[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

 

posted @   伊凡晴天  阅读(3741)  评论(0编辑  收藏  举报
编辑推荐:
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 2 本地部署DeepSeek模型构建本地知识库+联网搜索详细步骤
点击右上角即可分享
微信分享提示