即使有限制,我的播放器仍会旋转

时间:2019-05-23 20:48:15

标签: c# unity3d

我希望我的玩家在游戏开始后不再旋转。我在脚本和约束中冻结旋转,但是播放器向前移动时仍然旋转。我能做什么 ? (我有一个fps和一个字符控制器)。我还有一个带有按钮的画布,可以控制向左,向右吗?我应该将rigibody或玩家脚本放置在Character对象内(我是否制作了包含角色和摄像机的玩家游戏对象)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class Player : MonoBehaviour
{
    public float playerSpeed = 1500;
    public float directionalSpeed = 20;

    private Rigidbody rb;

    // Start is called before the first frame update
    void Start()
    {
        GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeRotation;
    }

    // Update is called once per frame
    void Update()
    {
#if UNITY_EDITOR || UNITY_STANDALONE || UNITY_WEBPLAYER

        float moveHorizontal = Input.GetAxis("Horizontal");
        transform.position = Vector3.Lerp(gameObject.transform.position, new Vector3(Mathf.Clamp(gameObject.transform.position.x + moveHorizontal, -2.5f, 2.5f), gameObject.transform.position.y, gameObject.transform.position.z), directionalSpeed * Time.deltaTime);
#endif
        GetComponent<Rigidbody>().velocity = Vector3.forward * playerSpeed * Time.deltaTime;
        transform.Rotate(Vector3.right * GetComponent<Rigidbody>().velocity.z / 3);
        //MOBILE CONTROLS
        Vector2 touch = Camera.main.ScreenToWorldPoint(Input.mousePosition + new Vector3(0, 0, 10f));
        if (Input.touchCount > 0)
        {
            transform.position = new Vector3(touch.x, transform.position.y, transform.position.z);
        }
    }
    public void MoveLeft()
    {
        rb.velocity = new Vector2(-playerSpeed, rb.velocity.y);
    }
    public void MoveRight ()
    {
        rb.velocity = new Vector2(playerSpeed, rb.velocity.y);
    }
    public void StopMoving()
    {
        rb.velocity = new Vector2(0f, rb.velocity.y);
    }
    void DetectInput()
    {
        float x = Input.GetAxisRaw("Horizontal");
        if (x > 0 )
        {
            MoveRight();
        }
        else if ( x < 0)
        {
            MoveLeft();
        }
        else
        {
            StopMoving();
        }
    }
}

2 个答案:

答案 0 :(得分:0)

使用MoveRotation旋转

使用Rigidbody组件约束将仅通过物理引擎约束游戏对象。您当前正在手动旋转变换。

摘自文档:

void FixedUpdate()
{
    Quaternion deltaRotation = Quaternion.Euler(m_EulerAngleVelocity * Time.deltaTime);
    m_Rigidbody.MoveRotation(m_Rigidbody.rotation * deltaRotation);
}

答案 1 :(得分:0)

如果添加了刚体,则可以冻结位置或旋转 (无论刚体是2d还是否) enter image description here

首先,您必须声明刚体

rb = GetComponent<Rigidbody>();

然后您可以冻结旋转RigidbodyConstraints(屏幕截图中的选定标签)

rigidbody.constraints = RigidbodyConstraints.FreezeRotationX;
//freeze only one rotation

rigidbody.constraints = RigidbodyConstraints.FreezePositionX | RigidbodyConstraints.FreezePositionZ | RigidbodyConstraints.FreezePositionY;
//freeze all rotations

仅选中即可取消选中

rigidbody.constraints = RigidbodyConstraints.None; 

如果您的游戏是2d,只需在所有Rigidbodies文本中添加2d