# How To Translate GameObject To Where It's Facing ?

Hi, I’m trying to translate my player every time the button is pressed.

This is script I used :

``````player.transform.Translate (new Vector2 (5f, 0f));
``````

But my player always be translated to right…

How to make my player be translated to where he’s facing ?

That is the proper code to move 5 to the right, based on ‘facing’.

But I want when my player face left, he will be translated to x = -5f (left).

I see. Well, if it was rotated it would be. Perhaps you are turning by negative scale or flipX ?

for negative scale:

``````player.transform.Translate (new Vector2 (Mathf.Sign(player.transform.localScale.x) * 5f, 0f));
``````

It’s basically what you had before, but multiplies your movement value by 1 or -1, depending on the value of the localScale’s ‘x’.

If it’s flipX you’re using and can’t work it out, I can try to help you with an example.

Thanks very much it’s worked. Now I have a new problem. My Player can be Translated through wall. How I can fix it so if there is a wall it will just Translated exactly at the edge of the wall?

Well, in 2D you can either try to raycast before you move to determine if the move is valid, or you can use physics and move with rigidbody. Some people like to try making their own collision detection, but I think using physics is a lot easier.
Physics will/would require you to change your code so you move with the system; instead of modifying the transform position directly (as in translate), you set the velocity of the rigidbody or addforce to it.

Hmm, i’m sorry i can’t understand what u r trying to explain. I’m still new to raycast and physics. Can you give me some example ?

Well, as I suggested you could always try using physics instead.

Please feel free to look this topic up online, because I’m sure there are many posts on raycasting in 2d.
Then, if you had a question about something you’ve tried, perhaps me or someone else can try to assist you.

The docs that explain, describe/show it: Unity - Scripting API: Physics2D.Raycast
You can also cast “shapes” : box, circle,capsule (and the 3d equivalents).

Physics (rigidbody2d): https://docs.unity3d.com/Manual/class-Rigidbody2D.html
and: Unity - Scripting API: Rigidbody2D

Hopefully that in combination with whatever you can search for online can help you get started.

Thanks, I will try to learn it and will ask if I need something…