简体   繁体   English

Unity C#,面对精灵和刚体的相机无法一起使用

[英]Unity C#, Camera facing sprite and rigidbody not working together

I have a small piece of code to make a sprite (in a 3D world) always face the camera (It has to be in 3D space). 我有一小段代码可以使精灵(在3D世界中)始终面对相机(必须在3D空间中)。

public class CS_CameraFacingBillboard : MonoBehaviour {

    private Camera m_Camera;

    private void Start()
    {
        m_Camera = Camera.main;
    } 

    void Update()
    {
        transform.LookAt(transform.position + m_Camera.transform.rotation * 
Vector3.forward, m_Camera.transform.rotation * Vector3.up); 
    }
}

This code ensures the sprite is always facing the camera, causing it to lean backwards as the camera in above the sprite facing down in a 45 degree agle. 此代码可确保精灵始终面向相机,从而使相机向后倾斜,因为相机上方的精灵朝下倾斜45度。 When I put a rigidbody on the sprite, the sprite moves on its own towards the direction its leaning. 当我在子画面上放置刚体时,子画面会自行朝着倾斜的方向移动。 The rigidbody works fine without this code attached. 无需附加此代码,刚体可以正常工作。

How can I have a sprite that always faces the camera, and has a rigidbody attached? 如何使精灵始终面向相机并附有刚体?

It seems you've left the rigidbody as Dynamic , you should set it to Kinematic . 似乎您将刚体保留为Dynamic ,应该将其设置为Kinematic

EDIT: After you comments, I checked myself inside Unity, and probably I've recreated the behaviour you described. 编辑:在您发表评论后,我在Unity内进行了检查,并可能重新创建了您描述的行为。 It happens to me too IF I use a Box Collider on the sprite without locking its rigidbody rotation. 如果我在Sprite上使用Box Collider而不锁定其刚体旋转,我也会遇到这种情况。 So you have three possible solutions: 因此,您有三种可能的解决方案:

  • Use a Box Collider and under Constraints of the rigidbody freeze the rotation: 使用Box Collider然后在刚体Constraints下冻结旋转: 在此处输入图片说明
  • Use a Sphere Collider (or another one that doesn't behave like the box one, you can check them out in play mode). 使用Sphere Collider (或者另一台行为不像方块的Sphere Collider ,您可以在播放模式下将它们检出)。
  • Split the components over two game object, a parent and a child. 将组件拆分为两个游戏对象(父对象和子对象)。 The parent will have all the components except the sprite renderer and the camera script, which will be on the child. 父级将具有子级渲染器和摄影机脚本以外的所有组件。 This option is the most flexible and less restraining. 此选项是最灵活且约束较少的选项。 You can have the box collider without freezing rotations, etc. 您可以使用盒子对撞机而不会冻结旋转等。

Another thing, you can avoid the use of the LookAt method, by simply using: 另一件事,您可以通过简单地使用以下方法避免使用LookAt方法:

transform.rotation = m_Camera.transform.rotation;

they have the same outcome. 他们有相同的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM