移动物体,每次移动一格,以及通过插值使移动平滑

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
调用它的目的是使物体的移动较为平滑。

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值