How to get an object to turn to point to a direction using the shortest path. E.g. 15° to 345° in 30° instead of 330°.
Hello,
Hello I'm working on a game where the player controls a spacecraft by touching an area of the screen to fly in that direction (currently I'm just using a joystick input, but will replace it). The joystick generates x, y coordinates which can be translated into an angle with some basic trigonometry.
The Question:
If the player starts their turn at 15 degrees and moves 30 degrees counter clockwise the angle will go from 15 to 345 degrees causing the craft to preform a 330 degree turn.
using UnityEngine;
using System.Collections;
using UnityStandardAssets.CrossPlatformInput;
public class ShipController : MonoBehaviour {
public float acceleration = 1;
public float torque = 1;
public float autoTurnForce = 1;
Vector2 joyInput;
Rigidbody rb;
float angle = 0;
float stickForce = 0;
void Start () {
rb = GetComponent<Rigidbody>();
}
void FixedUpdate() {
//Shortcut variable for joystick input.
joyInput = new Vector2(CrossPlatformInputManager.GetAxis("Horizontal"), CrossPlatformInputManager.GetAxis("Vertical"));
if (joyInput.x != 0 || joyInput.y != 0) { // <-- Prevents dividing zero by zero
angle = CalculateAngle(joyInput.x, joyInput.y);
rb.AddRelativeForce(0, 0, CalculateStickForce(joyInput.x, joyInput.y) * acceleration);
if (angle - transform.rotation.eulerAngles.y > 2.5F) {
rb.AddRelativeTorque(0, autoTurnForce, 0);
}
if (angle - transform.rotation.eulerAngles.y < -2.5F) {
rb.AddRelativeTorque(0, -autoTurnForce, 0);
}
}
}
float CalculateAngle(float x, float y) { //Calculates the angle of the joy stick input.
if (joyInput.x > 0 && joyInput.y > 0) {
return Mathf.Atan(x / y) * Mathf.Rad2Deg;
}
if (joyInput.x > 0 && joyInput.y < 0) {
return (Mathf.Atan(x / y) * Mathf.Rad2Deg) + 180;
}
if (joyInput.x < 0 && joyInput.y > 0) {
return (Mathf.Atan(x / y) * Mathf.Rad2Deg) + 360;
}
if (joyInput.x < 0 && y < 0) {
return (Mathf.Atan(x / y) * Mathf.Rad2Deg) + 180;
}
else { //The compiler get miffed if this else is not present.
return 0;
}
}
float CalculateStickForce(float x, float y) { //Calculates how far away from the centre the joy stick is.
if (joyInput.x > 0 && joyInput.y > 0) {
return x + y;
}
if (joyInput.x > 0 && joyInput.y < 0) {
return x + -y;
}
if (joyInput.x < 0 && joyInput.y > 0) {
return -x + y;
}
if (joyInput.x < 0 && joyInput.y < 0) {
return -x + -y;
}
if (stickForce > 1) {
return 1;
}
else {
return 0;
}
}
}
Hope you can help, thanks!
Your answer
Follow this Question
Related Questions
Modifying number based on % change 0 Answers
Getting average value of slider while playing. 0 Answers
Unity Math is Wrong for Some Reason 0 Answers
I need help with input field ui. 0 Answers
Horizontal Input showing random decimal when it should be 0 0 Answers