(First time on the forums) So, I want my players ship to face the mouse using physics and it sort of does… I have posted a screenshot below to illustrate the problem
My code looks as follows:
using UnityEngine;
using System.Collections;
public class Movement : MonoBehaviour {
public GameObject thruster;
public float thrust;
public float torque;
private float optimalDirection;
public float mouseAngle;
private float playerRotation;
float angle;
void Start() {
rigidbody2D.centerOfMass = new Vector2(0.0f,0.0f);
}
void Update() {
}
// Update is called once per frame
void FixedUpdate()
{
//Enables acceleration
if ((Input.GetAxisRaw("Vertical") > 0) && (Input.GetKey("left shift")))
{
rigidbody2D.AddForce((transform.up * Time.deltaTime * thrust) * 1.5f, ForceMode2D.Force);
thruster.particleEmitter.emit = true;
}
else if (Input.GetAxisRaw("Vertical") > 0)
{
rigidbody2D.AddForce(transform.up * Time.deltaTime * thrust, ForceMode2D.Force);
thruster.particleEmitter.emit = true;
}
else
{
thruster.particleEmitter.emit = false;
}
//Allows ship to strave
rigidbody2D.AddForce(transform.right * Time.deltaTime * (thrust / 2) * Input.GetAxisRaw("Horizontal"), ForceMode2D.Force);
//Mouse rotation
Vector2 mouse = Camera.main.ScreenToViewportPoint(Input.mousePosition); //Mouse position
Vector3 objpos = Camera.main.WorldToViewportPoint(transform.position); //Object position on screen
Vector2 relobjpos = new Vector2(objpos.x - 0.5f, objpos.y - 0.5f); //Set coordinates relative to object
Vector2 relmousepos = new Vector2(mouse.x - 0.5f, mouse.y - 0.5f) - relobjpos;
mouseAngle = Vector2.Angle (Vector2.up, relmousepos); //Angle calculation
if (relmousepos.x > 0)
mouseAngle = 360-mouseAngle;
//sets 2 variables to aid with figuring out which direction to go
playerRotation = rigidbody2D.rotation;
//Finds the optimal direction
optimalDirection = ((((mouseAngle - (playerRotation)) % 360) + 540) % 360) - 180;
//Makes ships come to a stand still
if (Mathf.Round(optimalDirection) == 0)
rigidbody2D.rotation += optimalDirection;
//Chages velocity when appropriate
if (Mathf.Round(optimalDirection) > 0 && rigidbody2D.angularVelocity < -5)
rigidbody2D.angularVelocity = rigidbody2D.angularVelocity / 1.5f;
if (Mathf.Round(optimalDirection) < 0 && rigidbody2D.angularVelocity > 5)
rigidbody2D.angularVelocity = rigidbody2D.angularVelocity / 1.5f;
//Applying torque relative to Optimal_Direction
if (Mathf.Round(optimalDirection) > 0)
rigidbody2D.AddTorque(torque * Time.deltaTime);
if (Mathf.Round(optimalDirection) < 0)
rigidbody2D.AddTorque(-torque * Time.deltaTime);
}
}
I’m not sure what the issue is and was hoping for some sort of solution or alternative, the problem is reoccurring with every side however having the mouse at 90, 180, 270 and 360 degrees relative makes it align perfectly
