I have a sprite of ball which moves when a player tap and holds the ball and move finger on the screen. I have a attached animations on it. straight, left, right and when the ball hits something.
Here is my code:
ball.cs
public RuntimeAnimatorController straight;
public RuntimeAnimatorController left;
public RuntimeAnimatorController right;
public RuntimeAnimatorController ballHit;
Animator animator;
Vector2 prevPos;
private void Start()
{
animator = gameObject.GetComponent<Animator>();
}
void Update ()
{
//Gets the world position of the mouse on the screen
Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
//Checks whether the mouse is over the sprite
bool overSprite = this.GetComponent<SpriteRenderer>().bounds.Contains(mousePosition);
if(GameObject.Find("GameController").GetComponent<brickMovement>().gameOver == true)
{
animator.applyRootMotion = true;
animator.updateMode = AnimatorUpdateMode.UnscaledTime;
animator.runtimeAnimatorController = ballHit;
}
//If it's over the sprite
if (overSprite)
{
//If we've pressed down on the mouse (or touched on the iphone)
if (Input.GetButton("Fire1") && GameObject.Find("GameController").GetComponent<brickMovement>().gamepaused == false && GameObject.Find("GameController").GetComponent<brickMovement>().gameOver == false)
{
float x = Camera.main.ScreenToWorldPoint(Input.mousePosition).x;
float y = Camera.main.ScreenToWorldPoint(Input.mousePosition).y;
//Set the position to the mouse position
prevPos = this.transform.position;
//Debug.Log(animator.runtimeAnimatorController);
if ((x > -1.938 && y > -4.51) && (x < 1.98 && y < 4.5))
{
//Debug.Log("Previous Pos: " + prevPos.x);
Debug.Log(IsThisObjectMoving());
if (this.transform.position.x < 0 && IsThisObjectMoving())
{
animator.runtimeAnimatorController = left;
}
else if (this.transform.position.x > 0 && IsThisObjectMoving())
{
animator.runtimeAnimatorController = right;
}
else if (this.transform.position.x == prevPos.x)
{
animator.runtimeAnimatorController = straight;
}
this.transform.position = new Vector3(Camera.main.ScreenToWorldPoint(Input.mousePosition).x,
Camera.main.ScreenToWorldPoint(Input.mousePosition).y,
0.0f);
}
}
}
}
bool IsThisObjectMoving()
{
Vector3 sek0pos;
Vector3 sek1pos;
sek0pos = gameObject.transform.position;
StartCoroutine(delay());
sek1pos = gameObject.transform.position;
if ((sek1pos.x - sek0pos.x) > 0f)
return true;
else
return false;
}
/*
Make function out of the above function that will check if object is
moving left or right.
*/
IEnumerator delay()
{
yield return new WaitForSeconds(1.0f);
}
I am having issue in detecting if ball is moving left or right. When ball is not moving straight animation should be played. but when it is the respective direction animation should be played.
Secondly when I do a hit animation it ends quickly without getting played properly.