I have my controls but my character movement won’t move whatever i do this is my update but i cant hold down my movement buttons to move.
void Update () {
//Your controls.
if (Input.GetKeyDown(KeyCode.A))
{
transform.Translate(Vector2.left * speed);
}
if (Input.GetKeyDown(KeyCode.D))
{
transform.Translate(Vector2.right * speed);
}
if (Input.GetKeyDown(KeyCode.Space))
{
body.AddForce(Vector2.up * jumpSpeed, ForceMode2D.Impulse);
}
}
Instead of using if statement for every key, you should use Input.GetAxix() for moving player left or right. I wrote you some comment so you can see how it works.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
[SerializeField]
private float maxSpeed = 10f; // Maximum speed player can have
//Facing of player. It can be Left or Right.
bool facingRight = true;
// Rigidbody 2D component you need to add to Player GameObject
private Rigidbody2D rigidbody2D;
void Start ()
{
rigidbody2D = GetComponent<Rigidbody2D>();
}
// It is better to do this things like movement in Fixed Update
void FixedUpdate ()
{
///<summary> You dont need if statement to check GetKeyDown(). GetAxix("Horizontal") will check if Player pressed keys (Left or Right Arrow, A or D).
///You can also change this in Input Settings if you want
///</summary>
///
float move = Input.GetAxis("Horizontal");
rigidbody2D.velocity = new Vector2(move * maxSpeed, rigidbody2D.velocity.y);
if(move > 0 && !facingRight)
{
Flip();
}
else if (move<0 && facingRight)
{
Flip();
}
}
/// <summary>
/// This function Flip player Sprite
/// </summary>
void Flip()
{
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}