人物的移动:用刚体控制移动
声明角色移动的速度和刚体组件,用MovePosition()
让物体移动到新的位置position,恒速移动适用于频繁改变,推荐使用这种,较为平滑
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public float speed=6;//主角移动速度
private Rigidbody rb;//刚体组件
private float camLeagth = 100;//射线的长度
private LayerMask floorMask;//地面的层级数
//private int floorMask;
private Animator anim;
private void Awake()
{
}
void Start()
{
rb = GetComponent<Rigidbody>();//获取刚体组件
//floorMask =LayerMask.NameToLayer("Floor");
floorMask = LayerMask.GetMask("Floor");
anim = GetComponent<Animator>();//获取动画组件
}
// 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);//播放move动画
}
else
{
anim.SetBool("moveing", false);//播放idle动画
}
//不用刚体控制移动
//if(Input.GetKey(KeyCode.W))
//{
// transform.Translate(Vector3.forward);
//}
}
//射线控制角色旋转的方向
public void Turn()
{
//从主摄像机的原点向鼠标的位置上发送一条射线
Ray camRay = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
//如果射线检测成功
if(Physics.Raycast(camRay,out hit,camLeagth,floorMask))
{
Debug.Log("射线");
//根据鼠标位置进行转向
Vector3 playerMouse = hit.point - transform.position;//向量计算
rb.MoveRotation(Quaternion.LookRotation(playerMouse));
//
//transform.LookAt(hit.point);
}
}
}
相机的跟随:用Unity平滑函数Lerp
lerp主要有三个参数(常用)
lerp(初始状态 , 目标状态, OneExecutePer )
OneExecutePer:每一次执行靠近的度是多少(如果是1,就是说执行一次就会达到目标)
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);
}
}