Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

I cant get my 2D Objects to collide

Discussion in '2D' started by slykrooper, Jan 5, 2020.

  1. slykrooper

    slykrooper

    Joined:
    Oct 27, 2018
    Posts:
    10
    Hey! so im trying to get two of my Game Objects to collide and no matter what I do I cant figure out why they wont. They both have boxcolliders2D and rigidbody2D and are both on the same layer.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerController : MonoBehaviour
    6. {
    7.     public float speed = 2;
    8.     public float rotationSpeed = 10;
    9.     public float verticalInput;
    10.     public bool gameOver = false;
    11.     // Start is called before the first frame update
    12.     void Start()
    13.     {
    14.  
    15.     }
    16.  
    17.     // Update is called once per frame
    18.     void FixedUpdate()
    19.     {
    20.         if (transform.position.y > 4)
    21.         {
    22.             transform.position = new Vector3(transform.position.x, 4 , transform.position.z);
    23.         }
    24.         if (transform.position.y < -4)
    25.         {
    26.             transform.position = new Vector3(transform.position.x, -4 , transform.position.z);
    27.         }
    28.         //Get vertical Input from player
    29.         verticalInput = Input.GetAxis("Vertical");
    30.  
    31.         //lets the player move
    32.         transform.Translate(Vector3.up * Time.deltaTime * speed * verticalInput);
    33.     }
    34.  
    35.     void onCollisionEnter2D(Collision2D collision)
    36.     {
    37.         if (collision.gameObject.CompareTag("Obstacle"))
    38.         {
    39.             Debug.Log("Hit");
    40.         }
    41.  
    42.     }
    43. }
    And the object I want to move does have the "Obstacle" tag as well. Let me know if you need any more info to help out, I super appreciate it!
     
  2. Chris-Trueman

    Chris-Trueman

    Joined:
    Oct 10, 2014
    Posts:
    1,256
    Don't use transform to move, it doesn't register collisions. You need to use the Rigidbody2D.velocity/Rigidbody2D.AddForce/Rigidbody2D.MovePosition to get collisions to happen.
     
    slykrooper likes this.
  3. slykrooper

    slykrooper

    Joined:
    Oct 27, 2018
    Posts:
    10
    You are amazing my guy! Thank you so much cus this has been driving me crazy lol.