object sucked towards object

Im trying to make it so that when i right click i shoot at objects and when i left click the object im aiming at gets sucked towards my players weapon and stays there and then im able to click and shoot the object. This is kinda a weird question so im having a hard time finding anything to help me.

So basically you want to make the gravity gun from half life 2.

What you need to do is use AddForce() on the rigid body you're pointing at (use a raycast for this) to move it towards your player(use look rotation to find the directing towards something). When it's within reach you can start manipulating its position directly to stay directly in front of you. To shoot it off just use AddForce() again but in the opposite direction and with a greater force.

If you wanted the attracting force to be distance relative you you can use this basic formula:

force = power/distance^2

With a maximum distance cut off point. The force an object experiences drops off rapidly the further away it is, like with gravity.


To keep something in front of the player with scripts you need to update the position of the object to match the player's position and then you add the forward vector of the player to keep it some distance in front of the player. For this you can use transform.TransformDirection()


var player : GameObject;
var distance : float = 1.0;

function update(){
   transform.position = player.transform.position + 

Hello! I have a resembling question, but I am a little stupid in codes…( Could you, please, explain how to use Force, Raycast and Look Rotation at greater length?

I created a script like this:

var target : Transform;

function Update () {

    var relativePos = target.position - transform.position;

    var rotation = Quaternion.LookRotation(relativePos);

    transform.rotation = rotation;


function FixedUpdate () {

    rigidbody.AddForce (Vector3.forward * 10);


But that doesn’t seem to work correct… And I don’t understand how to use Raycast with those two scripts, should this script be attached to the rigid body or to the camera?

Please forgive me those primitive questions. I would be very thankful if you could help! I can’t find an answer for that a very long time…

Yours respectfully, Stephan Rotar

I found a way to do that, using Vector3.Lerp and my player position. Here is the CODE:

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

function OnMouseOver() {
if (AttractOn == 1){
gameObject.tag = "AttractToPlayer";

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

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