要通過鼠標(biāo)控制并模擬人物移動和轉(zhuǎn)換視角,將會使用射線檢測、鼠標(biāo)點擊和鼠標(biāo)水平移動,配合物體旋轉(zhuǎn)和移動方法共同實現(xiàn)。
首先搭建個由一個Plane地板和若干cube組成的簡單場景:
其次創(chuàng)建一個Capsule作為移動物體,并把攝像頭拉到該物體中。
創(chuàng)建以下腳本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour
{
private Vector3 targetPosition; // 目標(biāo)位置
private float moveSpeed = 5f; // 攝像頭移動速度
private bool isMoving = false; // 標(biāo)記物體是否正在移動
public float rotateSpeed = 3f; // 攝像頭旋轉(zhuǎn)速度
public void Update()
{
if (Input.GetMouseButton(0))
{
//視角旋轉(zhuǎn)
transform.Rotate(Vector3.up, Input.GetAxis("Mouse X") * rotateSpeed);
//檢測射線獲取目標(biāo)點
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo = new RaycastHit();
if (Physics.Raycast(ray, out hitInfo))
{
if (hitInfo.collider.name == "Ground")
{
targetPosition = hitInfo.point;
targetPosition.y = transform.localPosition.y;
isMoving = true;
}
Debug.DrawLine(ray.origin, hitInfo.point, Color.blue);
}
//讓物體移動到目標(biāo)位置
if (isMoving)
{
MoveObject();
}
}
}
private void MoveObject()
{
// 使用插值函數(shù)逐漸將物體移動到目標(biāo)位置
transform.position = Vector3.MoveTowards(transform.position, targetPosition, moveSpeed * Time.deltaTime);
// 檢查是否到達(dá)目標(biāo)位置
if (transform.position == targetPosition)
{
isMoving = false;
}
}
}
?把腳本拉到移動物體中就可以了。
實際效果如下:文章來源:http://www.zghlxwxcb.cn/news/detail-778091.html
Unity鼠標(biāo)模擬人物走動轉(zhuǎn)換視覺文章來源地址http://www.zghlxwxcb.cn/news/detail-778091.html
到了這里,關(guān)于Unity 通過鼠標(biāo)控制模擬人物移動和旋轉(zhuǎn)視角的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!