Throw the ball
Throw the candy ball and give it to the game character.
In this game, 2D physics and physics material are used in Unity.
Sample pictures
C# code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | using System.Collections; using UnityEngine; public class Ball : MonoBehaviour { public GameObject eatEffect; public Animator eatAnim; public AudioSource padAudio; private void OnTriggerEnter2D(Collider2D collision) { if(collision.tag == "Pad") { padAudio.Play(); } else if (collision.tag == "Player") { StartCoroutine(StartEat()); } else if(collision.tag == "Border") { gameObject.SetActive(false); } } IEnumerator StartEat() { eatAnim.SetTrigger("eat"); eatEffect.SetActive(true); yield return new WaitForSeconds(.2f); gameObject.GetComponent<SpriteRenderer>().enabled = false; yield return new WaitForSeconds(1f); eatEffect.SetActive(false); gameObject.GetComponent<SpriteRenderer>().enabled = true; gameObject.SetActive(false); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | using System; using UnityEngine; using UnityEngine.UI; public class Run : MonoBehaviour { public GameObject ball; Vector3 ballStartPos; public Text textX; public Text textY; void Start() { ballStartPos = ball.transform.position; } public void PlayBall() { int x = Convert.ToInt32(textX.text); int y = Convert.ToInt32(textY.text); ball.GetComponent<Rigidbody2D>().AddForce(new Vector2(x*100 , y*100)); } public void REstart() { ball.SetActive(true); ball.transform.position = ballStartPos + new Vector3(0, 1, 0); ball.GetComponent<Rigidbody2D>().velocity = Vector2.zero; ball.GetComponent<Rigidbody2D>().angularVelocity = 0; } } |