Circular movement for the player
Spent 4 hours trying to implement this so I must be doing something wrong.
I want the player object to be able to move in a circle when a special target locking mode is activated. I'm done implementing mode switching. I also have this method which enforces the circular motion:
void LockMotionUpdate()
{
t += h * Time.deltaTime * 0.05f * speed;
Vector3 d = Vector3.zero;
d.x = tcenter.x + R * Mathf.Cos(t);
d.z = tcenter.z + R * Mathf.Sin(t);
transform.LookAt(tcenter);
transform.position = d;
}
This function uses the parametric equation of a circle and it works as expected. h
is the parameter, which is received as input from one of the controller axes.
The center of the circle, tcenter
, is calculated in another function which is run once upon activating the mode:
void LockMotion()
{
R = 4f;
var a1 = transform.forward;
a1.y = 0f;
a1.Normalize();
a1 *= R;
var a2 = transform.position;
a2.y = 0f;
//calculate the center of the circle in which the player will be moving
tcenter = a1 + a2;
}
The center is expected to be at point which is R units away from the player in the direction it is facing. When activating the mode, I want the player to already be on the circumference, with the center being R units ahead in the facing direction.
The problem is that when I activate this circular motion mode, the code "sees" the player object as the center of the circle and jumps it to some point on the circumference so that it can begin moving in the circle. How do I fix this?
What is t's initial value? it looks like it should be 270 degree
The circle in light green is just for illustrative purpose, it does not reflect an in-game situation. But anyway, speed = 50.0f
, Time.deltaTime = 0.02f
(in my case) and h
, being input from an axis, ranges between -1 and 1. So t
is around 0.05.
Also, t
should not be in degrees, since it's a parameter of the parametric equations, so it should just be some value which, when plugged into the equations, gives points on a circle.
This expression :
d.x = tcenter.x + R * $$anonymous$$athf.Cos(t);
d.z = tcenter.z + R * $$anonymous$$athf.Sin(t);
might start your player any place on circle according to your players orientation.
Using transform.RotateAround function might be better:
void Lock$$anonymous$$otionUpdate()
{
float t = h * Time.deltaTime * 0.05f * speed;
transform.RotateAround (tcenter, Vector3.up, t);
transform.LookAt(tcenter);
}
Hope that helps.