Followers

Monday, May 23, 2011

Creating a Smooth Moving Character with a Maximum Speed

Everyone knows that in a game, we can have a character set their position to our finger position, but what if we don't want that character to be able to "teleport" if the player picks up their finger and moves it to another end of the screen. That's what I will be showing using AndEngine (as that's what my current project is using) but the concept can be extended to any other platform, language, etc.

 //** 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