Page 1 of 1

How to make a bullet face the direction it was fired in...

Posted: Tue Apr 16, 2013 11:30 pm
by Ser_Mitch
Hey Guys,

I want to make a Realm of the Mad God-esque RPG (eventually), and I would like the melee attack sprite face the direction it was fired in.
Here is the bit of code which is giving me an issue (I think):

Code: Select all

function love.draw()

	local x1 = hero.x
	local y1 = hero.y
	local x2 = love.mouse.getX()
	local y2 = love.mouse.getY()

	local angle = math.deg(math.atan2(y2 - y1, x2 - x1)) 

	love.graphics.setColor(255, 255, 255)

	g.draw(hero.sprite, hero.x, hero.y)

	love.graphics.setColor(128, 128, 128)
   	
    	for i,v in ipairs(slash) do
        	g.draw(slash.sprite, v["x"], v["y"], angle)
   	end

end
Is it possible to make the angle argument a constant based off the x and y coordinates taken at the mouse click, rather than a variable that tracks the mouse position the whole time?

Thanks in advance guys :)

Re: How to make a bullet face the direction it was fired in.

Posted: Wed Apr 17, 2013 1:23 am
by Indefinity
One way that I can think of is to find the slope between the center of the image and the point at which you clicked. You can, from that, make a linear equation for it and plug in the X position (a constant x+1 per frame I'd guess or whatever you'd prefer) and set the Y from the equation.

Re: How to make a bullet face the direction it was fired in.

Posted: Wed Apr 17, 2013 5:43 am
by micha
Ser_Mitch wrote:

Code: Select all

function love.draw()

	local x1 = hero.x
	local y1 = hero.y
	local x2 = love.mouse.getX()
	local y2 = love.mouse.getY()

	local angle = math.deg(math.atan2(y2 - y1, x2 - x1)) 

	love.graphics.setColor(255, 255, 255)

	g.draw(hero.sprite, hero.x, hero.y)

	love.graphics.setColor(128, 128, 128)
   	
    	for i,v in ipairs(slash) do
        	g.draw(slash.sprite, v["x"], v["y"], angle)
   	end

end
Is it possible to make the angle argument a constant based off the x and y coordinates taken at the mouse click, rather than a variable that tracks the mouse position the whole time?
You somewhere have code to produce a new "slash" (this is where you assign x,y and velocity to each slash). There add the line for calculating the angle and then assign

Code: Select all

newslash.angle = ...
and in the draw() function you substitute your line for this one:

Code: Select all

g.draw(slash.sprite, v.x, v.y, v.angle)
In other words, add an angle to each slash.

By the way, you don't need the math.deg function. The angle calculated by atan2 is in radians and the angle needed by the drawing function also should be in radians. You'd only need the math.deg if you want to print the angle on screen in a human readable manner. Otherwise, always have it in radians.