Search code examples
c#unity-game-enginevelocitydirection

How do I set the velocity of an object in the direction of the game object?


I want my ball to teleport to another teleporter and launch itself out of it directly forwards, in the direction the teleporter is facing.

I transform the position of the ball and try and reset the velocity but the ball barely moves out of the teleporter

 ball.velocity = linkedTeleporter.transform.forward * ball.velocity;

Where linkedTeleporter is a game object and ball is a rigidbody


Solution

  • Assuming ball.velocity is a Vector3:

    ball.velocity = linkedTeleporter.transform.forward * ball.velocity.magnitude;
    

    Keep in mind that .forward is a reference to the blue Z-axis. If you're in a 2D game, you probably want .right (red X-axis)