- Home /
acceleration in a 2D game (easy question, probably)
I was watching a 2D character controller tutorial
http://unity3d.com/learn/tutorials/modules/beginner/2d/2d-controllers
but I got stuck somewhere.
The video uses a script in which the movement speed accelerates. So instead of just either WALKING or NOT WALKING, the script stands still, then goes through an acceleration process in which he will first walk slowly and then quicker until max speed. I'm trying to make a 2D street fighting game as first project, so this doesnt really work for me.
What do I need to edit in order to achieve this?
Here is the script:
. . . .
using UnityEngine; using System.Collections;
public class CharacterControllerScript : MonoBehaviour {
public float maxSpeed = 10f;
bool facingRight = true;
Animator anim;
// Use this for initialization
void Start ()
{
anim = GetComponent<Animator> ();
}
// Update is called once per frame
void FixedUpdate ()
{
float move = Input.GetAxis ("Horizontal");
anim.SetFloat ("Speed", Mathf.Abs (move));
rigidbody2D.velocity = new Vector2 (move * maxSpeed, rigidbody2D.velocity.y);
if (move > 0 &&!facingRight)
Flip ();
else if (move < 0 && facingRight)
Flip ();
}
void Flip ()
{
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
Answer by Razouille · Mar 05, 2014 at 06:24 PM
float move = Input.GetAxis ("Horizontal");
This line will return a value between -1 and 1, so if you only want to have 0 or maxSpeed you can just force 1 if value > 0 and <= 1, or -1 if value < 0 and >= -1 The velocity is set correctly after so you don't have to do something else.
Thanks for your reply!
I have no idea how to do what you've told me though.. Could you make a small code for me?
With the code i gave you earlier, add this :
if (move > 0.1f) {
move = 1f;
}
else if (move < -0.1f) {
move = -1f;
}
else {
move = 0;
}
So "move" will be only 0, -1 or 1