- Home /
Question by
Ulluses · Jul 07, 2017 at 03:31 PM ·
raycastloopraycasthit2dmouseovercolor.lerp
Raycast for mouseover isn't working
The sprite is a child of a rigidbody gameobject so I went with raycasting to detect when the mouse is over the trigger box of sprite. So far all I have are null references and that's about it, the loop won't start. I think it's something to do with the hit variable but I don't know how to fix it.
Here's the code:
void Update () { CurrentAlpha = SpriteRend.color; CheckForHover(); }
private void CheckForHover ()
{
Ray ray = Camera.main.GetComponent<Camera>().ScreenPointToRay(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, Mathf.Infinity);
if (Hovered == false && hit.transform.gameObject == this.gameObject)
{
Debug.Log("Beep");
Hovered = true;
FadeIn();
}
if (Hovered == true && hit.transform.gameObject != this.gameObject)
{
Debug.Log("Boop");
Hovered = false;
Fadeout();
}
}
private IEnumerator FadeIn ()
{
float ElapsedTime = 0.0f;
float TotalTime = 10.0f;
while (ElapsedTime < TotalTime)
{
ElapsedTime += Time.deltaTime;
SpriteRend.color = Color.Lerp(CurrentAlpha, Visible, (ElapsedTime / TotalTime));
yield return null;
}
}
private IEnumerator Fadeout()
{
float ElapsedTime = 0.0f;
float TotalTime = 10.0f;
while (ElapsedTime < TotalTime)
{
ElapsedTime += Time.deltaTime;
SpriteRend.color = Color.Lerp(CurrentAlpha, Invisible, (ElapsedTime / TotalTime));
yield return null;
}
}
Comment
Your answer
Follow this Question
Related Questions
New UI ~ Check for mouse-hover 1 Answer
OnCollisionEnter2D is not working 0 Answers
0 Understanding of raycast2D commands 2 Answers
Raycasting and foreach loops 1 Answer