实现3D人物的移动和旋转。(Unity)

首先,需要在人物身上加刚体和碰撞器。

 如果需要人物身上有声音,可以添加AudioSource音频源。

 然后创建脚本,需要把脚本挂载到对应的对象身上。

如果有动画,还需要创建状态机添加到对应的对象上面,并且设置好里面的动画。

实现3D人物的移动和旋转。(Unity)_第1张图片

实现3D人物的移动和旋转。(Unity)_第2张图片


 代码实现:

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

public class PlayerMove : MonoBehaviour
{
    // Start is called before the first frame update

    //设置速度
    public float Speed = 6f;
    Rigidbody RigidbodyPlayer;
    Animator animatorPlayer;
    //偏移量
    Vector3 moveMent;
    //地板
    LayerMask floorMask;

    //Vector3 playerToMouse;

    void Awake()
    {
        //获取刚体
        RigidbodyPlayer = GetComponent();
        //获取动画
        animatorPlayer = GetComponent();
        //获取地板
        floorMask = LayerMask.GetMask("floor");
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        // -1  1
        float h = Input.GetAxisRaw("Horizontal");
        float v = Input.GetAxisRaw("Vertical");

        //移动 横向和纵向
        Move(h, v);

        //检测动画
        Animating(h, v);

        //角色旋转
        Turning();
    }
    void Move(float h, float v)
    {
        //设置方向
        moveMent.Set(h, 0f, v);
        moveMent = moveMent.normalized * Speed * Time.deltaTime;

        //通过刚体主键移动 对象
        RigidbodyPlayer.MovePosition(transform.position + moveMent);
    }
    void Animating(float h, float v)
    {
        if (h != 0 || v != 0)
        {
            animatorPlayer.SetBool("IsWaking", true);
        }
        else
        {
            animatorPlayer.SetBool("IsWaking", false);
        }
    }
    void Turning()
    {
        Ray cameraRay = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit cameraHit;
        if (Physics.Raycast(cameraRay, out cameraHit, 100f, floorMask))
        {
            Vector3 playerToMouse = cameraHit.point - transform.position;
            playerToMouse.y = 0f;
            //旋转 四元素
            Quaternion newQraternion = Quaternion.LookRotation(playerToMouse);

            //角色刚体旋转
            RigidbodyPlayer.MoveRotation(newQraternion);
        }
    }
}

图片实现:

 实现3D人物的移动和旋转。(Unity)_第3张图片

 

上面代码顺序不一样,可能会导致运行出错,如需要得进行完整性使用,才能保证项目正常运行。如出错请认真检查并且通过调整看看是否能达到效果。如有更好的方法,请在下方留言!谢谢你的观看!!!


----------------------------------------------------------END-----------------------------------------------------------------

 实现3D人物的移动和旋转。(Unity)_第4张图片

你可能感兴趣的:(Unity项目,unity,游戏引擎)