- Home /
[2D] How to move an object along a Raycast and over a set period of time?
Hi, sorry for the long title. I am making a 2D bullet hell game, and I got stuck on how to make the bullets move towards the player. I already set up a raycast that makes the enemy AIM the bullet towards the player, and I tried using a rigidbody to MOVE the bullet towards the player, like this:
//Moving the new bullet: bulletRigidbody.AddRelativeForce(raycastDir * speed); // raycastDir is the "position of the player - position of the bullet", which is the distance between them, I think. // bulletRigidbody is the RigidBody2D component that is attached to the bullet. // speed is a float that represents the amount of time it takes for the bullet to reach the player. // My goal is to move the bullet to the player, over a fixed time period.
However, when I test it, the bullets are floating uncontrollably in the air, slightly going towards the player. It is also important to note that each enemy spawns a bullet and targets it at the player once every 3 seconds. Every single bullet after the first is slightly faster than the previous. I do not know how to fix this. It's either there's something wrong with the Rigidbody2D settings, OR using a RigidBody2D may not be the best approach. Any help is greatly appreciated, Thanks in advance!
Here are my RigidBody2D component settings, if it helps:
Answer by logicandchaos · Jul 16, 2021 at 06:51 PM
Well I would get the direction of the ray, you can get it by subtracting 2 points and normalizing the vector, then use that to move your object using a coroutine or a tween asset. Actually if you are using rigidbodies you should be able to take that direction vector and multiply by speed then set to its velocity.
rb.velocity = direction * speed * Time.deltaTime;
Your answer
![](https://koobas.hobune.stream/wayback/20220613040415im_/https://answers.unity.com/themes/thub/images/avi.jpg)