I am making a small game as a side project and part of the game includes a ball being launched from a cannon. I need to be able to track the and of the rotating cannon to know where to instantiate the ball. I understand the trig behind tracking a point on the circumference of a circle but I just don't know how to convert the quaternion values I get from the transform.rotation to radians/degrees so I can use them in trig functions.
Just using the quaternion values in my trig functions didn't work, as you may expect. I am very new to C# so I'm sure there is a much more elegant solution to this and I am probably doing more work than necessary but this is still something I'd like to know regardless. I appreciate any insight you guys may have on this and can you please talk to me like a 5-year-old because I'm having a hard time conceptualizing quaternions.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Launcher : MonoBehaviour
{
public GameObject ball;
public float posX;
public float posY;
public float radians;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
//convert the degrees to radians
radians = (float)((transform.rotation.z) * (System.Math.PI / 180));
posX = (float) System.Math.Cos(radians);
posY = (float) System.Math.Sin(radians);
if(Input.GetKeyDown(KeyCode.S)) {
Instantiate(ball, new Vector3(posX, posY + transform.position.y, transform.position.z), transform.rotation);
}
}
}
You don't have to convert the quaternion into another representation to do this. The Transform
class from Unity provides a way to rotate and translate a vector given a transform. Assuming that the tip of the cannon in local coordinates is (1,0,0)
, you can calculate the position of the ball like this:
var localBallPosition = new Vector3(1,0,0);
var worldBallPosition = transform.TransformPoint(localBallPosition);
localBallPosition
should be made to fit the length of the cannon.