- Home /
Question by
Linezokode · May 26 at 03:36 AM ·
unity 2dspritesanglesvectors
How can I get the distance from the center of an object to the mouse position?
So basically, I have a sprite and I need to set the size.x of it to the distance to the mouse. all fine and dandy until I move the mouse above the object, and now it's getting shorter... Any help is much appreciated!
like so: https://youtu.be/6GRJ8iU1gWk
and this is my PlayerController.cs: (I kinda know the problem is that im setting the sprite size to the distanceFromMouse.x, but I have no idea how I could fix it)
public class PlayerController : MonoBehaviour
{
[Header("Aiming")]
[SerializeField] private GameObject rotatePoint;
[SerializeField] private Transform aimIndicator;
[Header("Shooting")]
[SerializeField] private float strengthThreshold;
[SerializeField] private float shootStrength;
[Header("Movement")]
[SerializeField] private float _moveSpeed;
private Vector3 _mousePosition;
private Vector3 _distanceFromMouse;
private float _horizontalInput;
private SpriteRenderer _aimSprite;
private Camera _mainCam;
private Rigidbody2D _playerRb;
bool isMoving;
private void Start()
{
_mainCam = Camera.main;
_aimSprite = aimIndicator.GetComponent<SpriteRenderer>();
_playerRb = GetComponent<Rigidbody2D>();
}
private void Update()
{
GetMousePosition();
AimTowardsMousePosition();
DrawLineTowardsMouse();
GetUserInput();
CheckPlayerMovement();
aimIndicator.gameObject.SetActive(!isMoving);
}
private void FixedUpdate()
{
MovePlayer();
}
void GetUserInput()
{
_horizontalInput = Input.GetAxis("Horizontal");
}
bool CheckPlayerMovement()
{
isMoving = _horizontalInput != 0;
return isMoving;
}
void MovePlayer()
{
_playerRb.velocity = new Vector2(_horizontalInput * _moveSpeed,_playerRb.velocity.y);
}
void GetMousePosition()
{
_mousePosition = _mainCam.ScreenToWorldPoint(Input.mousePosition);
// Debug.Log(_mousePosition);
}
void AimTowardsMousePosition()
{
// Get the distance between _rotatePoint and the _mousePosition
_distanceFromMouse = _mousePosition - rotatePoint.transform.position;
Vector2 normalisedDistance = _distanceFromMouse.normalized;
// Get angle from mouse location and rotate point location
float zAngle = Mathf.Atan2(normalisedDistance.y, normalisedDistance.x) * Mathf.Rad2Deg;
rotatePoint.transform.rotation = Quaternion.Euler(0,0,zAngle); // Rotate _rotatePoint.
}
void DrawLineTowardsMouse()
{
_aimSprite.size = new Vector2(Mathf.Abs(_distanceFromMouse.x), 1);
if (_aimSprite.size.x < 1)
{
_aimSprite.size = new Vector2(1, 1);
}else if (_aimSprite.size.x > strengthThreshold)
{
_aimSprite.size = new Vector2(strengthThreshold, 1);
}
}
}
Comment
Just for testing, instead of using a sprite's scale try using a Line Renderer... Then see what happens
Also instead of calculating the distance manually I think you can use Vector3.Distance