Sunday, January 21, 2018

java - How can I move a sprite in the direction it is facing?


I'm using Java/Slick 2D. I'm trying to use the mouse to rotate the sprite and the arrow keys to move the sprite. I can get the sprite to rotate no problem, but I cannot get it to move in the direction it is supposed to. When I hit "forwards", the sprite doesn't necessarily move towards the mouse. Actually, it will only move towards the left of the screen really. I'm sure there has to be some standard code for this since many games use this style of motion. Can anyone help me out with what the trig is supposed to be? Thanks


EDIT: Here is the rotation code (which does something else weird: https://stackoverflow.com/questions/12610320/why-is-my-image-rotating-off-center)


int mX = Mouse.getX();
int mY = HEIGHT - Mouse.getY();
int pX = sprite.x;

int pY = sprite.y;
int tempY, tempX;
double mAng, pAng = sprite.angle;
double angRotate=0;

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. I can only move towards the left of the screen...


double ang = sprite.angle;
Input input = gc.getInput();

if(input.isKeyDown(sprite.up)){
sprite.x += Math.cos(ang)*sprite.moveSpeed;
sprite.y += Math.sin(ang)*sprite.moveSpeed;
}if (input.isKeyDown(sprite.down)){
sprite.x += -1*Math.cos(ang*Math.PI/180)*sprite.moveSpeed;
sprite.y += -1*Math.sin(ang*Math.PI/180)*sprite.moveSpeed;

}if (input.isKeyDown(sprite.left)){
sprite.x -= Math.cos(ang*Math.PI/180)*sprite.moveSpeed;
sprite.y += Math.sin(ang*Math.PI/180)*sprite.moveSpeed;
}if (input.isKeyDown(sprite.right)){
sprite.x += Math.cos(ang*Math.PI/180)*sprite.moveSpeed;
sprite.y -= Math.sin(ang*Math.PI/180)*sprite.moveSpeed;
}

Answer



You'll want to get a vector based on your current velocity and heading. Then use that vector to increment your position.


//first get the direction the entity is pointed

direction.x = (float) Math.cos(Math.toRadians(rotation));
direction.y = (float) Math.sin(Math.toRadians(rotation));
if (direction.length() > 0) {
direction = direction.normalise();
}
//Then scale it by the current speed to get the velocity
velocity.x = direction.x * speed;
velocity.y = direction.y * speed;

So now you know your velocity based on your rotation. You can the update your position with that information.



//Update the position based on our current speed
//This is basic s = vt physics
position.x += velocity.x * timeElapsed;
position.y += velocity.y * timeElapsed;

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...