- Home /
The question is answered, right answer was accepted
Changing 2d Destination by angle
So I am playing with creating a 2d golf game. It's a top down and the ball only moves in the x and y directions. I have a target that shows where the ball will go.
float x = ((target.x - transform.position.x) * (float)ratio) + transform.position.x;
float y = ((target.y - transform.position.y) * (float)ratio) + transform.position.y;
moveTo = new Vector2 (x, y);
transform.position = Vector2.MoveTowards(transform.position, moveTo, ballspeed * Time.deltaTime);
This works just fine and the ball goes exactly where it should. The ratio is just for power so that the ball can go short of the target. So now I want to mess with accuracy. If they are off on their accuracy, I want the ball to go to the left or right (or if they are aiming straight left or right could be up and down) of the destination based on an angle and how far off they are. So this is what I came up with:
moveTo = Quaternion.AngleAxis (accuracy, Vector3.forward) * new Vector2 (x, y);
So now the destination is changed by a set accuracy amount which goes from -30 to 30. This works perfectly most of the time. But every once and awhile the ball will shoot in the exact opposite direction or an extra 45ish degrees. I have no idea what is causing this and I feel like I am so close. Any ideas?
Answer by Awesome_Oposssum · May 29, 2016 at 06:26 AM
Since I could not get what I was looking for from the built in tools (or at least could not figure it out), I used some trig with a circle as such:
float positionX = transform.position.x;
float positionY = transform.position.y;
//Find the destination based on power and the direction of the circle
float x = ((target.x - positionX) * (float)ratio) + positionX;
float y = ((target.y - positionY) * (float)ratio) + positionY;
//Convert the accuracy to radians
accuracy = offset * (Mathf.PI / 180);
newX = positionX + ((x - positionX) * Mathf.Cos (accuracy)) + ((y - positionY) * Mathf.Sin (accuracy));
newY = positionY + ((y - positionY) * Mathf.Cos (accuracy)) - ((x - positionX) * Mathf.Sin (accuracy));
moveTo = new Vector2 (newX, newY);
This moves the point along a circle using the current point, the destination, and the angle difference that I want. Just for reference, for me offset is an int between -30 and 30.