Move object along ray cast

Hi,

I want to move an object along a ray gradually,

I have the following code so far which moves it in 1 frame to the destination rather than smoothly gliding there.

If I remove the Destroy(projectile.rigidbody2D) line from the end it sort of does it but then bounces around all over the place?

Any help would be much appreciated!

		void Update () 
	{

				if (Input.GetMouseButtonUp (1)) {
				if (Hand.transform.childCount == 1){
				projectile.gameObject.transform.parent = null;

				Ray ray = new Ray(spawn.position,spawn.up);
				RaycastHit hit;
				
				float shotDistance = shotdistance;
				
				if (Physics.Raycast(ray,out hit, shotDistance)) {
					shotDistance = hit.distance;
				}
				projectile.AddComponent<Rigidbody2D>();
				projectile.rigidbody2D.gravityScale = 0;
				projectile.rigidbody2D.AddForce(Vector2.up * 5);
				projectile.transform.position = Vector3.MoveTowards(projectile.transform.position,ray.direction * shotDistance,shotDistance);
				Debug.DrawRay(ray.origin,ray.direction * shotDistance,Color.red,1);
				Destroy(projectile.rigidbody2D);

								}
						}
				}

Many Thanks,

I think the problem is there is with the 3rd parameter you’re passing into Vector3.MoveTowards(). Instead of using shotDistance, try to implement something like this and see if it fixes it?

public float speed;
    void Update() {
        float step = speed * Time.deltaTime;
        transform.position = Vector3.MoveTowards(transform.position, target.position, step);

Hope this helps :slight_smile: