繁体   English   中英

如何使运动独立于 object 的旋转? C# 统一

[英]How to make movement independent of rotation of the object? C# Unity

我试图让我的胶囊移动,但是当我旋转相机时,它的运动会倒转。 我应该改变什么?

这是我的代码

using System.Collections.Generic;
using UnityEngine;

public class ejimaslol : MonoBehaviour
{

    public Rigidbody rb;
    public Transform rotation;
    public float forwardForce = 1f;
    public float sidewaysForce = 1f;


    void FixedUpdate()
    {
     if(Input.GetKey("w") ){
         rb.AddForce((forwardForce, 0f, 0f) * rotation.transform.rotation);
        }
    if(Input.GetKey("d") ){
            rb.AddForce((sidewaysForce, 0f, 0f) * rotation.transform.rotation);
        }
        if(Input.GetKey("a") ){
            rb.AddForce((-sidewaysForce, 0f, 0f) * rotation.transform.rotation);
        }
         if(Input.GetKey("s"))
        {
            rb.AddForce((-forwardForce, 0f, 0f) * rotation.transform.rotation);
        }```

诀窍是使这些方向相对于相机而不是 object 本身:

float dt = Time.fixedDeltaTime;
float forcePerSecond = 10f;
var cameraTransform = Camera.main.transform;
if( Input.GetKey(KeyCode.W) )
    rb.AddForce( Vector3.ProjectOnPlane(cameraTransform.forward,Vector3.up).normalized * forcePerSecond * dt );
if( Input.GetKey(KeyCode.S) )
    rb.AddForce( Vector3.ProjectOnPlane(-cameraTransform.forward,Vector3.up).normalized * forcePerSecond * dt );

暂无
暂无

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

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