Hello, I am making a 2D sidescrolling fighter game but I am having some problems with creating a C# script for moving the player character left and right using the arrow keys. I’ve tried looking at a lot of tutorials and help sites but most of what I find is outdated and so when I’ve tried following them, I’ve just hit dead ends. I came here because I really don’t know where else I can ask this - thanks in advance to anyone who can help me out here!
There are multiple ways in which you can move the player, This is how I do it in a lot of my 2D games:
if (Input.GetKey(KeyCode.A))
{
transform.position = transform.position += transform.right * -moveSpeed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.D))
{
transform.position = transform.position += transform.right * moveSpeed * Time.deltaTime;
}
That is just simply checking if the player is pressing either the A or D key and then it will move the player in the right direction times by it’s moveSpeed which I assign in the inspector. If you want to use the arrow keys to move the player instead then you just got to change KeyCode.A
to KeyCode.LeftArrow
and KeyCode.D
to KeyCode.RightArrow
.
Also make sure to run all this in the Update method so it’s checking for input every frame.
Hope this helps and good luck with your game
//movement variable
bool facingRight;
public float maxSpeed;
float move = Input.GetAxis("Horizontal");//Edit>Project setting>Input check about Horizontal if you dont know about t//
myAnim.SetFloat("speed", Mathf.Abs(move)); //playing the animation//
myRB.velocity = new Vector2(move * maxSpeed, myRB.velocity.y);
if (move > 0 && !facingRight)
{
flip();
}
else if (move < 0 && facingRight)
{
flip();
}
}
void flip()
{
facingRight = !facingRight;
Vector2 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}