- Home /
Not able to find the problem in my movement code using velocity
I was working on a movement script for my character, everything was going fine, my character was moving until I tried to limit his top speed using a comparaison. I first tought the comparison was never getting a "true" state, but I tried to replace the "if" condition by true and it still doesn't work.
As rexeplenation, the goal is to make the character move by increasing his velocity but still setting him a limit, all of that controlled by the "a" and "d" keys on the keyboard.
Here's my actual code:
using System.Collections;
using UnityEngine;
public class GaucheDroite : MonoBehaviour {
private Animator animator;
private SpriteRenderer spriteParameters;
enum Direction {right, left, idle};
[SerializeField]
public float velocityMax;
// Use this for initialization
void Start () {
spriteParameters = gameObject.GetComponent<SpriteRenderer>();
animator = gameObject.GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
if (Input.GetKey("d") == true)
{
animator.SetBool("Walking", true);
spriteParameters.flipX = false;
WalkingAction(Direction.right);
}
else if (Input.GetKey("a") == true)
{
animator.SetBool("Walking", true);
spriteParameters.flipX = true;
WalkingAction(Direction.left);
}
else
{
animator.SetBool("Walking", false);
WalkingAction(Direction.idle);
}
}
void WalkingAction (Direction directionDeLaMarche)
{
Rigidbody2D rigidbody2D = gameObject.GetComponent<Rigidbody2D>();
float velocityY = gameObject.GetComponent<Rigidbody2D>().velocity.y;
float velocityX = gameObject.GetComponent<Rigidbody2D>().velocity.x;
switch (directionDeLaMarche)
{
case Direction.right:
if (velocityX < velocityMax)
{
rigidbody2D.velocity.Set(velocityX+1,velocityY);
}
break;
case Direction.left:
if (velocityX > -velocityMax)
{
rigidbody2D.velocity.Set(velocityX-1,velocityY);
}
break;
case Direction.idle:
break;
}
}
}
As extra information:
VelocityMax is set to 10
Animation work fine
The keys are detected as wished (which makes the character sprites flip his direction and trigger the walking animation)
"idle" does nothing except setting the animation of the character to the idle pose
I can share an actual version of my in-dev game if needed
Thanks for your help in advance!
Answer by Meuleuh · Jul 05, 2018 at 04:13 PM
I've finally found out! Instead of using rigidbody2D.velocity.Set(velocityX+1,velocityY);
, I'm now using rigidbody2D.velocity = new Vector2(velocityX + 1, velocityY);
which do works instead! Thanks for trying to help me, but it seems that I figured out by myself!
If you click on the link in my comment, the example says exactly that.