What is wrong with my code? C# beginner
Hi there, I am trying to create a game in where an object in unity rotates 90 degrees when the mouse is clicked. I have made it so that the object moves to the right as can be seen in the code below. So I tried to write a similar bit of code for this rotation script but it's not working for me. Can anybody please tell me where I have gone wrong? Thanks!
using UnityEngine; using System.Collections;
public class Movement : MonoBehaviour {
// Use this for initialization
void Start()
{}
// Update is called once per frame
void Update () {
Rigidbody2D rb = GetComponent<Rigidbody2D>();
// Change the mass of the object's Rigidbody.
rb.mass = 10f;
rb.AddForce(Vector2.right * 10f);
}
}
public class Rotate : MonoBehaviour { void OnMouseDown()
{
Rigidbody2D rb = GetComponent<Rigidbody2D>();
// Rotate the object's Rigidbody.
rb.transform.Rotate(new Vector3( 0, 90, 0));
}
}
Answer by alexisrabadan · Mar 18, 2016 at 01:23 AM
Try
rb.transform.rotation = Quaternion.Euler(0f, 90f, 0f);
and while you are at it, it is good practice to cache the rigidbody by declaring the class variable Rigidbody rb;
above the Start
method and placing
rb = GetComponent<Rigidbody2D>();
into the Start
method