- Home /
Player respawn with 2D collision not working
I have set up a script the is suppose to teleport the player to a game object using triggers. But when the player passes through the trigger nothing happens
My: Code
var spawn : Transform;
function OnTriggerEnter2D(other : Collider2D)
{
if (other.tag == "Player")
{
other.transform.position = spawn.position;
}
}
Comment
Can you confirm that the game objects in question have a Box Collider 2D (2D!) component attached?
Best Answer
Answer by brunocoimbra · Dec 30, 2015 at 08:30 AM
How are you moving your player?
First of all, a Rigidbody is needed to be attached to the player, as only an Rigidbodies and CharacterControllers can detect collisions with OnTrigger.
Also, transform.Translate will not let the player to detect collision with OnTrigger, but you can easily move your character changing the rigidbody's velocity.
A sample code to help you out:
private Rigidbody2D physics;
private Vector2 velocity;
void Start()
{
physics = GetComponent<Rigidbody2D>();
}
void Update()
{
velocity.x = Input.GetAxis("Horizontal");
velocity.y = Input.GetAxis("Vertical");
physics.velocity = velocity;
}
Didn't tested the code above, but it should work.