在使用UNITY有两个脚本,我在unity写了两个C#脚本,一个是通过键盘鼠标控制视角的,另一个是通过鼠标拖拽移动物体的。但是当通过键盘鼠标控制视角的脚本运行之后,通过鼠标拖拽移动物体的脚本就很难起作用,具体表现为:键盘鼠标控制视角的脚本运行之后,多次点击并尝试拖拽物体失败,被拖拽物体不会有任何反应,这主要是因为代码无法准确识别点击的对象,常常会认为鼠标点击的是其它物体,例如物体下方的地板。代码如下,请各位不吝赐教:
// 通过键盘鼠标控制视角的脚本
using UnityEngine;
public class FirstPersonController : MonoBehaviour
{
public float moveSpeed = 5.0f;
public float lookSpeed = 2.0f;
public float lookXLimit = 45.0f;
private float rotationY;
private float rotationX;
private CharacterController controller;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
controller = GetComponent<
CharacterController>
();
}
void Update()
{
if (Input.GetMouseButton(0))
{
rotationX -= Input.GetAxis("
Mouse Y"
) * lookSpeed;
rotationY += Input.GetAxis("
Mouse X"
) * lookSpeed;
rotationX = Mathf.Clamp(rotationX, -lookXLimit, lookXLimit);
transform.localRotation = Quaternion.Euler(rotationX, rotationY, 0);
transform.GetChild(0).localRotation = Quaternion.Euler(0, rotationY, 0);
}
float moveX = Input.GetAxis("
Horizontal"
);
float moveZ = Input.GetAxis("
Vertical"
);
Vector3 moveDir = new Vector3(moveX, 0, moveZ).normalized;
moveDir = transform.TransformDirection(moveDir);
moveDir.y = 0;
controller.Move(moveDir * moveSpeed * Time.deltaTime);
}
}
// 通过鼠标拖拽移动物体的脚本
using UnityEngine;
public class DragObject : MonoBehaviour
{
private bool dragging = false;
private Vector3 screenPoint;
private Vector3 offset;
void OnMouseDown()
{
screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
dragging = true;
}
void OnMouseUp()
{
dragging = false;
}
void OnMouseDrag()
{
if (dragging)
{
Vector3 mousePosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
gameObject.transform.position = Camera.main.ScreenToWorldPoint(mousePosition) + offset;
}
}
}