Weird ContactPoint2D on two BoxCollider2D collision - unity3d

Well, while creating a kind of 2D platformer using Tilemaps for creating levels consisting of blocks I stumbled upon a problem with weird contact points I get on collision between my player's BoxCollider2D and TilemapCollider2D. I need to detect what tiles specifically the incoming collider is colliding with and because of this problem I often gain wrong tiles positions. Then I discovered that the very same problem of detecting contact points is actual for the collision of two BoxCollider2D so here is the test with them.
The last frame before the collision was detected. BoxCollider of a cube is perfectly aligned to the grid. Player's falling on collider from above (Collision Detection mode is Discrete).
The next frame. Player's collider changed it's position trying to get out of collider what is OK. Red dots are bottom corners of the collider from the previous frame and white dots are contact points returned at this frame from Collision2D.GetContacts(). We get two points, but the left one is out of collider bounds. I expected (and it seems quite logical) that all the points must be inside the colliders intersection area.
Here is the script attached to the Square that gets contacts and places dots in them:
public class Test : MonoBehaviour
{
[SerializeField] private BoxCollider2D _collider;
[SerializeField] private GameObject _contactDotWhite;
private ContactPoint2D[] _contacts = new ContactPoint2D[5];
private void OnCollisionEnter2D(Collision2D other)
{
other.GetContacts(_contacts);
for (var i = 0; i < other.contactCount; i++)
{
ContactPoint2D contact = _contacts[i];
GameObject go = Instantiate(_contactDotWhite);
go.transform.position = contact.point;
}
}
}
So, the questions are: how unity calculates these contact points? Is this a normal behaviour at all? If it's not, how do I fix it?

Related

Collision Layer Matrix and Parent/Child object relationships

I come here after some testing, and because after some googling, I was incapable of finding a straight answer.
Suppose I have a player character with a tag set to Player and a layer set to Humanoid. I also have a bunch of NPC performing patrol, wander, and other movement behaviors. Their tags are set to NPC and their layers to Humanoid. Since this is a 2D game using 2D physics, I used the Project Settings collision matrix to make it so that Humanoids do not collide with each other.
In other words, the NPCs and the player characters can pass through each other, while respecting gravity, force, impulse, etc... This is working fine. My problem arises when: I want some child GameObject of NPC which is in layer Default and has a CircleCollider2D of type Trigger and I want to detect that collision in order to perform some actions (e.g.: show dialogue, stop or switch AI Behaviour of the parent object, or others).
From my testing, this seems not to be working, but I might be doing something wrong. So my question is:
If a GameObject A ignores collisions against layer X, will collisions against a GameObject C in layer Y be ignored if C is a child of a GameObject P in layer X?
private void OnCollisionEnter2D(Collision2D other) {
if (other.gameObject.CompareTag("Player")) {
Debug.Log("Collided with player");
}
if (!eventConsumed && other.gameObject.CompareTag("Player")) {
var draw = Random.Range(0.001f, 1.0f);
if (draw > 1.0f - eventChance) {
dialogueEvent.Play();
dialogueEvent = null;
}
eventChance = Mathf.Clamp(eventChance * 1.33f, 0.0f, 1.0f);
}
}
In order to detect whether or not a physics collider that is set as a trigger has collided. You would need to use the OnTriggerEnter2D function instead of the OnCollisionEnter2D function.

How to detect a potential collision in Unity?

I have a Unity game I am working on as a hobby and have come across an interesting issue with how to best handle collision detection. My problem here is that my game is a 2D turn-based game, whereby a game object can move a fixed distance each time in a non-grid based world space. I have my game objects currently using BoxCollider2D to handle collision detection, but I need to be able to determine if there will be a collision BEFORE actually making a move, which right now causes the game object to overlap another game object and fire the OnCollisionEnter2D event. The eventual idea here is to allow a player to plan out a move and have a "navigation guide" appear next to the object to show move options based on the game object's move capabilities.
Is it possible to take my game object's collider, transform its position to move or rotate it, see if a collision would occur, but NOT actually move the object itself?
You mean like simply using Rigidbody.SweepTest ? ;)
Tests if a rigidbody would collide with anything, if it was moved through the Scene.
From the example
public class ExampleClass : MonoBehaviour
{
public float collisionCheckDistance;
public bool aboutToCollide;
public float distanceToCollision;
public Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
RaycastHit hit;
if (rb.SweepTest(transform.forward, out hit, collisionCheckDistance))
{
aboutToCollide = true;
distanceToCollision = hit.distance;
}
}
}
Oh just noted that actually this is only for 3D Rigidbody.
For 2D this doesn't exist but can be kind of replicated using instead Collider2D.Cast
Casts the Collider shape into the Scene starting at the Collider position ignoring the Collider itself.

How to keep the same velocity after bumping into things ? (Unity 2D)

