#Make the player teleport to a certain coordinate

1 messages · Page 1 of 1 (latest)

jolly oracle
#

So I want to make my player object teleport to it's start position when it hits any object tagged with "Obstacle" I somewhat achieved that but the place my player teleports to is a bit off the actual start place.


public class PlayerCollision : MonoBehaviour
{

    void OnCollisionEnter(Collision colinf)
    {
        if(colinf.collider.tag == "Obstacle")
        {
            transform.position = new Vector3(0.019f,0.075f,0f);
        }
    }
}```
true phoenix
#

that code is correct from what I can tell. maybe you can instead have an empty transform at the start position, and for the PlayerCollision script, assign that transform in the inspector to a variable, then read the position from that transform instead of hard coding a vetor3
so that it is more modular/easier to change when the start position changes. and you can test changes easier

2 other things:

  • consider using https://docs.unity3d.com/ScriptReference/Component.CompareTag.html for slightly increased efficiency or tag checks
  • maybe there is a position offset that the character needs between start position and it's own, and that's why it isn't correct. or the start position has a collider that "pushes" the character out of it so it never looks optimal
#

@jolly oracle

jolly oracle
#

public class PlayerCollision : MonoBehaviour
{
    public Transform playerPos;
    void OnCollisionEnter(Collision colinf)
    {
        if(colinf.collider.tag == "Obstacle")
        {
            playerPos.position = playerPos;
        }
    }
}```
true phoenix
#

seems like you need to learn a bit more about c# and types
and just programming basics
why are you trying to assign playerPos to itself?
playerPos.position is a Vector3, playerPos is a Transform,
https://docs.unity3d.com/ScriptReference/Vector3.html
https://docs.unity3d.com/ScriptReference/Transform.html
you can't automatically convert these two, but transform has the position information

from your previous script I assume that PlayerCollision script is already on your player object. so you can access the player transform simply with "transform" which gives you the transform of the object your script is attached to
and then you'd assign the startPosition to the player pos

using UnityEngine;

public class PlayerCollision : MonoBehaviour
{
    public Transform startPoint;
    void OnCollisionEnter(Collision colinf)
    {
        if(colinf.collider.CompareTag("Obstacle"))
        {
            transform.position = startPoint.position;
        }
    }
}
jolly oracle
true phoenix