Unity中同时使用MoveLeft与Spin脚本时对象运动异常问题
Unity物体同时挂载移动与自转脚本后运动异常问题解决
需求
实现物体向左飞行的同时进行自转。
现有实现脚本
MoveLeft 移动脚本
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MoveLeft : MonoBehaviour { private float moveLeftSpeed = 10; void Start() { } void Update() { transform.Translate(Vector3.left * Time.deltaTime * moveLeftSpeed); } }
SpinObjectsX 自转脚本
using System.Collections.Generic; using UnityEngine; public class SpinObjectsX : MonoBehaviour { public float spinSpeed = 50; void Update() { transform.Rotate(new Vector3(0, Time.deltaTime * spinSpeed, 0)); } }
问题现象
问题原因
transform.Translate方法默认使用**局部空间(Space.Self)**计算移动方向。当物体自转时,自身的局部坐标系会跟着旋转,导致Vector3.left指向的方向不断变化,最终运动轨迹偏离直线,变成绕圈运动。
解决方案
修改MoveLeft脚本中的Translate调用,明确指定使用世界空间(Space.World):
void Update() { transform.Translate(Vector3.left * Time.deltaTime * moveLeftSpeed, Space.World); }
效果说明
指定Space.World后,物体的移动方向将以世界坐标系为基准,无论物体如何自转,都会保持世界空间中的向左方向做直线运动,同时自转功能不受影响,即可实现预期的运动效果。
内容的提问来源于stack exchange,提问作者Tiến Hưng
相关产品推荐
相关产品推荐

