- Home /
Question by
dylan1812 · Jun 22, 2020 at 11:14 PM ·
2d2d-platformerrotaterotate objectrotatearound
[2D] Tranform.RotateAround flickers arrow between two positions when the mouse is close to the player
I'm trying to get an arrow to point towards my mouse location and rotate around my player gameobject. For the most part I have it working well but when my mouse gets close to the player the arrow flickers between two locations. These two locations seem to be the same angle from the vector which describes the direction from the player to the mouse position.
Here's my current code, it is attached to the arrow gameobject which in turn is a child of the player.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerArrow : MonoBehaviour
{
[SerializeField] private Transform player;
// arrow rendering and rotating
private Vector3 mousePos;
private float differenceX;
private float differenceY;
private float prevAngle = 0f;
private float angle;
[SerializeField] private Sprite[] arrowStage;
private SpriteRenderer arrowSprite;
private int arrowIndex;
void Start()
{
arrowSprite = GetComponent<SpriteRenderer>();
}
void Update()
{
mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
public void SimulateArrow(float powerRatio)
{
// show correct sprite
arrowIndex = (int)Mathf.Round(powerRatio * 20); // round to nearest 0.05 since we have 21 positions
arrowSprite.sprite = arrowStage[arrowIndex];
// rotate sprite
differenceX = mousePos.x - transform.position.x;
differenceY = mousePos.y - transform.position.y;
angle = Mathf.Atan2(differenceY, differenceX) * Mathf.Rad2Deg;
transform.RotateAround(player.position, Vector3.forward, angle - prevAngle);
prevAngle = angle;
}
}
Thank you.
Comment