Reputation: 57
I'm struggling for about 5-6 hours to find a way to controll my character in c#. I just want to make it as simple as posible. (press W - it goes up, release the W key, it stops) And absolutly nothing I could find on google helps. Even it's a reaaally long code, which i don't understand because I just started learning, even it's not what I want. For example, that's like the most viewed tutorial, but it doesn't work for my 'game'. It might work for a character that's flaoting/flying, but not for a basic one.
private Rigidbody2D rb2d;
public float speed = 10f;
void Start()
{
rb2d = GetComponent<Rigidbody2D> ();
}
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector2 movement = new Vector2(moveHorizontal, moveVertical);
rb2d.AddForce(movement * speed);
}
}
Upvotes: 0
Views: 490
Reputation: 807
You can either rewrite
rb2d.AddForce(movement * speed);
to
rb2d.AddForce(movement * speed, ForceMode2D.Force);
or replace it entirely with
rb2d.velocity = movement * speed;
Upvotes: 1