- Home /
Controlling if object is moving right or left
Hello, currently I'm trying to create a 2D platformer for some practice. I got character moving jumping shooting but I want to check if the character is moving right or left, so I can shoot my projectile accordingly. I'm working with C#, thanks in advance!
public float movementSpeed;
transform.Translate(Input.GetAxis("Horizontal") *movementSpeed * Time.deltaTime,0,0,Space.World);
By the way , I also want my character to interact with objects correctly( when I run towards an obstacle, my character is trying to go into the obstacle, I want him to stop when it collides with an obstacle) in my research people recommend to make velocity zero when you want your character to stop but I think "transform.translate" method has no relation with physics that's why it doesn't work for me, so can you give any other methods about moving my character?
I hope I can get an answer soon because I really would like to develop myself in this community.
Please bump questions by editing them or posting a comment (and not an "Answer") on UA Answer means Solution and not reply.
Presumably you have some code that actually moves this character based on the players input - can you post that code perhaps? Hard to help you without knowing what you are doing.
I want to check if the character is moving right or left : first store your Input in a variable, then check if that has a value of approximately +- 0.02 (you should include a deadzone for sensitive analogue inputs). Then you can still use that variable in your move command. eg :
float deadZone = 0.02f;
// in method
float inputHorz = Input.GetAxis("Horizontal");
if ( inputHorz < -deadZone ) {
// object going left
}
else if ( inputHorz > deadZone ) {
// object going right
}
transform.Translate( inputHorz *movementSpeed * Time.deltaTime,0,0,Space.World);
want my character to interact with objects correctly are you using a character controller? If not, you'll need to use physics or some very clever obstacle detection. One relationship I noticed (and clear me up if I'm wrong) is that using rigidbody.velocity is pretty much the same as transform.position. eg :
transform.position += transform.forward * speed * Time.deltaTime;
rigidbody.velocity = transform.forward * speed;
For me this has worked very well, have very quickly added rigidbodies and modified scripts using this relationship.
Your answer
![](https://koobas.hobune.stream/wayback/20220613085913im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How do you make an object go left and right? 1 Answer
Moving a object around with mouse, rotating it with arrow keys and placing it. 1 Answer
Rigidbody2d Moving up and Down but not left and right 1 Answer
charactercontroller.isgrounded not working!! 1 Answer
Moving character on a moving ground 1 Answer