- Home /
2D Aiming with a mouse angle problem
Hi, I've been trying to find a solution for this particular problem for a while now, but with no result. I'm a bit new to Unity and scripting in general, so I decided to ask here if someone might have an idea how to solve the issue.
Basically, what I'm trying to do is have "object B" (crosshair for instance) circle around "object A" (player) using the mouse. I've made that work, but here's the problem:
Since it follows the mouse position and rotates towards it, the angle to mouse-movement changes depending on the distance of the mouse to the player character, who is the pivot point (the closer the mouse is, each mouse movement makes the angle more erratic, and vice versa). But since I intend to make the mouse pointer invisible in-game, there is no way to know where the pointer is, thus the angle is all over the place.
question/tldr:
Is there a way to bind mouse movement to a circle around a specific object or have consistent mouse movement to crosshair angle ratio for a 2d shooter?
Script I'm using at the moment, if someone is interested.
using System.Collections; public class AimingFinal : MonoBehaviour {using UnityEngine;
public Transform target; public float fRadius = 3.0f;
void Update () { Vector3 v3Pos = Camera.main.WorldToScreenPoint (target.position); v3Pos = Input.mousePosition - v3Pos; float angle = Mathf.Atan2 (v3Pos.y, v3Pos.x) Mathf.Rad2Deg; v3Pos = Quaternion.AngleAxis (angle, Vector3.forward) (Vector3.right * fRadius); transform.position = target.position + v3Pos; } }
Answer by robertbu · Mar 17, 2014 at 04:40 AM
Try this.
using UnityEngine;
using System.Collections;
public class RotaterUnitCircle : MonoBehaviour
{
public float sensitivity = 1.0f;
private Vector3 trackingPos;
void Start() {
trackingPos = Vector3.right;
}
void Update ()
{
trackingPos.x += Input.GetAxis ("Mouse X") * sensitivity;
trackingPos.y += Input.GetAxis ("Mouse Y") * sensitivity;
trackingPos = trackingPos.normalized;
float angle = Mathf.Atan2 (trackingPos.y, trackingPos.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis (angle, Vector3.forward);
}
}
This code assumes that the front of your sprite is on the right.
It works perfectly! Thank you so much, you're awesome! :D
Your answer
Follow this Question
Related Questions
2D platformer cursor 1 Answer
Sidescroll Shooter Crosshair? 0 Answers
2D Animation does not start 1 Answer
Making a Turret Have a Circle Sector Range 1 Answer
2D Top down shooter, gun is shaking while moving and Cursor solutions 0 Answers