When the player clicks on an object, how do I make that object be forced away from them in the opposite direction?

Hi, as the title says, I want to force a game object away from the player in the way they are facing. I am using an FPS controller if this matters. This is probably a simple thing, but I’m new to Unity, and I can’t figure out how to do it. I don’t mind whether it is JavaScript or C#.

Another little side-question, is there a way to limit the distance the player can click on the object from?

Thanks in advance! :slight_smile:

you might want to check out this link:

https://docs.unity3d.com/ScriptReference/Rigidbody.AddExplosionForce.html

if you are new here,
there is a simple math pricipal to get direction between two points

you simply subtract the two Vector3 positions and the resulting vector3 represents direction!

you would simply use the result for the velocity or position of the object to be moved.
(pry want to normalize it and multiply by a speed variable first)

  1. the thing you want to push needs a collider and a rigidbody attached.

  2. you want to read and use the Script that is used here

  3. Understand every character in the Script

  4. Adapt the Script to this:

    RaycastHit hit;
    Ray ray = camera.ScreenPointToRay(Input.mousePosition);
    if (Physics.Raycast(ray, out hit)) {
    Rigidbody rigid = hit.rigidbody;
    rigid.AddForce(Camera.main.transform.forward * XXX);
    }

  5. Remember the object will always move in the Direction the Camera is looking

  6. if you want to limit the Player Reach, check this out and find maxDistance :wink: