第一种,采用更加现实的模式进行运动,代码里含有加速度和速度,以及摩擦力,在人物开始运动时会有一定延迟(毕竟要先加速嘛),优点时贴合实际,这套模式可采用到赛车游戏等需要加速的游戏中。
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MyRubyController : MonoBehaviour { [SerializeField] //将加速度暴露出来使其可调 private float _accel = 0.1f;//加速度 [SerializeField] public float _maxSpeed = 5f;//maxSpeed:对速度进行限制 // Start is called before the first frame update Rigidbody2D rb2d;//声明刚体组件 //获取用户输入 float horizontal;//获取水平键盘输入 float vertical;//获取垂直键盘输入 public float friction = 1f;//摩擦力 void Start() { //获取当前游戏对象的刚体组件 rb2d = GetComponent<Rigidbody2D>(); } // Update is called once per frame void Update() { horizontal = Input.GetAxis("Horizontal"); vertical = Input.GetAxis("Vertical"); float dt = Time.deltaTime;//时间 ApplyFriction(dt); ApplyMovement(dt); } private void ApplyMovement(float dt) { Vector2 accel = new Vector2(horizontal * this._accel, vertical * this._accel);//建立一个加速度向量 Vector2 vel = rb2d.velocity;//建立一个向量获取当前刚体组件的速度 vel += accel * dt;//每一帧速度加等于加速度 float velSize = vel.magnitude;//向量长度 if (velSize > _maxSpeed)//大于最大速度时置为最大速度 { vel = vel.normalized * _maxSpeed; } rb2d.velocity = vel;//将修改过的值返回该速度 } private void ApplyFriction(float dt) { float faccel = friction; //摩擦力加速度 Vector2 vel = rb2d.velocity; // 人物速度 vel = Vector2.MoveTowards(vel, Vector2.zero, faccel * dt);//向zero靠近,慢慢减速 rb2d.velocity = vel; } }
第二套是立刻启动,因为原理是直接修改Rigidbody的position属性,不过这一套我们也要添加摩擦力系统,不然的话我们如果被带有速度的刚体撞击的话会停不下来。
using System.Collections; using System.Collections.Generic; using UnityEngine; public class RubyController1 : MonoBehaviour { //将速度暴露出来使其可调 public float speed = 0.1f; int currentHealth;//生命值 // Start is called before the first frame update Rigidbody2D rb2d;//声明刚体组件 //获取用户输入 float horizontal;//获取水平键盘输入 float vertical;//获取垂直键盘输入 public float friction = 1f;//摩擦力 void Start() { //获取当前游戏对象的刚体组件 rb2d = GetComponent<Rigidbody2D>(); currentHealth = maxHealth; } // Update is called once per frame void Update() { } private void FixedUpdate() { horizontal = Input.GetAxis("Horizontal"); vertical = Input.GetAxis("Vertical"); Vector2 position = rb2d.position;//tranform组件,该节点tranform修改x和y position.x = position.x + speed * horizontal * Time.deltaTime; position.y = position.y + speed * vertical * Time.deltaTime;//Time.deltaTime:时间帧率。 rb2d.position = position; float dt = Time.deltaTime;//时间 ApplyFriction(dt); } private void ApplyFriction(float dt) { float faccel = friction; //摩擦力加速度 Vector2 vel = rb2d.velocity; // 人物速度 vel = Vector2.MoveTowards(vel, Vector2.zero, faccel * dt);//向zero靠近 rb2d.velocity = vel; //float velSize = vel.magnitude; //float accelSize = faccel * dt; //if (accelSize >= velSize) //{ // vel = Vector2.zero; //} //else //{ // vel -= vel.normalized * accelSize; //} } }
Ruby