Showing posts with label Mouse Click. Show all posts
Showing posts with label Mouse Click. Show all posts

Unity Move Object to Mouse Click Position

Unity Move Object to Mouse Click Position

No matter 2D or 3D, we use same method to move an object to mouse click position. We need to get mouse click position on ground or whatever, and move object to this position. Create a plane and a cube. We will move cube to any position on plane with mouse click. We get the mouse click position with Raycast.

public GameObject cube;
 Vector3 targetPosition;
 
 void Start () {
 
  targetPosition = transform.position;
 }
 void Update(){
 
  if (Input.GetMouseButtonDown(0)){
   Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
   RaycastHit hit;
 
   if (Physics.Raycast(ray, out hit)){
    targetPosition = hit.point;
    cube.transform.position = targetPosition;
   }
  }
 }

Attach this code to plane and assign a cube as public game object. Now, press play and test it. Click anywhere on plane and see cube moving.

Unity Move Object to Mouse Click Position

Unity Mouse Click on Game Object

Unity Mouse Click on Game Object

There are two ways to perform click function on a game object:

1- Create and attach a script to the target object. Write this function in it.
void OnMouseDown()
{
 Destroy(gameObject);
}

2- You can use Physics.Raycast to detect target with ray. You must write this code in script which is attached to camera. Be careful, this code works ONLY if the object in scene has collider.
void Update()
{
 if (Input.GetMouseButtonDown(0)){
  Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
  RaycastHit hit;
  if (Physics.Raycast(ray, out hit)){
   Destroy(hit.transform.gameObject);
  }
 }
}

Unity Mouse Click on Game Object