Why does my game objects position keep getting closer and closer?

Fix: Read AnimalMan’s answer

I’m making a drag and drop system for my game, but when I drag the object it constantly gets closer to the camera until it teleports back to where it should be and repeats the process. I’m doing all this in 3D just so you know.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class DragAndDrop : MonoBehaviour
{
    [SerializeField] private Button placeRockWall;
    [SerializeField] private GameObject[] defenses;
    [SerializeField] private GameObject shopUI;
    [SerializeField] private Camera cam;
    private enum Structures {none, rockWall};
    private Structures structures = new Structures();
    private GameObject rockWallCopy;
    [SerializeField] private Transform buildings;

    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            if (EventSystem.current.currentSelectedGameObject.CompareTag("Place Rock Wall") && structures == Structures.none)
            {
                Place(defenses[0], Structures.rockWall);
            }
        }

        if (Input.GetMouseButtonUp(0) && structures != Structures.none)
        {
            shopUI.SetActive(true);                                                                                                                                           
            structures = Structures.none;
        }
    }

    void LateUpdate()
    {
        if (structures == Structures.rockWall)
        {
            Ray ray = cam.ScreenPointToRay(Input.mousePosition);

            if (Physics.Raycast(ray, out RaycastHit raycastHit))
            {
                rockWallCopy.transform.position = raycastHit.point;
            }
        }
     
    }

    void Place(GameObject objectToPlace, Structures whatObjectIs)
    {
        Debug.Log("Placing");
        shopUI.SetActive(false);

        if (whatObjectIs == Structures.rockWall)
        {
            Debug.Log("Object is rock wall, instantiating copy");
            rockWallCopy = Instantiate(defenses[0], buildings);
        }

        structures = whatObjectIs;
    }
}

So as the object moves in front of the raycast it updates its position to be closer to the camera because - the raycast is hitting the object you are dragging so it is returning a closer and closer position because you are dragging and centerint the object where your raycast is searching for objects

So,

you’ll have to disable collision on the object OR change the layer of the object to a layer that will not register a raycast hit. OR stop raycasting when an object is selected

1 Like