So I'm basically making pong and lethal league combined, the paddles start with no collision until a certain key is pressed then the collider is enabled. OnTriggerEnter2D stops the ball, OnCollisionStay2D adds to an acceleration variable while the ball is still colliding, and OnTriggerExit2D flips the direction of the ball and applies the acceleration.
The problem I'm having right now is that Enter and Exit are being called every frame of the collision instead of the first frame and the frame after collision respectively, and Stay is never called at all, but that part is understandable.
Even if I comment out the OnTriggerExit2D function, which again applies the new speed and flips the direction, and essentially make the ball stop on collision, OnTriggerEnter2D will still fire each frame despite nothing moving.
I tried taking this to my professor but he wasn't of much help, I don't think I'll be able to get any help on this unless it's from here or I take my laptop to his office to show him what's going on. Please help
void OnTriggerStay2D(Collider2D c)
{
if (c.gameObject.transform.tag.StartsWith("Paddle") && acceleration <= 1)
{
acceleration += 0.1f;
}
}
void OnTriggerExit2D(Collider2D c)
{
if (c.gameObject.CompareTag("PaddleLeft"))
{
dir.x = 1;
speed = tempSpeed + acceleration;
}
if (c.gameObject.CompareTag("PaddleRight")
{
dir.x = -1;
speed = tempSpeed + acceleration;
}
}
void OnTriggerEnter2D(Collider2D c)
{
if (c.gameObject.transform.tag.StartsWith("Paddle"))
{
tempSpeed = speed;
speed = 0;
acceleration = 0;
}
}
OnCollisionStay2D
at the start of the question but usedOnTriggerStay2D
elsewhere. If you want collision detection you should use collision methods instead of triggers \$\endgroup\$Transform
component instead of theRigidbody2D
. Moving a physics collider with its transform forces it to be removed from the physics scene (causing OnTriggerExit2D to fire) then re-added in the new place (causing OnTriggerEnter2D to fire), so it never stays in contact, it's constantly teleporting in & out. This is one of the reasons why you should avoid moving a collider via its transform. \$\endgroup\$