- Home /
sprite refuses to flip in a specific angle, please help
(2D game) so i have this script that makes an object point towards the mouse pointer, i use it to move my character arm to aim, at the bottom is the code to rotate towards my mouse and at the top is the code to flip Y when he's aiming at something behind him, it's a mess but please bear with me i'm a dumbass, for some reason it works up until you reach from 0 to -90 degrees, i attached an image or what i mean, for some reason it doesn't flip the Y even though it's rotation is less than 90,so i have this script that makes an object point towards the mouse pointer, i use it to move my character arm to aim
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class look_at_mouse : MonoBehaviour
{
private SpriteRenderer mySpriteRenderer;
private void Awake()
{
mySpriteRenderer = GetComponent<SpriteRenderer>();
}
void Update()
{
if (transform.rotation.eulerAngles.z < 90)
{
if (mySpriteRenderer != null)
{
mySpriteRenderer.flipY = true;
}
}
if (transform.rotation.eulerAngles.z < 90)
{
if (mySpriteRenderer != null)
{
mySpriteRenderer.flipY = true;
}
}
Vector2 positionOnScreen = Camera.main.WorldToViewportPoint(transform.position);
Vector2 mouseOnScreen = (Vector2)Camera.main.ScreenToViewportPoint(Input.mousePosition);
float angle = AngleBetweenTwoPoints(positionOnScreen, mouseOnScreen);
transform.rotation = Quaternion.Euler(new Vector3(0f, 0f, angle));
}
float AngleBetweenTwoPoints(Vector3 a, Vector3 b)
{
return Mathf.Atan2(a.y - b.y, a.x - b.x) * Mathf.Rad2Deg;
}
}
,using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class look_at_mouse : MonoBehaviour
{
private SpriteRenderer mySpriteRenderer;
private void Awake()
{
mySpriteRenderer = GetComponent<SpriteRenderer>();
}
void Update()
{
if (transform.rotation.eulerAngles.z < 90)
{
if (mySpriteRenderer != null)
{
// flip the sprite
mySpriteRenderer.flipY = true;
}
}
if (transform.rotation.eulerAngles.z < 90)
{
if (mySpriteRenderer != null)
{
mySpriteRenderer.flipY = true;
}
}
Vector2 positionOnScreen = Camera.main.WorldToViewportPoint(transform.position);
Vector2 mouseOnScreen = (Vector2)Camera.main.ScreenToViewportPoint(Input.mousePosition);
float angle = AngleBetweenTwoPoints(positionOnScreen, mouseOnScreen);
transform.rotation = Quaternion.Euler(new Vector3(0f, 0f, angle));
}
float AngleBetweenTwoPoints(Vector3 a, Vector3 b)
{
return Mathf.Atan2(a.y - b.y, a.x - b.x) * Mathf.Rad2Deg;
}
}
Your answer
Follow this Question
Related Questions
Flip over an object (smooth transition) 3 Answers
Make movement of an object independant. 1 Answer
Unity C# 2D Adding Velocity on rotation 1 Answer
Multiple Cars not working 1 Answer
Flip Sprite C# 0 Answers