Instantiate gameobject on mouseclick from the top down perspective

Updated on June 24, 2019 in General
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
3 on June 24, 2019

Hi, I’m making a 3d top down game and I want my character instantiate gameobject on mouse click.

The problem is that when I create a game object the gameobject is not created in the position I want, the object is created in the air and not in surface of the floor. This is the code:

Game Object in scene:

 

Game Object in game:

This is the code:

  
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 public class InstantiateCube : MonoBehaviour
 {
 public GameObjectcube;
 // Start is called before the first frame update
  
  
 publicvoidSpawn(Vector3position){
 Instantiate(cube).transform.position = position;
 }
 // Update is called once per frame
 voidUpdate()
 {
  
 if(Input.GetKeyDown(KeyCode.Mouse0)){
 Vector3 worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition,Camera.MonoOrStereoscopicEye.Mono);
 Vector3 adjustZ = new Vector3(worldPoint.x,worldPoint.y,cube.transform.position.z);
 Spawn(adjustZ);
 }
 }
 }
  • Liked by
Reply
2 on June 24, 2019

Instead of using ScreenToWorldPoint, use ScreenPointToRay, and raycast down to the ground.

Unity docs on ScreenPointToRay here: https://docs.unity3d.com/Manual/CameraRays.html

on June 24, 2019

Ok that worked,thanks.  I have another problem. When I instantiate a new object some objects overlap others. How I fix that?

using System.Collections;
using System.Collections.Generic;
using UnityEngine; 
 public class testclick : MonoBehaviour {
// Start is called before the first frame update
publicGameObjectcube;
// Start is called before the first frame update
RaymyRay; 
 RaycastHit hit; 
 // Update is called once per frame
voidUpdate() {  
myRay = Camera.main.ScreenPointToRay(Input.mousePosition); 
 if(Physics.Raycast(myRay,out hit)){ 
 if(Input.GetMouseButtonDown(0)){
 Instantiate (cube,hit.point,Quaternion.identity); 
 } 
 } 
 } }

 

 

 

Wise
on June 24, 2019

You need to move it out of the existing object after you instantiate it, or you could use SphereCast instead of Raycast, and check if the area is available before placing the object.

 

SphereCast docs here:

https://docs.unity3d.com/ScriptReference/Physics.SphereCast.html

Show more replies
  • Liked by
Reply
Cancel