How to offset position on gameobject axis not global axis?

this should check if my left side is obstructed, if it is, i would get out of the car on the other side
but for now i get out literally on the global right side whic could be in front of the vehicle if standing along the axis.

hit = Physics2D.Raycast(currentVehicle.transform.position,-currentVehicle.transform.right,1f);
        if (hit.collider != null) {
            Debug.Log (hit.collider.gameObject.name + "Left obstacles");

        }
        else
        {
            getOutSide = new Vector3 (transform.position.x -2, 0, 0); // this is wrong
            PC.Instance.transform.position = currentVehicle.transform.position + getOutSide;
            return;
        }

the way you wrote your code, the player exits to the right when NO collider was hit on the left, also if you do not want global axis you should use transform.localPosition.

are you sure ?.. i think the logic is working… and i already tried localposition…he always leaves at the same spot

No not sure at all, but if the logic is that if the ray hits a collider to the left then

if (hit.collider != null) // an obstacle prevents the player from exiting the car on the left
{
    // the player should exit from the right side of the car
}
else // no obstacles found to the left
{
    // the player should exit from the left side of the car
}

or am I missing something here?

you miss a few lines after because i need to do something if no side is actually free.
so i got this part working but that’s not part of the question. .:- )
i need him to get out on the side of the vehicle not world.

I tried a simple setup with 2 boxes, 1 being the car and 1 being the player. If the player is a child of the car, then setting it’s localPosition works correctly, if the player is NOT a child of the car I get the same behaviour as you described.

player is not child of car.

try this:

PC.Instance.transform.position = currentVehicle.transform.TransformPoint (currentVehicle.transform.position + getOutSide);

he just leaves at weirdest points, like the farther the car is from 0,0,0 the farther behind the car he exits.

PC.Instance.transform.position = currentVehicle.transform.position - 2 * currentVehicle.transform.right;

Is probably a much more readable way of doing it.

3 Likes

This,

Was just about to post this very same until I saw Baste posted it.

yes thank you … : - )

Thank you for your help. : -)