I want to rotate a sprite.
In a mesh I can specify a rotation (in radians, anticlockwise) as the fifth parameter in addRect. Is there an equivalent with sprite? I don’t think there is but maybe I’m missing something.
Instead, the code below gets the right answer, though I’m a little confused as to the need to take the negative of the angle. Also, is there a reason why the angles rotate anticlockwise rather than clockwise (I’m not aware of a coding convention either way, but if there is one I’d like to know). Finally @Simeon is there any reason for the use of degrees rather than radians in the rotate() function?
Code taken from step 8 of my snake tutorial
-- Snake tutorial
-- by West
--8. Add movement
function setup()
displayMode(FULLSCREEN)
supportedOrientations(LANDSCAPE_ANY)
x=300
y=500
angle=90
turning=2
speed=2.5 --a variable to hold the current speed of the snake
end
function draw()
background(40, 40, 50)
if CurrentTouch.state==BEGAN or CurrentTouch.state==MOVING then
if CurrentTouch.x<WIDTH/2 then
angle = angle + turning --use the turning variable
else
angle = angle - turning --use the turning variable
end
end
--change the x and y coordinates based on the current direction. The direction needs to be resolved into its x and y components using simple trigonometry. The variable speed will be used to control the magnitude of the components.
--math.sin is the sine function - I assume you know what this is - you should have learned trigonometry at school. If you are still at school - ask your teacher.
--in codea, the trig functions require the angles to be provided in radians not degrees. Fortunately there is an in built function to convert from degrees to radians called math.rad(). Again I will assume you know what radians are, but if you don't either use the function blindly or find out!
--Finally, the angle is negative. I'm not sure why but reckon it's linked back to the rotate function being anticlockwise
x = x + speed*math.sin(math.rad(-angle))
y = y + speed*math.cos(math.rad(-angle))
pushMatrix()
translate(x,y)
rotate(angle)
sprite("Space Art:Part Green Hull 4",0,0)
popMatrix()
end