OnCollisionEnter2D bug or missing some code - c#

i am totally new to c# scripting and unity... i was trying something on unity and created this code and it's woring fine but some times it's just overlapping "wall" tagged object or even getting out of that circle i am using Edge collider 2D on it and polygon collider 2D on my shooter object and this script is attached to shooter object. check the screen shot for the bug.
void OnCollisionEnter2D (Collision2D collider){
if (collider.gameObject.tag == "wall") {
StartCoroutine (shooterscale());
collider.gameObject.GetComponent<bgAnimater> ().animateBg ();
if (turn) {
turn = false;
}
else {
turn = true;
}
}
}

I assume you are using Rigidbody2D on the shooter.
Make sure that Collision detection mode is set to Continous to avoid objects passing through each other.
From Docs:
When the Collision Detection is set to Continuous, GameObjects with
Rigidbody 2Ds and Collider 2Ds do not pass through each other during
an update. Instead, Unity calculates the first impact point of any of
the Collider 2Ds, and moves the GameObject there. Note that this takes
more CPU time than Discrete.
and
When you set the Collision Detection to Discrete, GameObjects with
Rigidbody 2Ds and Collider 2Ds can overlap or pass through each other
during a physics update, if they are moving fast enough. Collision
contacts are only generated at the new position.
Hope this helps

Related

cant make my gameobjects change position after collision [duplicate]

