- Home /
My object is rotating crazily - 2D
Hi, I want my object to simply rotate and look towards where I click (In 2D), but instead it kind of faces my click in 3D, so it rotates around the X and Y axis instead of just Z. I have tried many different types of rotation strategies, but none seem to work the way I want them to. If anyone could help, that would be greatly appreciated. Cheers!
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class PlayerShip : MonoBehaviour {
public Text massText;
public Text thrustText;
[Header("Attributes")]
public float speed = 0f;
public float mass = 1f;
[Space(5)]
public Rigidbody2D rb;
[Space(5)]
public float distanceToClick;
private Vector3 mouseClickPos;
[Space(5)]
public float smoothTime;
private Vector3 velocity = Vector3.zero;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
GameObject placementManager = GameObject.Find("PlacementManager");
if (placementManager.GetComponent<PlacementScript>().isAnObjectSelected == true)
{
transform.rotation = Quaternion.Euler(0, 0, 90);
transform.position = new Vector2(Mathf.Round(transform.position.x), Mathf.Round(transform.position.y));
}
mass = mass / 2;
rb.mass = mass;
smoothTime = rb.mass;
float massRounded = Mathf.Round(mass);
float thrustRounded = Mathf.Round(speed);
massText.text = "Mass: " + massRounded;
thrustText.text = "Thrust: " + thrustRounded;
}
private void FixedUpdate()
{
GameObject placementManager = GameObject.Find("PlacementManager");
if (Input.GetMouseButton(1))
{
if (placementManager.GetComponent<PlacementScript>().isAnObjectSelected == false)
{
mouseClickPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
distanceToClick = Vector3.Distance(transform.position, mouseClickPos);
}
}
if (distanceToClick >= 0.5f && speed > 0)
{
if (placementManager.GetComponent<PlacementScript>().isAnObjectSelected == false)
{
Vector2 dir = mouseClickPos - transform.position;
var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
transform.position = Vector3.SmoothDamp(transform.position, mouseClickPos, ref velocity, smoothTime);
}
}
transform.position = new Vector3(transform.position.x, transform.position.y, 0);
}
}
Answer by JonPQ · Jul 22, 2019 at 09:56 PM
did you try Transform.RotateAround() ? https://docs.unity3d.com/ScriptReference/Transform.RotateAround.html Specify Vector3.forward as the axis. and, angle is the angleDelta since the last frame.
or, transform.rotation = Quaternion.Euler(0,0,zAngle);
Your answer