Good day Unity members!
I am making a game in which my player (runner) must avoid getting hit by some obstacles and must destroy
an enemy ( food) which is a prefab. Upon collision with this enemy ( food), a sound is played and the player earns a score.
However, there are a few problems when I tried previewing my game.
-
When I tried to play the game, the player does not die when it collides with an obstacle.
-
When player (runner) collides with food, a sound is played but it KILLS player (runner) instead.
-
Why is the music already playing when I tried to play the game? it should only play when player (runner) collides with food.
Question: what went wrong? I have already asked some members here and followed their suggestions. Unfortunately, the code isn’t working as expected once I play the game.
I am attaching the codes and some screenshots for reference. Please let me know if I have missed something or some better solutions to my dilemma. Thank you.
Code for runner ( player)
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(AudioSource))]
public class runner : MonoBehaviour {
public Vector2 jumpForce = new Vector2(0, 1);
public AudioClip[] blips;
void Update () {
if (Input.GetKeyUp("space")) {
rigidbody2D.velocity = Vector2.zero;
rigidbody2D.AddForce(jumpForce);
}
Vector2 screenPosition = Camera.main.WorldToScreenPoint(transform.position);
if (screenPosition.y > Screen.height || screenPosition.y < 0)
Die();
}
void OnCollisionEnter2D (Collision2D other) {
if (other.gameObject.tag == "food")
{
Debug.Log("Collided food !");
audio.PlayOneShot(blips[0]); //part that changed
Destroy (other.gameObject);
}
else
Die();
}
void Die () {
Destroy(this.gameObject);
Application.LoadLevel(Application.loadedLevel);
}
}
Code for food
using UnityEngine;
using System.Collections;
public class foodpowgen1 : MonoBehaviour {
public GameObject sans;
int score = 0;
// Use this for initialization
void Start()
{
InvokeRepeating("CreateObstacle", 1f, 1.5f);
}
// Update is called once per frame
void OnGUI ()
{
GUI.color = Color.black;
GUILayout.Label(" Score: " + score.ToString());
}
void CreateObstacle()
{
Instantiate(sans);
score++;
Code for obstacle:
using UnityEngine;
using System.Collections;
public class obstacle : MonoBehaviour {
public Vector2 velocity = new Vector2(-4, 0);
// Use this for initialization
void Start()
{
rigidbody2D.velocity = velocity;
}
}
These are the respective screenshots of my player, obstacle and food.
Player’s screenshot:
obstacle screenshot:
food screenshot: