Move to click not working

hey guys, what did i miss? there isn’t any force added when i click and the raycast is definitely showing up in the log.

using UnityEngine;

public class ClickMovement : MonoBehaviour
{
    public Rigidbody _rigidbody;
    public LayerMask clickMask;
    [SerializeField] private float moveSpeed = 1000f;

    public void FixedUpdate()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            bool hitSomething = Physics.Raycast(ray, out RaycastHit hitInfo);

            if (hitSomething)
            {
                Vector3 clickedWorldPoint = hitInfo.point;
                _rigidbody.AddForce(Vector3.MoveTowards(transform.position, clickedWorldPoint, moveSpeed * Time.deltaTime));
                Debug.Log(clickedWorldPoint);
            }
        }
    }
}

cheers

it’s very strange to use Vector3.MoveTowards to pick a direction to add a force in. I think what you actually want is the direction from your transform to the clicked world point. That would be calculated as:

(clickedWorldPoint - transform.position).normalized

Another problem is that it’s usually not appropriate to call Rigidbody.AddForce in a function that is not FixedUpdate.

Third problem - you’re only applying the force once, and it usually makes sense to apply a force over a period of time across many FixedUpdate calls. Remember it’s adding a force, not directly setting a velocity. It’s just a small push in a direction.

1 Like

Blue! i <3 u. it works.

thanks for pointing out those problems too! ill look into those rn :3

for the FixedUpdate problem-- how do i make “clickedWorldPoint” available out of its context? i changed the access modifier of void ReadInput to public/protected but its still a missing variable in the Move() function.

    public void Update()
    {
        ReadInput();
    }

    public void ReadInput()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            bool hitSomething = Physics.Raycast(ray, out RaycastHit hitInfo);

            if (hitSomething)
            {
                Vector3 clickedWorldPoint = hitInfo.point;
                //_rigidbody.AddForce((clickedWorldPoint - transform.position).normalized * _moveSpeed);

                Debug.Log(clickedWorldPoint);
            }
        }
    }

    void FixedUpdate()
    {
        Move();
    }

    private void Move()
    {
        _rigidbody.AddForce((clickedWorldPoint - transform.position).normalized * _moveSpeed);
    }
}