CharacterController
组件实现
Unity 设置
实现代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour
{
public float speed = 0.01f;
private CharacterController mController;
// Start is called before the first frame update
void Start()
{
}
public void Awake()
{
mController = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
if (h != 0 || v != 0)
{
Vector3 direction = new Vector3(h, 0, v);
mController.Move(direction * speed);
//transform.rotation = Quaternion.LookRotation(direction);
}
}
}
实现效果
RigidBody
组件实现
document: https://docs.unity.cn/cn/current/ScriptReference/Rigidbody.html
Unity 配置
实现代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class move_better : MonoBehaviour
{
public float speed = 3.0f;
private Rigidbody mRigidbody;
// Start is called before the first frame update
void Start()
{
mRigidbody = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
if (h != 0 || v != 0)
{
Vector3 direction = new Vector3(h, 0, v);
mRigidbody.velocity = direction * speed;
//transform.rotation = Quaternion.LookRotation(direction);
}
}
}