Unity中简单的摄像机视角跟随鼠标转动而转动

本文提供了一个Unity摄像机跟随脚本,通过简单的代码实现摄像机根据鼠标输入平滑旋转的功能。用户只需将脚本拖入摄像机即可使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

没有废话直接上代码,直接拖入摄像机里即可使用

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Camerafollow : MonoBehaviour
{
    public float moveSpeed;
    // Start is called before the first frame update
    void Start()
    {
        moveSpeed = 60f; //移动速度
    }

    // Update is called once per frame
    void Update()
    {
        Vector3 angle = Vector3.zero;

        angle.x = transform.localEulerAngles.x - Input.GetAxis("Mouse Y") * moveSpeed * Time.deltaTime;
        angle.y = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * moveSpeed * Time.deltaTime;

        transform.localEulerAngles = angle;

      

    }
}
要实现Unity视角跟随鼠标转动,可以按照以下步骤进行: 1. 在Unity中创建一个摄像机,并将其放置在场景中。 2. 创建一个空物体,将其命名为“Player”,并将其放置在场景中。 3. 将摄像机作为“Player”的子对象,并将其位置设置为相对于“Player”对象的偏移量(例如,将其放置在“Player”对象的后方一定距离的位置)。 4. 编写脚本来控制摄像机旋转。在脚本中,使用Input.GetAxis函数获取鼠标移动的偏移量,并将其应用于摄像机旋转中。 以下是一个示例脚本: ```C# public class CameraController : MonoBehaviour { public Transform player; public float sensitivity = 5.0f; public float smoothing = 2.0f; private Vector2 smoothedVelocity; private Vector2 currentLookingPos; void Start() { Cursor.lockState = CursorLockMode.Locked; } void Update() { Vector2 inputValues = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y")); inputValues = Vector2.Scale(inputValues, new Vector2(sensitivity * smoothing, sensitivity * smoothing)); smoothedVelocity.x = Mathf.Lerp(smoothedVelocity.x, inputValues.x, 1f / smoothing); smoothedVelocity.y = Mathf.Lerp(smoothedVelocity.y, inputValues.y, 1f / smoothing); currentLookingPos += smoothedVelocity; transform.localRotation = Quaternion.AngleAxis(-currentLookingPos.y, Vector3.right); player.localRotation = Quaternion.AngleAxis(currentLookingPos.x, player.up); } } ``` 在这个脚本中,我们首先定义了一个“Player”对象,以及一些控制摄像机旋转的参数。在Start函数中,我们锁定了鼠标,这样它就不会离开游戏窗口。在Update函数中,我们使用Input.GetAxis函数获取鼠标移动的偏移量,并将其平滑处理,然后将其应用于摄像机旋转中。最后,我们使用Quaternion.AngleAxis函数来将旋转转换为四元数,并将其应用于摄像机和“Player”对象中。 如果一切正常,你现在应该能够在Unity中看到摄像机跟随鼠标转动了。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值