- Home /
Rotating around a point in a circular motion depending on mouse position
Hello everyone,
Im trying to create sort of aiming system for my top down shooter but can't get it to work. I've done tons of research but I didn't find anything usefull.
What I'm trying to do, is to create a circle around a character with a dot on it, and then make that dot rotate around the player to "face" the mouse, "get as close as possible to it".
I got the behavior I like, but it feels unrealistic, and I get wierd teleportations etc etc. I would like to set up a fixed speed of the dots rotation, lets say 2pi in a second, but I have no idea how to achive this.
I dont know, it feels just to wierd and unnatural, and I want to make it feel smooth and kind of "real", like its an actual physic thing.
Here is the code:
public class Test1 : MonoBehaviour {
public Transform target;
public float speed;
public float fRadius = 3.0f;
public float targetAngle;
public float currentAngle;
float x;
float y;
void Start () {
}
void Update () {
Vector3 mousePosition2D = Camera.main.WorldToScreenPoint (target.position);
mousePosition2D = Input.mousePosition - mousePosition2D;
currentAngle = Mathf.Atan2 (transform.position.y, transform.position.x) * Mathf.Rad2Deg;
targetAngle = Mathf.Atan2 (mousePosition2D.y, mousePosition2D.x) * Mathf.Rad2Deg;
mousePosition2D = Quaternion.AngleAxis (targetAngle, Vector3.forward) * (Vector3.right * fRadius);
//Debug.Log (mousePosition2D);
transform.position = target.position + mousePosition2D;
}
And what I'm trying to achive:
Any ideas?
Answer by zach-r-d · Jun 25, 2015 at 02:15 AM
Working manually with inverse trig functions is really tricky and takes forever to get right; I strongly recommend using vectors instead. In this case, the desired behavior can be accomplished using Vector3.RotateTowards:
Vector3 targetScreenPos = Camera.main.WorldToScreenPoint (target.position);
targetScreenPos.z = 0;
Vector3 targetToMouseDir = Input.mousePosition - targetScreenPos;
Vector3 targetToMe = transform.position - target.position;
targetToMe.z = 0;
Vector3 newTargetToMe = Vector3.RotateTowards(targetToMe, targetToMouseDir, /* max radians to turn this frame */, 0f);
transform.position = target.position + /*distance from target center to stay at*/ * newTargetToMe.normalized;
Works like a charm! Thank you. Never heard of that function before. Have to write it down :D
I'm glad it works! If the answer is satisfactory, remember to accept it as well. :)
If I will have more comments about this issue, am I free to P$$anonymous$$ you? Thanks for help once again.
If a new problem regarding this comes up post a new question here on UA, but feel free to mention me by writing "@zach.r.d" in the question so that I am personally notified.
That way, if someone else can answer it before I do, you will get a faster response, otherwise, I will answer it when I see it and it would be as if you sent me a P$$anonymous$$!