How to I get a rotated sprite to move left or right?
Posted
by
rphello101
on Game Development
See other posts from Game Development
or by rphello101
Published on 2012-10-02T22:26:16Z
Indexed on
2012/10/03
3:51 UTC
Read the original article
Hit count: 382
Using Java/Slick 2D, I'm using the mouse to rotate a sprite on the screen and the directional keys (in this case, WASD) to move the spite. Forwards and backwards is easy, just position += cos(ang)*speed or position -= cos(ang)*speed. But how do I get the sprite to move left or right? I'm thinking it has something to do with adding 90 degrees to the angle or something. Any ideas?
Rotation code:
int mX = Mouse.getX();
int mY = HEIGHT - Mouse.getY();
int pX = sprite.x+sprite.image.getWidth()/2;
int pY = sprite.y+sprite.image.getHeight()/2;
double mAng;
if(mX!=pX){
mAng = Math.toDegrees(Math.atan2(mY - pY, mX - pX));
if(mAng==0 && mX<=pX)
mAng=180;
}
else{
if(mY>pY)
mAng=90;
else
mAng=270;
}
sprite.angle = mAng;
sprite.image.setRotation((float) mAng);
And the movement code (delta is change in time):
Input input = gc.getInput();
Vector2f direction = new Vector2f();
Vector2f velocity = new Vector2f();
direction.x = (float) Math.cos(Math.toRadians(sprite.angle));
direction.y = (float) Math.sin(Math.toRadians(sprite.angle));
if(direction.length()>0)
direction = direction.normalise(); //On a separate note, what does this line of code do?
velocity.x = (float) (direction.x * sprite.moveSpeed);
velocity.y = (float) (direction.y * sprite.moveSpeed);
if(input.isKeyDown(sprite.up)){
sprite.x += velocity.x*delta;
sprite.y += velocity.y*delta;
}if (input.isKeyDown(sprite.down)){
sprite.x -= velocity.x*delta;
sprite.y -= velocity.y*delta;
}if (input.isKeyDown(sprite.left)){
//???
}if (input.isKeyDown(sprite.right)){
//???
}
© Game Development or respective owner