How to create a "clicking effect" on a 3d-object (3d-cube) in Unity3d? - animation

I have a 3d-object (cube), which I want to use as a button. I've written the code in order to detect, if the cube was pressed but it doesn't look like it was pressed, since it lacks the "clicking animation". How can I create a clicking animation on my 3d-object ?

A good idea is to play an aninimation which skrinks the cube a bit and releases it immediately afterwards. The handler code you want to execute on a click might block the game loop, e.g. when you load a level. Then it might be useful to load the level aysnchronously to be able to see the animation. Or you execute the handler code after the animation. Or you play the scale down animation on the press event and the scale up animation on the release event.
Technically you can use the build in animation editor, the Update() method, start a coroutine or use the assets iTween or HOTween.
http://docs.unity3d.com/ScriptReference/Transform-localScale.html
Let me know if you like the idea or questions arise.

Unity makes it easier now to do this using Unity Canvas UI. Instead of real 3d buttons, you could place a canvas UI in world space at the location where you want the buttons. Add a UI Panel to the canvas then add a UI Button.
Now, you have out of the box several clicking effects. The default it color tint, but you can choose sprite swap, or animation.
If you do want animation, when you select button animation it will create an animator for you. Click on your UI button Game Object in the scene hierarchy and open the animation window. You can choose Pressed animation from the drop down, and press RECORD button, then edit your buttons scale, say make it 0.75 for x,y,z. Now when you click on the button it will animate a cool scale down for you.
Sorry, I know that is a lot of information dumped! But you will find it pretty great once you start working with it in world space.

You can scale it down a tiny bit once click happen. For example:
void OnMouseDown() {
this.transform.localScale += new Vector3(0.05f, 0.05f, 0.05f);
}
Then after click scale it back to the original size.

Perhaps look into iTween (free on Unity Asset store).
Its very easy to use and you can produce some nice looking animations.

you can scale it when pressed or just change the color a little bit. On mouse up, rescale or recolor it.
void OnMouseDown()
{
transform.localScale -= new Vector3(0.05, 0.05 , 0);
//or
transform.GetComponent<SpriteRenderer>().color += new Color(40,40,40);
}
void OnMouseUp()
{
transform.localScale += new Vector3(0.05, 0.05 , 0);
//or
transform.GetComponent<SpriteRenderer>().color -= new Color(40,40,40);
}

You can implement your button using new Event system of unity. Here are the functions you can implement :
public class ExampleClass : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerClickHandler, IPointerEnterHandler, IPointerExitHandler
{
public void OnPointerEnter(PointerEventData eventData)
{
//it is the function when you hover your mouse to the object
//You can change the color of your object to make your users
//understand that it is not just a cube but also a clickable item
}
public void OnPointerExit(PointerEventData eventData)
{
//You can revert your color back to its original
}
public void OnPointerDown (PointerEventData eventData)
{
//You can play with local scale as suggested by other answers here
}
public void OnPointerUp (PointerEventData eventData)
{
// Revert back the changes you made at onPointerDown
}
public void OnPointerClick (PointerEventData eventData)
{
//Use here for operations when your button is clicked
}
}

Related

Different animation in 2 directions

I’m really just a beginner & I have no idea how to use the animation in Unity properly. I’m working on a 2D platformer game. I managed to make the animation work, but the point is that my character should looks different from each side (so I can’t just flip the sprite). What’s the simplest way to for example, when pressing right he will use animation 1 and when pressing left he will use animation 2? Thanks in advance & sorry about my stupidity;)
Did you try using Animator Controller.
[RequireComponent(typeof(Animator))]
public class PlayerAnimation: MonoBehaviour
{
[SerializeField]private Animator _animator;
private const string DirectionParam = "Direction";
private void Update()
{
//On Right button clicked
if (Input.GetKeyDown(KeyCode.RightArrow))
{
//Play Right animation
_animator.SetInteger(DirectionParam, 1);
}else if (Input.GetKeyDown(KeyCode.RightArrow))
{
_animator.SetInteger(DirectionParam, -1);
}
else
{
_animator.SetInteger(DirectionParam, 0);
}
}
}
Drag this script on you player. This will also Add unity Animator Component on your game object.
Create Animator Object and place it on the animator component.
open Animator Editor from Window>Animation>Animator
Then create an int parameter in Animation Controller Window and name it "Direction".
Create two animation clips one for left move animation and another for right move animation
Drag these clips to the animator Window. Right click and create two transition and add condition with Direction parameter. You should create 3 animation clips and set that to idle and transition to idle when the direction value is 0.
Enjoy!

