Player push Object on mouse click

Hello! I have a small problem with pushing Objects from my FPS. I want my player to have three possibilities: drag objects (already enable in Unity), attract objects and push them (I mean moving objects from camera on mouse click).

For attracting objects I used Vector3.Lerp and used player position as the end point. That works fine, so I decided just to put “-” to make a pushing. But it didn’t work - the object is moving in a strange direction, but not from my player.

Here is the CODE:

var target : GameObject;
target = GameObject.Find ("Player");
var PushOn = 0;
var smooth = 1.0;

function OnMouseOver() {
if (PushOn == 1){
gameObject.tag = "PushFromPlayer";
}
}

function Update () {
if (Input.GetMouseButtonDown(1) && PushOn == 0){
PushOn = 1;
}
if (Input.GetMouseButtonUp(1) && PushOn == 1){
PushOn = 0;
}

if (gameObject.tag == "PushFromPlayer"){
transform.position = Vector3.Lerp(transform.position,-target.transform.position,Time.deltaTime*smooth);
}
}

Maybe I am wrong using this method for pushing objects and there is a simpler one?
Thank you very much!

First of all, when you want your objects to react with physics, you shouldn’t set the position of the objects manually. You should use AddForce with the correct direction vector.

The direction vector is pretty easy to calculate:

Vector3 dir = transform.position - target.transform.position;

You should normalize this vector to use it further on:

dir.Normalize();

With this new normalized vector, you have the direction vector between your target and the player. You can now use it to add force in both directions, giving you the possibility to push or pull the object.

This will push the object away from the player:

transform.rigidbody.AddForce(dir * forceIntensity * Time.deltaTime);

This will pull the object towards the player: (notice it’s just the negative direction vector)

transform.rigidbody.AddForce( - dir * forceIntensity * Time.deltaTime);

You should experiment more with this stuff, it’s pretty easy once you get the hang of it :wink:

Cheers