我在unity写了两个C#脚本,一个是通过键盘鼠标控制移动的,另一个是通过鼠标拖拽移动物体的。但是当通过键盘鼠标控制移动的脚本运行之后,就无法在通过鼠标拖拽移动物体。Unity也没有报错。代码如下,请各位不吝赐教:
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;
}
}
}
```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(1))
{
rotationX -= Input.GetAxis("Mouse Y") * lookSpeed;/*rotationX-与rotationY+中的减号和加号决定鼠标移动方向最终朝向的视野*/
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);
}
}
```