Unity学习 2D角色 PlayerControl脚本编写

tech2022-12-03  91

Rigid刚体移动

对角色添加刚体组件,通过刚体控制移动。

使用 Rigid2D 进行角色移动,会受到移动惯性的影响。可以在 Rigidbody2D 中设置线性阻尼(Linear Drag),来抵消这种移动惯性,数值越大惯性越小。

Linear Drag数值为0时的角色移动表现 Linear Drag数值为10时的角色移动表现

代码示例

using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerPrac : MonoBehaviour { private Rigidbody2D rig2D; private float moveSpeed = 5.0f; //设置移动速度 void Start () { rig2D = gameObject.GetComponent<Rigidbody2D>(); //获得 Rigid2D 组件 } void Update() { //帧更新函数 //根据坐标轴名称返回虚拟坐标系中的值。键盘输入区间[-1,1] float H = Input.GetAxis("Horizontal"); float V = Input.GetAxis("Vertical"); Vector2 playerMove = new Vector2(H,V); rig2D.AddForce(playerMove*moveSpeed); } }
最新回复(0)