【问题标题】:Unity rigidbody2d tilt issueunity 刚体 2d 倾斜问题
【发布时间】:2015-11-20 22:00:43
【问题描述】:

我是新手,正在尝试学习如何使用 C# 和 unity。当你在 x 轴上来回移动时,我目前正试图倾斜我的船。但是我得到一个编译器错误但看不到它?任何帮助将不胜感激:)

错误是这样的:

Assets/Scripts/PlayerController.cs(28,62):错误 CS0029:无法将类型“UnityEngine.Quaternion”隐式转换为“float”

using UnityEngine;
using System.Collections;

[System.Serializable]
public class Boundary {
    public float xMin, xMax, yMin, yMax;
}

public class PlayerController : MonoBehaviour {

    public float speed;
    public float tilt;
    public Boundary boundary;

    void FixedUpdate () {
        float moveHorizontal = Input.GetAxis ("Horizontal");
        float moveVertical = Input.GetAxis ("Vertical");

        Vector2 movement = new Vector2 (moveHorizontal, moveVertical);
        this.gameObject.GetComponent<Rigidbody2D> ().velocity = movement * speed;

        this.gameObject.GetComponent<Rigidbody2D> ().position = new Vector2 
            (
                Mathf.Clamp (this.gameObject.GetComponent<Rigidbody2D> ().position.x, boundary.xMin, boundary.xMax),
                Mathf.Clamp (this.gameObject.GetComponent<Rigidbody2D> ().position.y, boundary.yMin, boundary.yMax)
            );

        //issue is on this line
        this.gameObject.GetComponent<Rigidbody2D> ().rotation = Quaternion.Euler (0.0f, this.gameObject.GetComponent<Rigidbody2D> ().velocity.x * -tilt, 0.0f);
    }
}

【问题讨论】:

  • Quaternion.Euler 正在返回 UnityEngine.Quaternion。但是游戏gameObject.GetComponent&lt;Rigidbody2D&gt; ().rotation 是个浮点数
  • 你能推荐一个替代方案吗?我正在使用统一 5,公平地说,我正在使用统一 4.3 教程来提供帮助。他使用以下代码并且它有效:rigidbody.rotation = Quaternion.Euler (0.0f, 0.0f,rigidbody.velocity.x * -tilt);可能是我正在使用带有 3D 变量的刚体 2D 吗?如果是这样,是否有 2D 的替代方案? :)

标签: c# unity3d unity5


【解决方案1】:

您使用的教程可能使用Rigidbody (3D),而您使用的是Rigidbody2D

Rigidbody2D.rotationfloat 绕 Z 轴旋转。

Rigidbody.rotationQuaternion 3d 旋转。您的代码创建了一个Quaternion,它可以与Rigidbody 一起使用,但您有一个Rigidbody2D

有两种方法可以修复错误:

  1. 使用 2d 旋转,跳过 Quaternion 的创建:

    var rigidbody2D = GetComponent<Rigidbody2D>();
    rigidbody2D.rotation = rigidbody2D.velocity.x * -tilt;
    
  2. 更改您的代码和 Unity 对象以使用 Rigidbody

【讨论】:

  • 非常感谢,这很有魅力 :) 编辑:我使用了第一个解决方案 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多