//** moveTo function - takes a destination in, and moves the ship sprite towards the destination **//
@Override
public void moveTo(Vector2 dest)
{
//This makes it so that when a finger is still, the ship doesn't "vibrate"
//Currently I am only moving along the y axis, so for 2D movement you'd have to impliment "& dest.x >= this.getX() + 5 || dest.x <= this.getX() - 5" after
if(dest.y >= this.getY() + 5 || dest.y <= this.getY() - 5)
{
//Finds the difference between the current position
Vector2 distance = new Vector2(dest.x - current.x, dest.y - current.y);
//Normalizes the vector
Vector2 direction = distance.nor();
//Multiplies the normalize vector by the max speed to set the speed
currentSpeed = direction.mul(maxSpeed);
}
else
{
//else we make sure the ship isn't moving
stop();
}
}
@Override
public int update()
{
//moves the ship, pretty standard stuff
this.current.x += currentSpeed.x;
this.current.y += currentSpeed.y;
//sets the position of the sprite
this.setPosition(this.current.x, this.current.y);
//this is for my sprite work as I'm dealing with a tiled sprite, so it looks like it tilts when it moves
if(currentSpeed.y >= 1)
return 3;
else if(currentSpeed.y < -1)
return 2;
else
return 1;
}
public void stop()
{
//sets the speed to 0
this.currentSpeed.x = 0;
this.currentSpeed.y = 0;
}
In implementing you do need a little more code:
// Deal with touch events
scene.setOnSceneTouchListener(new IOnSceneTouchListener() {
@Override
public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) {
if (pSceneTouchEvent.getAction() != TouchEvent.ACTION_UP) {
playerShip.moveTo(new Vector2(playerShip.getX(), Math.round(pSceneTouchEvent.getY())));
return true;
}
else
{
playerShip.stop();
return false;
}
}});
You need to make sure that the character stops when the player releases their finger (as well you need to update the ship using the update method in an update handler. Hope this helps! If you have any questions feel free to leave a comment.
No comments:
Post a Comment