Friday, June 3, 2016

2d - How can I make a sprite move in the direction it's facing using radians?


I am using PGELua for the PlaystationPortable. I would just like to know how to make a 2D sprite move in the direction that the sprite is facing.


When the sprite is blitted to the screen it should be heading down the y axis (like it's moving up the screen) but it doesn't appear to be working that way. As far as I am aware, the angles of the images use radians for the rotations.


I have this in a function


function FUNC_MOVE_SHIP(speed,angles)
VAR_SHIPX = VAR_SHIPX + pge.math.sin(angles) * speed
VAR_SHIPY = VAR_SHIPY + pge.math.cos(angles) * speed
end


and I call it in my main program like


    FUNC_ST_DR()
if pge.controls.held(PGE_CTRL_LEFT) then
VAR_SHIP_ANGLE=VAR_SHIP_ANGLE-0.01
elseif pge.controls.held(PGE_CTRL_RIGHT) then
VAR_SHIP_ANGLE=VAR_SHIP_ANGLE+0.01
end
FUNC_MOVE_SHIP(VAR_SHIP_SPEED,pge.math.rad(VAR_SHIP_ANGLE))
SHIP_11:activate()

SHIP_11:draweasy(VAR_SHIPX,VAR_SHIPY,pge.math.rad(VAR_SHIP_ANGLE))
FUNC_EN_DR()

Answer



A common problem with using radians is that they start to the right. Look at this picture (from Wikipedia):


radians/degrees


As you can see, it starts at 0 on the right of the circle and goes counter-clockwise around the circle until it hits 2 * PI. So if your sprite isn't pointing to the right with a rotation of 0, you might have to add some constant. Eg. if your sprite is pointing up, you have to add PI * 0.5 to the calculated angle. Also, instead of adding and subtracting 0.01 from the angle, I'd rather choose some fraction of PI instead. Eg. PI / 90 equals 2 degrees of rotation per update.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...