Unity3D 人物移动控制

  1. 加刚体(RigidBody) 设置 y方向锁定位置
  2. 拖拽脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RemController : MonoBehaviour {

    Vector3 movement;
    Rigidbody playerRigidbody;

    private float speed = 6f;
    private int rotSspeed = 100;


    void Awake()
    {
        playerRigidbody = GetComponent();
    }

    // 不受fps影响 因为是按一定时间间隔更新
    void FixedUpdate()
    {
        float h = Input.GetAxisRaw("Horizontal");
        float v = Input.GetAxisRaw("Vertical");

        movement.Set(h, 0f, v);
        movement = movement.normalized * speed * Time.deltaTime;
        // 移动到指定位置
        playerRigidbody.MovePosition(transform.position + movement);
    }
}

只需要控制方向的移动:

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

public class RemController : MonoBehaviour {

    Vector3 movement;
    Rigidbody playerRigidbody;

    private float speed = 6f;
    public int rotSspeed = 100;


    void Awake()
    {
        playerRigidbody = GetComponent();
    }

    // 不受fps影响 因为是按一定时间间隔更新
    void FixedUpdate()
    {
        float h = Input.GetAxisRaw("Horizontal");
        float v = Input.GetAxisRaw("Vertical");

        //movement.Set(h, 0f, v);
        //movement = movement.normalized * speed * Time.deltaTime;
        //// 移动到指定位置
        //playerRigidbody.MovePosition(transform.position + movement);
        transform.position += transform.forward * speed * Time.deltaTime;

        if (Input.GetKey(KeyCode.A))
        {
            transform.Rotate(Vector3.up * Time.deltaTime * -rotSspeed);
        }
        if (Input.GetKey(KeyCode.D))
        {
            transform.Rotate(Vector3.up * Time.deltaTime * +rotSspeed);
        }
    }
}

你可能感兴趣的:(unity3d)