First, I know that this question has been asked a lot, but I cant find a solution, so mi problem is, Im making an educational game, and I have a vein and the blood flow (with many box colliders) and a single blood cell (also with a box collider) however i want the cell to destroy when it reaches the wall collider, but it doesn't it just stays there, here is the project!
http://tinypic.com/r/10706es/9
(cant upload images because of my reputation, sorry)
The collider where I want to destroy my cell is the pink collider, however when it touches it it just does nothing, here's my script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class collision : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void OnCollisionEnter(Collision col)
{
print("hihi");
if (col.gameObject.tag == "Collider")
{
Destroy(gameObject);
}
}
}
Also, here is the AddForce script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AddForce : MonoBehaviour {
public float thrust;
public Rigidbody rb;
private Vector3 up;
private bool move;
void Start()
{
rb = GetComponent<Rigidbody>();
up = new Vector3(0, 1, 0);
move = false;
}
void FixedUpdate()
{
if (Input.GetKey("space"))
{
if (rb.velocity.magnitude < 5)
rb.AddForce(up * thrust);
move = true;
}
else
{
if (move == true)
rb.velocity = new Vector3(0, -0.5F, 0);
}
}
}
thanks for your help guys! :D
It can be several things, whether you are using OnTriggerEnter or OnCollisionEnter:
Missing RigidBody (the most common). At least one of the GameObjects involved needs to have a RigidBody. (check if at least one of them have a RigidBody attached and, if you are using OnCollisionEnter, does not have the "Is Kinematic" checked). See the below collision matrix for more information.
Missing tag. The GameObject from collision does not have a "Collider" tag (try to remove the if statement to test it) (to compare tags, use collider.gameObject.CompareTag("Collider"), it has a better performance)
Undetectable collision. The physics Layer Collision Matrix is set to not detect collision between the layers the objects are (enter Edit > Project > Phisics and check if the encounter of the layer of both GameObjects are checked inside Layer Collision Matrix)
Wrong Collider configuration. one or both of the GameObjects have a small/wrong placed or absent Collider (check if they both have a Collider component and if their size are correct)
If it's working, you should be able to press play and drag one GameObject into the other one and your Debug.Log will appear.
As an advice, use tag names that better describe the group of GameObjects that will be part of it, like "RedCells" or "WhiteCells". It'll be easier to configure the Layer Collision Matrix and improve the performance of your game.
Another advice: for colliders that just destroys another GameObject (don't react, like bump or actually collide) I use triggers. That way, the collision between them will not alter anything in the remaining GameObject (like direction/velocity/etc). To do that, check the Is Trigger in the Collider and use OnTriggerEnter instead of OnCollisionEnter.
Source
some times you added Nav Mesh Agent component to your game object ( to auto route operation in strategic game and ...).
in this case, this game object does not attend to collider.
So, if you really need this Nav Mesh Agent, you should add Nav Mesh Obstacle to other fixed game object and also add Nav Mesh Agent to other movable game object.
I have a few followup questions which might lead to a solution.
First, does the object holding your 'collision' script have a rigidbody and a collider on it?
Second, does the wall have both a rigidbody and collider?
Usually if those conditions are met, then collisions will work.
A couple other things that could be the problem:
Check if you have istrigger checked for either object and make sure it is unchecked.
Check and make sure the rigidbodies on both are non-kinematic.
I've finally fixed it, I dont really know if this was the problem, but i just removed the rigidbody from the parent of the wall and it started working!, I dont know what the rigidbody did, but just with that the problem was fixed, thank you all for your help! :D
Ensure the following things are considered in your code,
All gameobject should contain collider attached and the player
gameobject should contain the rigidbody component in it.
The collider size should change to the width and height of the
component instead of default (1,1) values.

Unity C#, Camera facing sprite and rigidbody not working together

I have a small piece of code to make a sprite (in a 3D world) always face the camera (It has to be in 3D space).
public class CS_CameraFacingBillboard : MonoBehaviour {
private Camera m_Camera;
private void Start()
{
m_Camera = Camera.main;
}
void Update()
{
transform.LookAt(transform.position + m_Camera.transform.rotation *
Vector3.forward, m_Camera.transform.rotation * Vector3.up);
}
}
This code ensures the sprite is always facing the camera, causing it to lean backwards as the camera in above the sprite facing down in a 45 degree agle. When I put a rigidbody on the sprite, the sprite moves on its own towards the direction its leaning. The rigidbody works fine without this code attached.
How can I have a sprite that always faces the camera, and has a rigidbody attached?
It seems you've left the rigidbody as Dynamic, you should set it to Kinematic.
EDIT: After you comments, I checked myself inside Unity, and probably I've recreated the behaviour you described. It happens to me too IF I use a Box Collider on the sprite without locking its rigidbody rotation.
So you have three possible solutions:
Use a Box Collider and under Constraints of the rigidbody freeze the rotation:
Use a Sphere Collider (or another one that doesn't behave like the box one, you can check them out in play mode).
Split the components over two game object, a parent and a child. The parent will have all the components except the sprite renderer and the camera script, which will be on the child. This option is the most flexible and less restraining. You can have the box collider without freezing rotations, etc.
Another thing, you can avoid the use of the LookAt method, by simply using:
transform.rotation = m_Camera.transform.rotation;
they have the same outcome.

Collision detection not working unity

First, I know that this question has been asked a lot, but I cant find a solution, so mi problem is, Im making an educational game, and I have a vein and the blood flow (with many box colliders) and a single blood cell (also with a box collider) however i want the cell to destroy when it reaches the wall collider, but it doesn't it just stays there, here is the project!
http://tinypic.com/r/10706es/9
(cant upload images because of my reputation, sorry)
The collider where I want to destroy my cell is the pink collider, however when it touches it it just does nothing, here's my script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class collision : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void OnCollisionEnter(Collision col)
{
print("hihi");
if (col.gameObject.tag == "Collider")
{
Destroy(gameObject);
}
}
}
Also, here is the AddForce script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AddForce : MonoBehaviour {
public float thrust;
public Rigidbody rb;
private Vector3 up;
private bool move;
void Start()
{
rb = GetComponent<Rigidbody>();
up = new Vector3(0, 1, 0);
move = false;
}
void FixedUpdate()
{
if (Input.GetKey("space"))
{
if (rb.velocity.magnitude < 5)
rb.AddForce(up * thrust);
move = true;
}
else
{
if (move == true)
rb.velocity = new Vector3(0, -0.5F, 0);
}
}
}
thanks for your help guys! :D
It can be several things, whether you are using OnTriggerEnter or OnCollisionEnter:
Missing RigidBody (the most common). At least one of the GameObjects involved needs to have a RigidBody. (check if at least one of them have a RigidBody attached and, if you are using OnCollisionEnter, does not have the "Is Kinematic" checked). See the below collision matrix for more information.
Missing tag. The GameObject from collision does not have a "Collider" tag (try to remove the if statement to test it) (to compare tags, use collider.gameObject.CompareTag("Collider"), it has a better performance)
Undetectable collision. The physics Layer Collision Matrix is set to not detect collision between the layers the objects are (enter Edit > Project > Phisics and check if the encounter of the layer of both GameObjects are checked inside Layer Collision Matrix)
Wrong Collider configuration. one or both of the GameObjects have a small/wrong placed or absent Collider (check if they both have a Collider component and if their size are correct)
If it's working, you should be able to press play and drag one GameObject into the other one and your Debug.Log will appear.
As an advice, use tag names that better describe the group of GameObjects that will be part of it, like "RedCells" or "WhiteCells". It'll be easier to configure the Layer Collision Matrix and improve the performance of your game.
Another advice: for colliders that just destroys another GameObject (don't react, like bump or actually collide) I use triggers. That way, the collision between them will not alter anything in the remaining GameObject (like direction/velocity/etc). To do that, check the Is Trigger in the Collider and use OnTriggerEnter instead of OnCollisionEnter.
Source
some times you added Nav Mesh Agent component to your game object ( to auto route operation in strategic game and ...).
in this case, this game object does not attend to collider.
So, if you really need this Nav Mesh Agent, you should add Nav Mesh Obstacle to other fixed game object and also add Nav Mesh Agent to other movable game object.
I have a few followup questions which might lead to a solution.
First, does the object holding your 'collision' script have a rigidbody and a collider on it?
Second, does the wall have both a rigidbody and collider?
Usually if those conditions are met, then collisions will work.
A couple other things that could be the problem:
Check if you have istrigger checked for either object and make sure it is unchecked.
Check and make sure the rigidbodies on both are non-kinematic.
I've finally fixed it, I dont really know if this was the problem, but i just removed the rigidbody from the parent of the wall and it started working!, I dont know what the rigidbody did, but just with that the problem was fixed, thank you all for your help! :D
Ensure the following things are considered in your code,
All gameobject should contain collider attached and the player
gameobject should contain the rigidbody component in it.
The collider size should change to the width and height of the
component instead of default (1,1) values.

Bullet not always hitting Enemy

void OnCollisionEnter(Collision col){
if (col.gameObject.name == "Enemy1") {
enemyDamage++;
GameObject clone = (GameObject) Instantiate (tempBloodSplat,enemyObj.position,enemyObj.rotation);
Destroy (clone , 0.5f);
if (enemyDamage > 3) {
anim.SetFloat ("Die", 0.5f);
Destroy (enemyObj.gameObject , 5.0f);
}
Debug.Log ("Bullet is hitting Enemy");
}
}
This is my code, i used on BulletObject
My Bullet Object has Collider
My Enemy has a Collider
My Enemy has a Rigidbody
Bullet is not having Rigidbody
I have problem that when i shoot, the bullet is hitting the Enemy in his range, like the circle under the body of the Enemy,Image
Sometimes the bullet hits correctly (means enemy is damaged), but sometimes the bullet moves out without making any damage to the enemy,I don't know why its happening.Does the velocity of the bullet has any effect on it..
Please help or guide me to solve this problem, Thanks
If you are not using a rigidbody on the bullet, then you are probably updating the bullets position vector directly, and what could be happening is the following:
. Since the bullet is not a rigidbody, Unity does not 'assume' it should behave like one and thus does not do an actual physics simulation of the bullet movement (which would probably include a raycast from start position to end position and colision checking in between). If you have a problem with adding a rigidbody to the bullet, then do the raycast yourself. You will even learn a bit of how the physics simulation behind unity actually might work!
Good Luck!

Collision detection not working in Unity 2D

I have two 2D game objects. They each have a Box Collider 2D and a Rigid Body 2D which is not kinematic. When the game plays, one moves towards the other and collides with it.
However, I also have the following method in the moving GameObject:
void OnCollisionEnter(Collision collision)
{
print( "Collided with someone" );
}
The print statement never prints, so presumably the method is never called. Where am I going wrong?
Unity has replicated all of the physics methods for 2D with the word "2D" stuck onto the end! So for your example, it should be changed to:
void OnCollisionEnter2D(Collision2D collision)
And the same with basically any other 2D physics thing.

Categories