Unity3D 控制物体移动且自动旋转

控制物体移动

在这里插入图片描述

直接上代码(改脚本挂载到游戏物体上)

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

public class Move : MonoBehaviour
{
    
    
    private Vector3 move;  //移动方向
    private float movespeed = 3f;  //移动速度
    private float H, V; 
    // Start is called before the first frame update
    void Start()
    {
    
    
        move = new Vector3(0, 0, 0);
    }

    // Update is called once per frame
    void Update()
    {
    
    
        //获取按键信息
        H = Input.GetAxis("Horizontal");
        V = Input.GetAxis("Vertical");
        move.x = H;
        move.z = V;
        //获取摄像机朝向
        float y = Camera.main.transform.rotation.eulerAngles.y;
        move = Quaternion.Euler(0, y, 0) * move;
        if (H != 0 || V != 0)
        {
    
    
            //使物体移动
            transform.Translate(move * Time.deltaTime * movespeed, Space.World);
            //这一步是使物体移动时始终面向前方
            transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(0, y, 0), 0.05f);
        }
    }
}

控制摄像机移动的代码

第三人称摄像机移动

猜你喜欢

转载自blog.csdn.net/weixin_44099953/article/details/127806080