Travis
Travis

Reputation: 25

Issues on collision detection

Not sure why my collision is not causing my console to print out "i hit enemy". Player has a rigidbody component, enemy does not.

My enemy has the tag Enemy. Enemy is moving about using transform. My player has the rigid body component, my enemy does not. Any ideas?

using UnityEngine;
using System.Collections;

public class PlayerMovement : MonoBehaviour {
public float moveSpeed;
public float maxSpeed = 5f;

private Vector3 input;
private Rigidbody rb;

// Use this for initialization
void Start () {
    rb = GetComponent<Rigidbody>();
}

// Update is called once per frame
void Update () {
    input = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));

    if (rb.velocity.magnitude < maxSpeed) {
        rb.AddForce(input * moveSpeed);
    }      
}

void onCollisionEnter(Collision other)
{
    if (other.transform.tag == "Enemy")
    {
        print ("I hit enemy");
    }
}
}

Upvotes: 1

Views: 63

Answers (2)

Programmer
Programmer

Reputation: 125445

Another simple mistake for new Unity users. Spelling counts! Simply replace onCollisionEnter with OnCollisionEnter. The callback functions are case sensitive and their first letter is usually capitalized.

If changing this does not work, attach Rigidbody to your enemy too. Make sure they both have Colliders attached to both of them and that IsTrigger is not enabled.

Upvotes: 1

fatel
fatel

Reputation: 209

Several solutions could fit. Maybe you simply forgot to set the tag on your enemy? Please have a look at the Unity3D collision matrix (https://docs.unity3d.com/Manual/CollidersOverview.html - at the bottom of the page).

The collision matrix tells you when you will get collision messages. E.g. you can't have a static collider colliding with a rigidbody collider. Recheck all your gameobjects. Are they fitting the needs of a collision?

Upvotes: 0

Related Questions