- Home /
Unity 2D stop player when hit collider
Hy there. First, sorry for my bad english, im not native. Second: I few days ago i start playing around with Unity Third: I want to stop my player when he hits a collider. I gave him the static variable "Player" in a other code. But in this code i can't stop his movement. The code from " function OnTriggerEnter2D (hitInfo : Collider2D) { if (hitInfo.name == "Player") { Debug.Log ("Game Over");" works fine. Here is my code:
#pragma strict
var "Player" : Rigidbody2D;
function OnTriggerEnter2D (hitInfo : Collider2D) {
if (hitInfo.name == "Player") {
Debug.Log ("Game Over");
rigidbody2D.velocity.x = 0;
rigidbody2D.velocity.y = 0;
}
}
I hope you can help me.
Answer by robertbu · Feb 15, 2014 at 07:29 PM
Untested, but I believe this is what you want:
#pragma strict
var "Player" : Rigidbody2D;
function OnTriggerEnter2D (hitInfo : Collider2D) {
if (hitInfo.name == "Player") {
Debug.Log ("Game Over");
hitInfo.rigidbody2D.velocity = Vector2.zero;
}
}
That is, you want to use the hitInfo to address the player's rigidbody2d, not set the rigidbody2d on the object this script is attached to.
It seems logical to me, but it does not work. $$anonymous$$aybe it helps to know the other code:
#pragma strict
var moveUp : $$anonymous$$eyCode;
var moveRight : $$anonymous$$eyCode;
var moveLeft : $$anonymous$$eyCode;
var moveDown : $$anonymous$$eyCode;
static var String = "Player";
function Update ()
{
if (Input.Get$$anonymous$$ey (moveUp) )
{
rigidbody2D.velocity.y = 1 * 2;
}
else if (Input.Get$$anonymous$$ey (moveRight) )
{
rigidbody2D.velocity.x = 1;
}
else if (Input.Get$$anonymous$$ey (moveLeft) )
{
rigidbody2D.velocity.x = 1 -2.5;
}
else if (Input.Get$$anonymous$$ey (moveDown) )
{
rigidbody2D.velocity.y = 1 * -2;
}
else
{
rigidbody2D.velocity.y = 0;
rigidbody2D.velocity.x = 1;
}
}
The problem is that your code on your player will move s$$anonymous$$dily to the right when no key is pressed. The code you first posted will stop the object, but your code on the actual player resets that movement to (1,0) on the next update call, so it appears as if the first code does nothing. I'm not sure how to suggest you solve this problem since I don't know the mechanics of your game. You may want to add an OnTriggerEnter() to the player script that sets the idle movement to (0,0), and an OnTriggerExit() to set the idle movement back to (1,0). Or you may want to add a Raycast() to the second script that stops moving if an object is too close.
Your answer

Follow this Question
Related Questions
Detecting what surface character is moving on and restrict movement outside 1 Answer
How having correct bounce on a rotating pinwheel(it's more complicated)? 0 Answers
Wacky helicopter Please Help! 0 Answers
Cannot move FPSController after respawning at a spawn point. 1 Answer
Moving up and down (in a slope) without change to velocity or "bumping" 0 Answers