c# - unity rigidbody2d倾斜问题

标签 c# unity3d

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

错误是这样的:

Assets/Scripts/PlayerController.cs(28,62): error CS0029: Cannot implicitly convert type 'UnityEngine.Quaternion' to '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);
    }
}

最佳答案

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

Rigidbody2D.rotation是围绕 Z 轴的 float 旋转。

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

修复错误的方法有两种:

  1. 使用二维旋转,跳过四元数的创建:

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

关于c# - unity rigidbody2d倾斜问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33836768/

相关文章:

c# - 使用静态时出现 "An object reference is required to access non-static member"错误

c# - 我可以从数据源创建和反对 "self-loads"属性吗?

unity3d - 渲染完整的相机 View (16 :9) onto a texture in Unity3d

ios - 用于 2D 游戏的 Unity

c# - Avalon Dock 和 Caliburn Micro - 文档 Pane 上没有标题(选项卡标题)

c# - 制作一个顶点等距的球体

c# - TCP/IP Unity Android ERROR 帮助

c# - 在 WPF 中拖放 TabItem?

c# - Xamarin.Forms - 数据更改时 ListView 不更新

c# - 具有 Active 标志的流畅映射和关系表