- Home /
why onCollisionEnter2D doesn't work when i use OnMouseDown or Up?
hi in android I make a game, and use OnMouseDown & UP for drag my object(player). there are some enemy that when player collide them it die. but when i drag player(on mouse down) to enemy collider, Oncollision2D doesn't work. please help me how to solve it. thanks.
Does the collision work when you are not dragging the player?
Also, I think it would be helpful if we can see the code that controls dragging the player.
@toficofi yes, when player collide enemy without dragging it work properly. i also added a script with oncollisionenter function to enemy but when i drag player it doesn't work. when player hit enemy itself both script work properly. thanks.
It would be good if you could share the code you use for dragging the player.
@$$anonymous$$ yes, both in default layer.
It's probably based on how you are moving your player when they mouse is down, you you are just setting it's position to the mouse position then physics won't work, you would have to make it move towards the mouse cursor using physics to not break the collision. I think. Posting your code would help a lot.
Answer by ahsen35813 · Mar 23, 2021 at 04:20 PM
I am guessing that this is because you are copying the mouse transform when moving it. Collisions will only be registered if at least one of the objects has a non kinematic rigidbody that is active. Try using something like playerRigidbody.AddForce(player.transform.position - mouse.transform.position)
to pull the rigidbody player towards the mouse instead of just copying the transform. Another thing that might work is using OnCollisionStay()
instead, because that should trigger as long as there is an overlap and the player's rigidbody is active.
thank you. i changed player's rigid body as kinematic and enemy's RB was kinematic so oncollision didn't work. i change enemy RB as dynamic then fix it.
Collisions will only be registered if at least one of the objects has a non kinematic rigidbody that is active.