Jump to content

How to change an object's speed, but not direction


ylluminarious
 Share

Recommended Posts

How do you change the speed of an object in phaser without changing its direction?  For example, I have a ball that collides against a moving platform.  I want the ball to change direction, but not gain any additional speed from the collision against a moving side of the platform. Up to now I have had to take the sign of the velocities of the object and then reapply a constant value speed to it on collision, but that seems quite wrong for a library as robust as Phaser is.

 

How do you modify speed and direction independently outside of velocity?

Link to comment
Share on other sites

I don't know if there is a better way, but what I usually do is to have a predefined speed, then look at the angle of the object, and apply something like:

 

object.velocity.x += speed * Math.sin(object.angle);

object.velocity.y += speed * Math.cos(object.angle);

 

There also seems to be (at least in Arcade physics) a body.velocityFromAngle() method, which seems to more or less do something similar. and might be what you need.

Link to comment
Share on other sites

That's unfortunate.  I have done it similar to @Qqwy, for example, I would take the `Math.sign(object.body.velocity.x)` and then assign the speed manually to that while reassigning the direction (`sign`). While it works, it seems that there should be a more direct way to modify just speed of the direction vectors without these extra steps.

 

Here's an example of when I used it in `game.physics.arcade.collide`:

 

game.physics.arcade.collide(object1, object2, function () {  direction_x = Math.sign(object1.body.velocity.x);  direction_y = Math.sign(object1.body.velocity.y);  object1.body.velocity.x = OBJECT1_VELOCITY * direction_x; //Where OBJECT1_VELOCITY is a constant  object1.body.velocity.y = OBJECT1_VELOCITY * direction_y;});
 

Obviously the example is for a very simple motion that does not take into consideration angles, etc, but it works in my case. I too was hoping to see other input that would show a clearer way to just modify speed while retaining the other vector data of the velocity. I can't imagine phaser not having this and that we're just missing something relatively simple in the library...

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...