Movement of characters: use rigid body to control movement
Declare the speed and rigid body components of the character movement, use MovePosition()
to move the object to a new position, constant speed movement is suitable for frequent changes, it is recommended to use this, it is smoother
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{ public float speed=6;//The protagonist's moving speed private Rigidbody rb;//The rigid body component private float camLeagth = 100;//The length of the ray private LayerMask floorMask;//The number of layers on the ground //private int floorMask; private Animator anim;
private void Awake()
{ } void Start() { rb = GetComponent<Rigidbody>();//Get Rigidbody Component //floorMask =LayerMask.NameToLayer("Floor"); floorMask = LayerMask.GetMask("Floor"); anim = GetComponent<Animator>();//Get animation component }
// Update is called once per frame
void Update()
{
}
private void FixedUpdate()
{
PlayerMove();
Turn();
}
//移动
public void PlayerMove()
{
//左右移动
float horizontal = Input.GetAxis("Horizontal");
//前后移动
float vertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(horizontal, 0, vertical);
if(horizontal!=0||vertical!=0)
{
rb.MovePosition(transform.position + movement.normalized * speed * Time.deltaTime);
anim.SetBool("moveing", true);//Play move animation
}
else
{ anim.SetBool("moveing", false);//Play idle animation } //Do not use rigid body to control movement //if(Input.GetKey( KeyCode.W)) //{ // transform.Translate(Vector3.forward); //}
}
//Ray controls the direction of character rotation
public void Turn()
{ //Send a ray from the origin of the main camera to the position of the mouse Ray camRay = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; //If Ray detection is successful if(Physics.Raycast(camRay,out hit,camLeagth,floorMask)) { Debug.Log("ray"); //Steer according to the mouse position Vector3 playerMouse = hit.point - transform.position;//Vector Calculate rb.MoveRotation(Quaternion.LookRotation(playerMouse)); // //transform.LookAt(hit.point); } } }
Camera follow: use Unity smoothing function Lerp
lerp has three main parameters (commonly used)
lerp(initial state, target state, OneExecutePer )
OneExecutePer: How close is each execution (if it is 1, it means that the goal will be reached after one execution)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraMove : MonoBehaviour
{
public Transform player;//主角
Vector3 pos;
private float smooth=3;//平滑值
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
pos.x = player.position.x + 1;
pos.y = player.position.y + 5;
pos.z = player.position.z - 5;
//transform.position = pos;//没有平滑
transform.position = Vector3.Lerp(transform.position, pos, smooth * Time.deltaTime);
}
}