- Home /
On hover over object
I have a cool idea I am wanting to do but not sure how to do it. I the cube I have in my screen to rotate 90 degress when the mouse hovers over it. How would I start this? I have four different cubes I would like to do this. Each one only do it when I got over it.
Answer by InfiniBuzz · Jul 03, 2013 at 09:11 PM
Hi
you would create a script and attach it to all of the cubes.
In C# this would look something like this:
using UnityEngine; using System.Collections;
public class example : MonoBehaviour {
void OnMouseEnter() {
transform.Rotate(Vector3.up * 90); // or whatever roatation you want
}
// to reset:
void OnMouseExit() {
transform.Rotate(*your inverse rotation*);
}
}
hope it helps
-edited
over time:
void OnMouseOver() {
Vector3 rotation = transform.rotation.eulerAngles;
if(rotation.y < 90)
rotation += new Vector3(0, rotation.y + 90 * Time.deltaTime, 0);
transform.eulerAngles = rotation;
}
try this, it will rotate your object 90 degrees in one second. If you want it slower, decrease the angles. I didn't test it ;)
Wouldn't On$$anonymous$$ouseOver continue to rotate the screen every frame? Also, depending on @davidflynn2's desired interaction, it might be useful to rotate gradually, rather than jumping 90 degrees in a single frame.
yes indeed, I edited it to On$$anonymous$$ouseEnter. He didn't say he want it to rotate gradually so I just answered what I thought he want :) but you're right, it would probably look better.
Yes that does what I want what would I have to change to make it happen over time that might improve what im looking at?
I tired adding "* Time.deltaTime" but it don't rotate all the way around then.
I edited my answer. You need to set it to On$$anonymous$$ouseOver so that it runs every frame. And then you have to check if it already is 90 degrees.
Answer by ebogguess · Jul 03, 2013 at 09:15 PM
It sounds like you need to get more familiar with performing actions on hover and rotating the camera/screen. OnMouseOver is the method that gets called on every frame that the mouse is over a collider, and OnMouseEnter is a method that is called when the mouse first enters a collider. Camera.main accesses your main camera, and from there you can manipulate it's transform (including rotation).
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Object won't rotate correctly 2 Answers
Why is my camera switching angles? 0 Answers