using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour {
private Vector2 targetPos = new Vector2(1, 1);
private Rigidbody2D rigidbody;
public float smoothing = 4;
public float restTime = 0.5f;
public float restTimer = 0;
// Use this for initialization
void Start () {
rigidbody = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
// rigidbody.MovePosition(Vector2.Lerp(transform.position, targetPos, smoothing * Time.deltaTime));//lerp插值,使移动平滑
rigidbody.MovePosition(targetPos);//无lerp,移动是瞬移。
//如果休息之间不够,不更新目标位置,直接返回
restTimer += Time.deltaTime;//restTimer会不断增加deldatime其实是每一帧(每一次update方法调用)所经过的时间
if (restTimer < restTime)
return;
float h = Input.GetAxisRaw("Horizontal");//返回1 -1 0
float v = Input.GetAxisRaw("Vertical");
if (h > 0)
{
v = 0;
}
if (h != 0 || v != 0)
{
targetPos += new Vector2(h, v);
restTimer = 0;
}
}
}
restTime的值代表在restTimer的时间小于restTime时,程序不会接收用户的输入,会直接退出。在restTimer大于restTime时,update()函数才会接收用户的输入,并更新目标位置。在想要达到这样一种效果:即物体在移动到某一位置的过程中用户不能再进行干预(即直线运动)。
关于rigidBody.movePosition()接收一个VectorX。如果是rigidBody2d,接收一个Vector2。执行这个函数会使指定物体瞬间移动到指定位置
2D刚体对其移动速度有一个固定的限制,因此在短时间尺度上移动大距离会导致刚体position在下一次物理更新期间未达到指定值。建议您仅将此用于相对较小的距离移动。——unity api手册2018.1
Vector2.lerp()表示插值操作,其用法可以看这篇文章:https://www.cnblogs.com/unity3ds/p/5737183.html
调用它的目的是使物体的移动较为平滑。