Saad Khawaja Menu

Permalink:

Move Object with Mouse

Move a 3D Object with Mouse – and make it collide

A basic problem that many Unity developers face is that they use Transform.Translate or update Transform.position of an object and expect it to collide with other objects.

This is not the case. When you’re using Transform.Translate or Transform.Position, you’re essentially just teleporting the object to that position. Hence, there will be no collision with intersecting objects.

Fortunately, Unity has provided a function rigidbody.MovePosition which takes care of this. The snippet below moves a 3D object (on which it is attached) with the mouse and collides with all objects that come in its way.


using UnityEngine;
using System.Collections;

public class MoveWithMouse : MonoBehaviour {



	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
	

		Vector3 v3 = Input.mousePosition;
		v3.z = 10.0f;
		v3 = Camera.main.ScreenToWorldPoint(v3);

		Debug.Log(v3); //Current Position of mouse in world space

		this.gameObject.rigidbody.MovePosition(v3);

	}



}
  • Melvin

    Awesome just what I needed! One question though, I’m doing this for a 2D Air Hockey game. I got the code to work, but when my paddle goes real quickly against the puck, then it goes through the puck. I tried this code in both FixedUpdate() and Update(). This is probably the case, because the move happens so quick, that the Unity engine does not check for collision in that fast mouse movement. I’m currently thinking of ways how to fix this, but perhaps you have a good idea for this?

  • qwertyuiopasdfghjklzxcvbnm

    on your rigidbody, change collision detection to continuous instead of discrete

  • Thanks for leaving a comment, please keep it clean. HTML allowed is strong, code and a href.