- Home /
Play animation C#
Hi Guys, I Have one problem. I have 2 animation. Anim_Left and AnimRight. So my question, this is the script I use in C#. If I swipe to the left, the animation "Anim_Left" has to play, and if I swipe to the right, animation "Anim_Right" needs to play. Someone who can help me out with this problem?
Thanks in advance.
//C#
//SwipeHandler.cs
using UnityEngine;
public class SwipeControl : MonoBehaviour
{
public float minMovement = 20.0f;
public bool sendLeftMessage = true;
public bool sendRightMessage = true;
public GameObject MessageTarget = null;
private Vector2 StartPos;
private int SwipeID = -1;
void Update ()
{
if (MessageTarget == null)
MessageTarget = gameObject;
foreach (var T in Input.touches)
{
var P = T.position;
if (T.phase == TouchPhase.Began && SwipeID == -1)
{
SwipeID = T.fingerId;
StartPos = P;
}
else if (T.fingerId == SwipeID)
{
var delta = P - StartPos;
if (T.phase == TouchPhase.Moved && delta.magnitude > minMovement)
{
SwipeID = -1;
if (Mathf.Abs(delta.x) > Mathf.Abs(delta.y))
{
if (sendRightMessage && delta.x > 0)
MessageTarget.SendMessage("OnSwipeRight", SendMessageOptions.DontRequireReceiver);
else if (sendLeftMessage && delta.x < 0)
MessageTarget.SendMessage("OnSwipeLeft", SendMessageOptions.DontRequireReceiver);
}
}
else if (T.phase == TouchPhase.Canceled || T.phase == TouchPhase.Ended)
SwipeID = -1;
}
}
}
void OnSwipeLeft()
{
transform.position -= Vector3.right*80;
}
void OnSwipeRight()
{
transform.position += Vector3.right*80;
}
}
Answer by TonyLi · May 02, 2013 at 01:30 PM
When starting out with Unity, there's a lot to learn. You'll find a lot of your own answers by reading the documentation and example projects. For example: http://docs.unity3d.com/Documentation/ScriptReference/Animation.html
The documentation will familiarize you with the different animation options. Unity 4 introduced the Mecanim animation system. But for your situation you might find the legacy animation system easier.
This is the scripting reference for the legacy Animation component. If you use it, your game object will need an Animation component. Add "Anim_Left" and "Anim_Right" to the animation list. Then add this code to your script:
void OnSwipeLeft() {
transform.position -= Vector3.right*80;
animation.CrossFade("Anim_Left");
}
void OnSwipeRight() {
transform.position += Vector3.right*80;
animation.CrossFade("Anim_Right");
}
I had the same script as this you gave me, I had this:
void OnSwipeLeft() {
transform.position -= Vector3.right*80;
animation.Play("Anim_Left");
}
void OnSwipeRight() {
transform.position += Vector3.right*80;
animation.Play("Anim_Right");
}
But I figured it out, Thanks!
Your answer
Follow this Question
Related Questions
GUITexture touch play animation 0 Answers
Proper way to play non looping animations 2 Answers
can't get fbx animation to play 3 Answers
How to get an object move by itself 2 2 Answers
Ped models do not want to play one animation at the same time 1 Answer