Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity rigidbody2d tilt issue

I'm new to this and trying to learn how to use C# and unity. I'm currently trying to tilt my ship as you move back and forth on the x axis. however I'm getting a compiler error but cant see it? any help would be appreciated :)

The error is this:

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);
    }
}
like image 729
MarkHughes88 Avatar asked Mar 11 '26 03:03

MarkHughes88


1 Answers

The tutorial you're using probably uses Rigidbody (3D), while you're using Rigidbody2D.

Rigidbody2D.rotation is a float rotation around the Z axis.

Rigidbody.rotation is a Quaternion 3d rotation. Your code creates a Quaternion, which would work with Rigidbody, but you have a Rigidbody2D.

There are two ways to fix the error:

  1. Use a 2d rotation, skipping creation of the Quaternion:

    var rigidbody2D = GetComponent<Rigidbody2D>();
    rigidbody2D.rotation = rigidbody2D.velocity.x * -tilt;
    
  2. Change your code and Unity objects to use Rigidbody.

like image 52
31eee384 Avatar answered Mar 12 '26 15:03

31eee384