Elevate object on mouse-over ?
I am making a tile based strategy game and i want to make it so when the mouse is over a certain tile, it elevates a bit and when the mouse is not on it anymore the tile reverts to it's former position. This is my code. It manages to lift the tile but it doesn't revert it to the original position for some reason. using System.Collections; using System.Collections.Generic; using UnityEngine;
public class TileSelection : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
Vector3 pos = hit.transform.position;
pos.y = 0.1f;
pos.y = Mathf.Clamp(pos.y, 0, 0.1f);
hit.transform.position = pos;
Debug.Log("We Got a Hit at: " + hit.collider.transform.parent.name);
}
else
{
Vector3 pos = hit.transform.position;
pos.y = 0;
hit.transform.position = pos;
}
}
}
Does anybody have any ideea how i can fix this ?
Answer by Hellium · May 27, 2018 at 02:39 PM
public class TileSelection : MonoBehaviour
{
private new Camera camera ;
private Transform lastHit ;
void Start()
{
camera = Camera.main ;
}
// Update is called once per frame
void Update ()
{
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
if( lastHit != null )
MoveDown( lastHit );
MoveUp( hit.transform );
lastHit = hit.transform;
Debug.Log("We Got a Hit at: " + hit.collider.transform.parent.name);
}
else if( lastHit != null )
{
MoveDown( lastHit );
lastHit = null ;
}
}
void MoveUp( Transform t )
{
Vector3 pos = t.position;
pos.y = 0.1f;
pos.y = Mathf.Clamp(pos.y, 0, 0.1f);
t.position = pos;
lastHit = hit.transform;
}
void MoveDown( Transform t )
{
Vector3 pos = t.position;
pos.y = 0;
t.position = pos;
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612163507im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to get exactly position of mouse in a gameObject when it's over it? 1 Answer
Pause my game with a game object! 0 Answers
How do I make an UI image apear over an invisible object? 0 Answers
Remove button OnMouseOver highlighting 0 Answers
How to add a different crosshair when mouse over an item 0 Answers