在不使用刚体的情况下将移动物体的朝向设置为朝向其移动方向 [英] Set orientation of moving object towards it movement direction without using rigidbody

查看:176
本文介绍了在不使用刚体的情况下将移动物体的朝向设置为朝向其移动方向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个GameObject(相机),它正在样条线上移动(使用库).我想为其运动设定方向.我的意思是,物体应该朝着其移动的方向看.我尝试了一些方法来实现此目的,但未成功.这是我的尝试:

I have a GameObject (camera) which is moving on the spline (using a library). I want to set its orientation towards its movement. What I mean is, the object should be looking in the direction that it is moving. I tried some things to achieve this, but I was unsuccessful. Here are my attempts:

 transform.rotation = Quaternion.LookRotation(transform.position);

我也尝试过

 transform.rotation = Quaternion.LookRotation(transform.forward);

推荐答案

transform.position(空间中的点)或transform.forward(物体已经面对的方向)都不会为您提供物体移动的方向内.

Neither transform.position (a point in space) nor transform.forward (the direction an object is already facing) will necessarily give you the direction an object is moving in.

对于具有RigidBody的对象,您可以通过velocity变量进行访问-但由于听起来您正在使用专有的样条库并且无法访问该对象的实际移动方向,因此您可能需要自己跟踪它.

For an object with a RigidBody, you'd access this through the velocity variable - but since it sounds like you're using a proprietary spline library and have no access to the object's actual movement direction, you may need to keep track of it yourself.

最简单的解决方案(如果库确实不提供运动信息),则是在每个帧中存储对象的当前位置和先前位置,并手动计算增量位置(也就是帧之间的行进距离)以查找速度向量.例如:

The simplest solution (if the library really doesn't provide movement information), is to store the object's present position and previous position each frame, and manually calculating the delta position (aka. The distance travelled between the frames) to find the velocity vector. For example:

public class MovingObject : MonoBehaviour {
    private Vector3 prevPosition;

    void Start() {
        // Starting off last position as current position
        prevPosition = transform.position;
    }

    void Update() {
        // Calculate position change between frames
        Vector3 deltaPosition = transform.position - prevPosition;

        if (deltaPosition != Vector3.zero) {
            // Same effect as rotating with quaternions, but simpler to read
            transform.forward = deltaPosition;
        }
        // Recording current position as previous position for next frame
        prevPosition = transform.position;
    }
}

希望这会有所帮助!如果您有任何问题,请告诉我.

Hope this helps! Let me know if you have any questions.

这篇关于在不使用刚体的情况下将移动物体的朝向设置为朝向其移动方向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