0
votes

I build my first game and want to Instantiate an object, the player should be allowed to choose where to instantiate it. It should be on the ground(plane) and the object(cube) should follow the mousePos. That's where the problem occurs. I tried for hours now (at least 5) but can't figure it out. I tried raycast and screentoWorld stuff, but the object doesn't follow my mouse perfectly. The best i could get is, if i moved right, the cube moved right, same for all the other directions but it did not move the same speed as my mouse, so it was not at the same pos and i can't "OnMouseDown" it(except for the very middle of the screen) I use an Orthographic Camera, the speed the Cube is moving with the mouse seems to be dependent on my camera Size, but I want it to work in any size etc. Thanks for any help in advance.

This is my code:

using UnityEngine;
using System;

public class VorKasernenBau : MonoBehaviour
{
    public static event Action<Vector3> onBuildBuilding;
    public Camera cam;
    public GameObject kasernePrefab;

    private void Update()
    {
       moveMe();
    }
    private void OnMouseDown()
    {
        if (true/*if genug platz*/)
        {
            Instantiate(kasernePrefab, transform.position, Quaternion.identity, transform.parent);
            if (onBuildBuilding != null)
                onBuildBuilding.Invoke(transform.position);
            Destroy(gameObject);
        }
    }
    private void moveMe()
    {
        Ray ray = cam.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit))
        {
            if (hit.collider.CompareTag("Ground"))
            {
                transform.position = hit.point + Vector3.up;
                Debug.Log("test");
            }
        }
    }
}

Update1: The z Position seems to be okay, but the xPos isn't following perfectly.

1
I'd recommend you use Debug.DrawRay(ray.origin, ray.direction); and see if it goes in the direction you expect and hits at the position you think it shouldderHugo

1 Answers

0
votes

I moved the object with another function. (cam.screentoworld and y value to 1) This problem is solved(even known i am not really happy with this solution), but another problem comes with it. if i move the screen in play mode (through drag and drop), the mousePos is not calculated right since the calculated mousepos isn't translated like the screen. Anyways have a great night and thanks for the help.

    Vector3 pos = cam.ScreenToWorldPoint(Input.mousePosition);
    transform.position = new Vector3(pos.x,1,pos.z);