Unity 简单的人物移动

第三人称:

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

public class PlayerController : MonoBehaviour
{
    private CharacterController controller;
    private Animator animator;

    [SerializeField] float moveSpeed;
    [SerializeField] float runSpeed;

    [Header("运动速度太小,放大一定的倍数播放动画")]
    [SerializeField] float moveSpeedMagnification;
    [SerializeField] float runSpeedMagnification;

    float _moveSpeed;
    float _moveSpeedMagnification;

    void Start()
    {
        controller = GetComponent<CharacterController>();
        animator = GetComponentInChildren<Animator>();
    }

    void Update()
    {
        MovePlayer();
    }

    void MovePlayer()
    {
        float horizontal = Input.GetAxisRaw("Horizontal");
        float vertical = Input.GetAxisRaw("Vertical");

        if (Input.GetKey(KeyCode.LeftShift))
        {
            _moveSpeed = runSpeed;
            _moveSpeedMagnification = runSpeedMagnification;
        }
        else 
        {
            _moveSpeed = moveSpeed;
            _moveSpeedMagnification = moveSpeedMagnification;
        }

        Vector3 dir = new Vector3(horizontal,0,vertical).normalized;
        Vector3 velocity = _moveSpeed * Time.deltaTime * dir;

        if (dir.magnitude >= 0.1f)
        {
            transform.rotation = Quaternion.LookRotation(dir);
            controller.Move(velocity);
        }
        animator.SetFloat("Speed", velocity.magnitude * _moveSpeedMagnification);
    }
}

第一人称:

 void Update()
    {
        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");

        Vector3 dir = new Vector3(h, 0, v).normalized;
        Vector3 velocity = 2 * Time.deltaTime * dir;

        transform.localEulerAngles += Vector3.up * h * 30f * Time.deltaTime;

        transform.Translate(velocity);

        if (Input.GetKey(KeyCode.Z))
        {
            transform.position -= Vector3.up * Time.deltaTime * 2;
        }

        if (Input.GetKey(KeyCode.X))
        {
            transform.position += Vector3.up * Time.deltaTime * 2;
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值