I am aware that version conflicting may have something to do with this, but I’m not entirely sure. I am using code from this website:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GroundPlacementController : MonoBehaviour
{
[SerializeField]
private GameObject placeableObjectPrefab;
[SerializeField]
private KeyCode newObjectHotkey = KeyCode.A;
private GameObject currentPlaceableObject;
private float mouseWheelRotation;
private void Update()
{
HandleNewObjectHotkey();
if (currentPlaceableObject != null)
{
MoveCurrentObjectToMouse();
RotateFromMouseWheel();
ReleaseIfClicked();
}
}
private void HandleNewObjectHotkey()
{
if (Input.GetKeyDown(newObjectHotkey))
{
if (currentPlaceableObject != null)
{
Destroy(currentPlaceableObject);
}
else
{
currentPlaceableObject = Instantiate(placeableObjectPrefab);
}
}
}
private void MoveCurrentObjectToMouse()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition /* + (Vector3.up * 10)*/);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo))
{
currentPlaceableObject.transform.position = hitInfo.point;
currentPlaceableObject.transform.rotation = Quaternion.FromToRotation(Vector3.up, hitInfo.normal); // stop rotation
}
}
private void RotateFromMouseWheel()
{
Debug.Log(Input.mouseScrollDelta);
mouseWheelRotation += Input.mouseScrollDelta.y;
currentPlaceableObject.transform.Rotate(Vector3.up, mouseWheelRotation * 10f);
}
private void ReleaseIfClicked()
{
if (Input.GetMouseButtonDown(0))
{
currentPlaceableObject = null;
}
}
}
I presume the website is using an older version of Unity3D than mine (I’m working with 2019.2.5f1) and that may factor into it, but I’m not sure.
When I use this script, the behaviour in the attached image occurs. The accompanying YouTube video on the website I got the code from does not have that issue, and that is something I wish to replicate.
So far, my workaround is to modify the MoveCurrentObjectToMouse()
function, so that currentPlaceableObject.transform.position = hitInfo.point + (Vector3.forward * 1);
. This helps prevent the sphere from moving closer to the camera, but this does mean that object placement is less intuitive. I wonder what solutions you are able to provide.