So I’m working on a 2D platformer game, and there is a void (obviously), but I don’t want the player to just jump off accidentally/on purpose and then keep falling forever. So I created an empty GameObject which was located a little below the platforms and attached a Rigidbody2D and Box Collider2D component to it and then made a custom script which I called “Respawn”. This is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Respawn : MonoBehaviour
{
public Rigidbody2D rgb;
public GameObject player;
// Start is called before the first frame update
void Start()
{
rgb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
}
public void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.name == "Player") {
player.transform.position = new Vector2(-8, -2); /* -8 and -2 are the coordinates of where the player is supposed to respawn */
}
}
}
I’ve attached the player as the player GameObject behaviour (or whatever it’s called can’t figure it out yet) in the inspector for this script. When I tested the game, it worked for the first time, I was teleported back to the top, but when I jump off again (immediately after respawning or even waiting for a bit in between) it doesn’t teleport the player back to the top and keeps falling forever. Does OnCollisionEnter2D only work once or something or is there something wrong in the script? Sorry I only started using Unity like last week and have only been using C# for about 2 to 3 weeks now.
Possibly because the player never “exits” the trigger because you teleport the player back to the start. So the trigger still thinks the player is there when it’s not, and thus cannot be triggered again. Could be wrong but just a hunch.
A much easier way to do it would just be to put in the Player’s Update() function something like:
I think what @AnthonySharp suggests is probably correct. When you directly assign transform.position, you are essentially bypassing the physics engine, so it never figures out that you left the trigger. It’s a teleport that bypasses the physics bookkeeping.
Instead, on line 25 above you can do :
rgb.MovePosition( new Vector2(-8, -2)); // move and give the Physics2D system a chance to process the move
That is how you should move anything with a Rigidbody/Rigidbody2D. You also wanna rotate such things with rgb.MoveRotation(myNewRotation); for the same reason.