• [Unity3D] 物体的几种移动方法


    一: 匀速移动,可以到达目标点

      Vector3.MoveTowars(从哪,到哪,速度);

        例子:

    1 Vector3 targetPos = new Vector3(this.transform.position.x, this.transform.position.y, 10);
    2         this.transform.position = Vector3.MoveTowards(this.transform.position, targetPos, 0.05f);

      效果GIF:

      

    二: 按比例移动,不能到达目标点(无限接近)

      Vector3.Lerp(从哪,到哪,速度)

      例子:

    1 Vector3 targetPos = new Vector3(this.transform.position.x, this.transform.position.y, 10);
    2         this.transform.position = Vector3.Lerp(this.transform.position, targetPos, 0.01f);

       效果GIF,注意看右上角的position z的值,是9.999无限接近

    三: 自然移动(可手动调节的,可快可慢)

      起点固定,终点固定,比例根据曲线变化

      在Unity界面中可以看到曲线编辑器

      双击黑色框框,会打开编辑界面

      

      曲线编辑界面  

    双击线上任意位置,即可添加线段,可自由拉伸曲线  

    例子:

     1 public class test : MonoBehaviour
     2 {
     3 
     4     public AnimationCurve curve;
     5     private float x ;
     6     public float Speed = 1f;       //---速度
     7    
     8     void Update()
     9     {
    10         x += Time.deltaTime / Speed;
    11         Vector3 targetPos = new Vector3(0, 0, 10);
    12         this.transform.position = Vector3.Lerp(Vector3.zero, targetPos, 
    13         curve.Evaluate(x));
    14     }
    15 }

    效果GIF: 到达时间,请修改Speed值

    自然移动不限制边界(回弹效果)

    方法:  Vector3.LerpUnclamped(从哪,到哪,速度)

    代码:

     1 using System.Collections;
     2 using System.Collections.Generic;
     3 using UnityEngine;
     4 
     5 public class test : MonoBehaviour
     6 {
     7 
     8     public AnimationCurve curve;
     9     private float x ;
    10 
    11    
    12     void Update()
    13     {
    14         x += Time.deltaTime;
    15         Vector3 targetPos = new Vector3(0, 0, 10);
    16         this.transform.position = Vector3.LerpUnclamped(Vector3.zero, targetPos, curve.Evaluate(x));
    17     }
    18 }

    使用的曲线

    效果GIF

    时间若流水,恍惚间逝去
  • 相关阅读:
    Hadoop 2.2.0单节点的伪分布集成环境搭建
    CentOS系统中出现错误--SSH:connect to host centos-py port 22: Connection refused
    JUnit 5和Selenium基础(三)
    JUnit 5和Selenium基础(二)
    JUnit 5和Selenium基础(一)
    如何对N个接口按比例压测
    性能测试中标记每个请求
    初学者的API测试技巧
    Web安全检查
    Groovy重载操作符
  • 原文地址:https://www.cnblogs.com/alanshreck/p/13691334.html
Copyright © 2020-2023  润新知