0
\$\begingroup\$

I know this has been asked before, but I don't understand why my code isn't working.

I'm doing top-down collision with no gravity.

Here is my wall and player entity

They both have Colliders

Here is my code :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

public class TankBodyControls : MonoBehaviour {

public KeyCode Foward = KeyCode.W;
public KeyCode Backward = KeyCode.S;
public KeyCode TurnLeft = KeyCode.A;
public KeyCode TurnRight = KeyCode.D;

public const float MaxSpeed = 6.0f;
public const float RotSpeed = 4.0f;

private Rigidbody2D TankBody;    


void Start () {
    TankBody = GetComponent<Rigidbody2D>();
}

void OnCollisionEnter2D(Collision2D coll)
{
    print("called");
    if(coll.collider.CompareTag("wall"))
    {
        print("collided!");
        var P = transform.position;
        P.x -= TankBody.velocity.x;
        P.y -= TankBody.velocity.y;

        transform.Translate(P);
    }
}

private void MoveTank()
{
    var Vel = TankBody.velocity;

    if(Input.GetKey(Foward)||Input.GetKey(Backward))
    {
        float VelMag = (Input.GetKey(Foward) ? MaxSpeed : -1.0f * MaxSpeed/2.0f);
        float VelAngle = transform.eulerAngles.z * ((float)Math.PI / 180f);
        Vel = new Vector2((float)Math.Cos(VelAngle), (float)Math.Sin(VelAngle));
        Vel *= VelMag;

        var rot = TankBody.rotation;

        if (Input.GetKey(TurnRight))
        {
            rot -= RotSpeed;
        }

        if(Input.GetKey(TurnLeft))
        {
            rot += RotSpeed;
        }

        TankBody.rotation = rot;
    }
    else
    {            
        Vel = Vector2.zero;
    }

    TankBody.velocity = Vel;
}


void Update () 
{
    MoveTank();
}
}

The idea was : if I detect a collision, shift the player out of the wall, the distance (velocity) they intersected it. My problem right now is, the OnCollisionEnter2D function doesn't even get called when they intersect (hence not console prints). Any idea what I'm doing incorrectly?

\$\endgroup\$
1
\$\begingroup\$

It's because your Rigidbody2D's Body Type is set to Kinematic. It should be Dynamic body type.

Kinematic body type will ignore force, joints, collisions. So what are you looking for is Dynamic body type.

Read Body Types here and Kinematic here.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.