How to higlight button color when hover the mouse after a click?

I'm doing a piano application thought to be played on mobile devices (Android). All the piano keys are UI buttons that have the "property" pressed color to a grey one in order to properly indicate when a piano key is emiting sound.
My current problem is that when I first click on a key and after that I drag the mouse over the following keys, only the first one that I clicked is getting the change of color (the idea is that the change of color duration finishes when other key starts sound and then the new key where I pass the mouse-finger gets the grey color).
I also tryied setting the higlighted color property to the same color as the pressed color with the Navigation parameter to none (if it's set to automatic it happens some kind of bug that the color is getting "stuck" until I make sound another key), but the result it's still the same.
EDIT:
I update the issue with some progress thath I made:
I'm trying to change the pressed color with a script thanks to the events Pointer enter and exit (both events are placed on a Event trigger in every button).
Code:
public class ChangeKeyColor : MonoBehaviour{
public Button button;
void Start()
{
}
void Update()
{
}
public void EnterKey () {
Debug.Log("Enter the key");
ColorBlock colors = button.colors;
colors.normalColor = new Color(179, 179, 179, 255);
//colors.highlightedColor = new Color32(179, 179, 179, 255);
button.colors = colors;
}
public void ExitKey()
{
Debug.Log("Exits the key");
ColorBlock colors = button.colors;
colors.normalColor = Color.white;
//colors.highlightedColor = new Color32(255, 255, 255, 255);
//colors.pressedColor = Color.white;
button.colors = colors;
}
}
The only improvement that I obtained is that now when I'm dragging the mouse (maintaning it) the first button returns to white color, but I think that this is happening because now I only setted to gray color the pressed color option...
Does anyone know why the pressed color change that I'm making in the script isn't happening? When I drag the mouse to another key isn't considered as a pressed button?
Regards!
I'm not sure if you are still looking for the answer, but I finally had some time to try it myself.
What I did is changing color and debug-logging transform's name instead of playing sound.
My code for Images/Buttons (attached to each Image, I didn't use Button components):
using UnityEngine;
using UnityEngine.UI;
public class ChangeColor : MonoBehaviour {
public Color activeColor, notActiveColor;
private Image thisImage;
void Awake () {
thisImage = GetComponent<Image>();
}
public void OnPointerClick()
{
Activate();
}
public void OnPointerEnterAndDown()
{
if (Input.GetKey(KeyCode.Mouse0))
{
Activate();
}
}
public void OnPointerExit()
{
thisImage.color = notActiveColor;
}
private void Activate()
{
Debug.Log(transform.name);
thisImage.color = activeColor;
}
}
EventTrigger settings:
And this is what it looks like in the end:
(This should be a comment, but it's a little long, so reply me and I'll update the answer)
I don't know why are you having this problem, I do the simple test creating 2 UI Buttons and setting the highlighted color to red, and the pressed to blue.
By default (there's no script attached to anything) the behaviour is the follow:
1.If I press (and mantain) the click on a button, that button is blue, when I release the "pression", the button keeps red.
2.While this first button is red, if I drag the mouse over the second button, this will be also red.
3.If now I press on the second button, the first behaviour applies to the second button, and the first one will be white again.
This is the following behaviour that you want, according to what I understood.
So, if this is not the desired behaviour, tell us more about what you want.

LibGDX-Scene2D: How to make hud with multiple buttons?

I'm making an Idle Game but now I don't know how to make the listeners of the HUD. It's okay to instantiate an InputListener() in every button of my hud? I have like 20 buttons or actors to touch.
Simply use addListener() method for every actor that you want to be clicable. I used to use ClickListener for this purpose although it is sometimes recommended to use ChangeListener due to better behaviour when the button is being disabled.
So what you need to do is just
Button button;
//creating button...
button.addListener(new ClickListener(){
#Override
public void clicked(InputEvent event, float x, float y)
{
//Do something
}
});
and the same for another buttons/actors on your HUD stage.
You can also take a look at this thread where I have asked about performance of many listeners.
Here is a scene2d button, which is really easy to use, I dont understand what the issue is or why you are worried about having a listener on each button or UI object, seems pretty logical to me.
button = new Button(buttonStyle);
button.setPosition(x, y);
button.addListener( new ClickListener() {
#Override
public void clicked(InputEvent event, float x, float y) {
Gdx.app.log(TAG, "Button clicked");
};
});

Unity 3D: Changing sprite animation using UI button

I'm following this tutorial on youtube about changing sprite animation in code, and I was wondering if I could change this to changing sprite animation using UI button. does anyone knows how to do this. Thank you!
EDIT:
The script that I reposed kind of works thanks to your help, it changes the sprite image from image one to image two but what I'm basically trying to achieve is that each time that I click the UI button the sprite image will change from sprite image one (UI button click)> sprite image two (UI button click)> sprite image three (UI button click)> then repeat the process instead of the sprite image automatically changing itself.
Buttons have an OnClick event http://docs.unity3d.com/ScriptReference/UI.Button-onClick.html
You just create a method that gets called when the button is clicked, in your case the changing sprite code. Seen as you are using a timer though you will need to use something like a bool because onClick() only gets called once when clicked, not every frame.
Look https://www.youtube.com/watch?v=J5ZNuM6K27E
bool b_RunSpriteAnim;
public void onClick(){
b_RunSpriteAnim = true;
}
void Update(){
if (b_RunSpriteAnim)
//your anim sprite stuff
}
Then once the sprite anim has finished, just toggle b_RunSpriteAnim to false and reset the timer.
Edited:
You don't need a boolean. I only thought you wanted it because you were using a timer (as based on the Youtube link). If you just want to change the sprite immediately then you do not need it. As for Imagethree not working, it's because you have never included it in your code. It isn't clear what you are trying to achieve with Imagethree, if you included this in onClick as well it would just overwrite the image two that was just set, so I am not sure what you are looking to achieve.
public void onClick(){
this.gameObject.GetComponent<SpriteRenderer>().sprite = Imagetwo;
}
Second Edit:
public Sprite[] Images;
//Index starts at one because we are setting the first sprite in Start() method
private int _Index = 1;
void Start(){
//Set the image to the first one
this.gameObject.GetComponent<SpriteRenderer>().sprite = Images[0];
}
public void onClick(){
//Reset back to 0 so it can loop again if the last sprite has been shown
if (_Index >= Images.Length)
_Index = 0;
//Set the image to array at element index, then increment
this.gameObject.GetComponent<SpriteRenderer>().sprite = Images[_Index++];
}

WP7 transition between Canvas's in a Grid

I have two canvas's in a Grid, full scene "images" that I want to transition, I wonder how I would go about transitioning between these two Canvas controls.
Programatically I add the first canvas to the grid, then I add the second canvas to the grid, and remove the first, what I really want to do is transition between them.
Any suggestions on how I might achieve this programatically?
Thanks.
Edit: I have implemented this method, but am having problems, anyone able to tell me if I'm using it wrong?
private void doTransitionIn(Canvas slide)
{
SlideTransition slideLeft = new SlideTransition();
slideLeft.Mode = SlideTransitionMode.SlideDownFadeIn;
ITransition transition = slideLeft.GetTransition(slide);
transition.Completed += delegate { transition.Stop(); }; transition.Begin();
}
private void doTransitionOut(Canvas slide)
{
SlideTransition slideLeft = new SlideTransition();
slideLeft.Mode = SlideTransitionMode.SlideDownFadeOut;
ITransition transition = slideLeft.GetTransition(slide);
transition.Completed += delegate { transition.Stop(); }; transition.Begin();
}
And here is how I use it:
SceneGrid.Children.Add(nextCanvas);
doTransitionIn(nextCanvas);
doTransitionOut(currentCanvas);
SceneGrid.Children.Remove(currentCanvas);
The problem with this is that the animation only seems to start from part way down the screen, as in, i only see it slide the last 20 or so pixels, it doesn't slide all the way.
Depending on what you mean by "transition" I'd look at creating a StoryBoard to animate the hiding/showing of each canvas.
I would recommend using the TransitioningContentControl which is part of the Silverlight Toolkit. To use this control, make your first Canvas the Content of this control. To transition, simply change the Content to your next Canvas and the TransitioningContentControl does the rest!
There are a number of blog posts that provide tutorials for this control:
http://blogs.academicclub.org/uidev/2010/06/12/transitioning-content-in-silverlight/

Resources