My game (2D Top-Down view) is about a tank that fires bouncing bullets. Those bullets have infinite bounces and keep the same velocity after bouncing. It works fine with static objects, however it doesn't keep the same velocity with moving objects : the bullet can push things, but will slow and I don't know how to remove the slow.
Here is a tweet where you can see the bullets slow down after touching some objects :
https://twitter.com/TurboDevTeam/status/1350751139508215808?s=20
Edit :
Here are the parameters of the bullet :
derHugo's comment is on point: since the cars move when hit, they absorb part of the energy.
I've set up a minimal example to demonstrate.
The ball has a CircleCollider2D and a Rigidbody2D with Linear Drag = 0 and a material with Friction = 0 and Bounciness = 1.
The walls have a BoxCollider2D and a Rigidbody2D. Gravity is disabled.
For the first test, the wall Rigidbody2D is set to Static.
For the second test, the wall Rigidbody2D is set to Dynamic, with Mass = 10 and Linear Drag = 1.
In order to keep it bouncing forever in this case, you must code the bounciness by yourself. First remove the Physics Material or set the bounciness to 0, to make sure the Physics Engine is not simulating it.
Then, create a script for the bullet:
public class Bullet : MonoBehaviour
{
private Vector2 lastVelocity;
void FixedUpdate()
{
lastVelocity = GetComponent<Rigidbody2D>().velocity;
}
void OnCollisionEnter2D(Collision2D collision)
{
GetComponent<Rigidbody2D>().velocity = Vector2.Reflect(lastVelocity, collision.contacts[0].normal);
}
}
(Please note that you should use GetComponent carefully, maybe calling it only once on Start and saving a reference, I didn't do it to keep a minimal sample.)
The idea here is to take the velocity right before the collision and invert it. However, if you take the Rigidbody2D velocity on OnCollisionEnter, it's already the updated value. So you must store the value in FixedUpdate, since the next is only called after the OnCollisionEnter method.
Then, you use Vector2.Reflect to reflect the incoming velocity by the collision normal.
Vector2.Reflect results are valid in 2D:

Unity - Tricky Particle Collisions

I am making a prototype for my 2D game. It consists of a ball that launches missiles that are aimed to explode where the user clicks. The explosion of the missile releases particles, which hit the ball and exert a force on the ball. Here is a video.
I used a standard particle system with the Collision module activated. Then attached this script to the particle systems created be each explosion:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class particleInteraction : MonoBehaviour {
//PS Variables
ParticleSystem myPS;
public List<ParticleCollisionEvent> particleCollisions = new List<ParticleCollisionEvent>();
//Physics variables
public float effect;
// Use this for initialization
void Start () {
myPS = GetComponent<ParticleSystem>();
}
void OnParticleCollision (GameObject other)
{
//Checking if the hit object is indeed the ball
if (other.tag.Equals("Player"))
{
Rigidbody2D hitObject = other.GetComponent<Rigidbody2D>();
//Getting the number of particles hat hit the ball
int noOfCollisions = myPS.GetCollisionEvents(other, particleCollisions);
Vector3 particleDirection = new Vector2(0,0); //The overall velocity of all the particles that collided
//Iterating through all the collisions and adding their vectors
for (int i = 0; i < noOfCollisions; i++)
{
particleDirection += particleCollisions[i].velocity;
}
//Applying the resultant force
hitObject.AddForce(particleDirection.normalized * effect * noOfCollisions);
}
}
}
This mostly works, however it causes a problem. The missile are designed to explode when they hit the walls too, so when the ball is on a wall I expect a missile aimed at the wall to push the ball off of it. However, the ball simply jerks away from the wall in the next frame (can be seen in the video). I believe this is because of the colliders on the particles instantiating inside of the ball's collider. This causes the physics engine to immediately move the ball away in the next scene.
So I tried using OnParticleTrigger, however I realized that Unity doesn't provide info on the gameobject affected in particle triggers, so I cannot affect the ball.
Could anyone help me find a way to make this work? I want to avoid the jerky movement caused by the intersecting colliders, or maybe use a better method expressing the missile explosions.
reduce the Radius Scale under the Collision Tab.
you can visually debug this using visualize Bounds checked inside the module.

Unity - Inconsistant speed of object following raycast2D

So im creating a simple game and one component of the game is a greendot following the outside of the level. I got this working using a raycast in the middle which rotates and gives the position of collision the the gameobject.
game overview
The problem is that the speed is inconsistant at the moment since the distance between two collisions can be further distance if i have a slope. I also have the feeling that there should be a easier way to get the same result. What are your thoughts?
public class FollowPath : MonoBehaviour {
Vector3 collisionPos;
public GameObject greenDot;
void Update ()
{
RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.up);
transform.Rotate(0.0f, 0.0f, 3);
if (hit.collider != null)
{
collisionPos = hit.point;
}
greenDot.transform.position = collisionPos;
}
}
I'm not sure if you will like this answer, as it suggests a complete departure from the way you were trying to do it.
A simple way to do this, would be to give your moving dot GameObject a Rigidbody2D component, AND a CircleCollider component.
Then, make your walls, and add to each an EdgeCollider component.
You'll probably also want to add a PhysicsMaterial2d to each GameObject with a Collider and set the friction and bounciness values for each.
Once this is setup, you can apply an initial force to the rigid body ball to get it moving, and it will bounce off the walls just like a ball does, using the Unity physics engine. No code would be needed in you update functions.