I have a simple collision detection program. The red object is controlled by the user and the yellow object is always moving up and down:
However, when the objects are supposed to collide, the red object ends up being underneath the yellow object. I wrote code that should destroy the red object on collision. This is a 2D game project, so I'm not sure how that works. They both have 0 set value for Order In Layer field.
Movement code for red object:
using UnityEngine;
using System.Collections;
public class Movement : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//GetKeyDown checks if a button is clicked, but GetKey checks if a button is held down.
//LEFT
if (Input.GetKey (KeyCode.LeftArrow))
{
transform.Translate(-1 * Vector2.right);
}
//RIGHT
if (Input.GetKey (KeyCode.RightArrow))
{
transform.Translate(Vector2.right);
}
//UP
if (Input.GetKey(KeyCode.UpArrow))
{
transform.Translate(Vector2.up);
}
//DOWN
if (Input.GetKey(KeyCode.DownArrow))
{
transform.Translate(-1 * Vector2.up);
}
}
}
Movement code for yellow object (contains collision event):
using UnityEngine;
using System.Collections;
public class EnemyMovement : MonoBehaviour {
private bool moveUp;
// Use this for initialization
void Start () {
moveUp = true;
}
// Update is called once per frame
void Update () {
if(transform.position.y == 30)
{
moveUp = false;
}
else if(transform.position.y == -30)
{
moveUp = true;
}
if (moveUp)
{
transform.Translate (Vector2.up);
}
else
{
transform.Translate (-1 * Vector2.up);
}
}
void OnCollisionEnter (Collision col)
{
if(col.gameObject.name == "player_character")
{
Destroy(col.gameObject);
}
}
}
Also, I'm a complete newbie with Unity, so sorry if I'm asking something that should be obvious.