1,Rigidbody
using UnityEngine;
public class Move : MonoBehaviour
{
public float moveSpeed = 1f;
public float rotateSpeed = 60f;
public float jumpVelocity = 5.0f;
private float vInput;
private float hInput;
private float JInput;
private Rigidbody _rb;
private bool _isGrounded;
void Start()
{
_rb = GetComponent<Rigidbody>();
}
void Update()
{
vInput = Input.GetAxis("Vertical") * moveSpeed;
hInput = Input.GetAxis("Horizontal") * moveSpeed;
if (Input.GetKeyDown(KeyCode.Space))
{
if (!_isGrounded)
{
JInput = jumpVelocity;
}
}
}
void FixedUpdate()
{
_rb.AddForce(Vector3.up * JInput, ForceMode.Impulse);
JInput = 0f;
if (Mathf.Abs(vInput) != 0 || Mathf.Abs(hInput) != 0)
{
_rb.MovePosition(this.transform.position + new Vector3(hInput * Time.fixedDeltaTime, 0, vInput * Time.fixedDeltaTime));
}
Vector3 rotation_V = new Vector3(vInput, 0, transform.position.x) * rotateSpeed;
Vector3 rotation_H = new Vector3(transform.position.z, 0, hInput) * rotateSpeed;
Quaternion angleRot_V = Quaternion.Euler(rotation_V * Time.fixedDeltaTime);
Quaternion angleRot_H = Quaternion.Euler(rotation_H * Time.fixedDeltaTime);
if (Mathf.Abs(vInput) != 0)
{
_rb.MoveRotation(_rb.rotation * angleRot_V);
}
if (Mathf.Abs(hInput) != 0)
{
_rb.MoveRotation(_rb.rotation * angleRot_H);
}
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag.Equals("Grounded"))
{
_isGrounded = false;
}
}
private void OnCollisionExit(Collision collision)
{
if (collision.gameObject.tag.Equals("Grounded"))
{
_isGrounded = true;
}
}
}
2,CharacterController
using UnityEngine;
public class Move : MonoBehaviour
{
private CharacterController controller;
private Vector3 Direction;
private Vector3 JumpDown;
private float vInput;
private float hInput;
private float moveSpeed = 1.5f;
private float jumpSpeed = 5f;
private float rotateSpeed = 180f;
private float jumpHeight = 7f;
private float Gravity = 18f;
void Start()
{
controller = GetComponent<CharacterController>();
Direction = Vector3.zero;
}
void Update()
{
if (controller.isGrounded)
{
vInput = Input.GetAxis("Vertical");
hInput = Input.GetAxis("Horizontal");
Direction = new Vector3(hInput, 0f, vInput);
Direction *= moveSpeed;
Vector3 rotation_V = Vector3.right * vInput * rotateSpeed * Time.deltaTime;
Vector3 rotation_H = Vector3.back * hInput * rotateSpeed * Time.deltaTime;
if (Mathf.Abs(vInput) != 0)
{
transform.Rotate(rotation_V, Space.World);
}
if (Mathf.Abs(hInput) != 0)
{
transform.Rotate(rotation_H, Space.World);
}
if (Input.GetKeyDown(KeyCode.Space))
{
JumpDown.y = jumpHeight;
}
}
else
{
JumpDown.y -= Gravity * Time.deltaTime;
}
controller.Move((Direction + JumpDown) * jumpSpeed * Time.deltaTime);
}
}