这篇文章主要为大家详细介绍了Unity实现物体左右移动效果,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了Unity实现物体左右移动效果的具体代码,供大家参考,具体内容如下
效果如下
代码:
using UnityEngine;
using System.Collections;
//Add this script to the platform you want to move.
//左右移动的平台
public class MovingPlatform : MonoBehaviour {
//Platform movement speed.平台移动速度
public float speed;
//This is the position where the platform will move.平台移动的位置
public Transform MovePosition;//创建一个空物体作为移动的位置
private Vector3 StartPosition;
private Vector3 EndPosition;
private bool OnTheMove;
// Use this for initialization
void Start () {
//Store the start and the end position. Platform will move between these two points.储存左右两端点位置
StartPosition = this.transform.position;
EndPosition = MovePosition.position;
}
void FixedUpdate () {
float step = speed * Time.deltaTime;
if (OnTheMove == false) {
this.transform.position = Vector3.MoveTowards (this.transform.position, EndPosition, step);
}else{
this.transform.position = Vector3.MoveTowards (this.transform.position, StartPosition, step);
}
//When the platform reaches end. Start to go into other direction.
if (this.transform.position.x == EndPosition.x && this.transform.position.y == EndPosition.y && OnTheMove == false) {
OnTheMove = true;
}else if (this.transform.position.x == StartPosition.x && this.transform.position.y == StartPosition.y && OnTheMove == true) {
OnTheMove = false;
}
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程学习网。
沃梦达教程
本文标题为:Unity实现物体左右移动效果
猜你喜欢
- 在C# 8中如何使用默认接口方法详解 2023-03-29
- Unity Shader实现模糊效果 2023-04-27
- c# 模拟线性回归的示例 2023-03-14
- WPF使用DrawingContext实现绘制刻度条 2023-07-04
- .NET CORE DI 依赖注入 2023-09-27
- C# 使用Aspose.Cells 导出Excel的步骤及问题记录 2023-05-16
- user32.dll 函数说明小结 2022-12-26
- 如何使用C# 捕获进程输出 2023-03-10
- Unity3D实现渐变颜色效果 2023-01-16
- Oracle中for循环的使用方法 2023-07-04