Hi, so I’m making a 2d platformer to teach myself, I’m using super mario world for the snes as a base to keep things simple in invisioning my game.
Anyway like in mario I want to be able to press a button and the character will double his speed into a run. But using the code I found in a tutorial I am having trouble figuring out how.
Here is the part of my player script that pertains to moving on the x axis in C#, I tried to trim it down to just the parts that matter as best I could
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
private Rigidbody2D myRigidbody;
private Animator myAnimator;
private float movementSpeed = 1;
private bool attack;
private bool facingRight;
private bool jump;
[SerializeField]
private float jumpForce;
// Use this for initialization
void Start ()
{
facingRight = true;
myAnimator = GetComponent<Animator>();
myRigidbody = GetComponent<Rigidbody2D>();
}
private void Update()
{
//Handles the player's input
HandleInput();
}
// Update is called once per frame
void FixedUpdate ()
{
float horizontal = Input.GetAxis("Horizontal");
HandleMovement(horizontal);
Flip(horizontal);
ResetValues();
}
private void HandleMovement(float horizontal)
{
if (!this.myAnimator.GetCurrentAnimatorStateInfo(0).IsTag("Attack") && (isGrounded || airControl))
{
myRigidbody.velocity = new Vector2(horizontal * movementSpeed, myRigidbody.velocity.y); //X = -1, Y = 0;
}
private void HandleInput()
{
if (Input.GetKeyDown(KeyCode.Space))
{
jump = true;
}
if (Input.GetKeyDown(KeyCode.LeftShift))
{
attack = true;
}
if (Input.GetKeyDown(KeyCode.RightShift))
{
movementSpeed = 2;
}
movementSpeed = 1;
}
private void Flip(float horizontal)
{
if (horizontal > 0 && !facingRight || horizontal < 0 && facingRight)
{
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
private void ResetValues()
{
attack = false;
jump = false;
}
private bool IsGrounded()
{
if (myRigidbody.velocity.y <=0)
{
foreach(Transform point in groundPoints)
{
//Makes an array of all colliders that are overlapping the ground points
Collider2D[] colliders = Physics2D.OverlapCircleAll(point.position, groundRadius, whatIsGround);
//Runs through the colliders to check if we are overlapping something that isn't the player
for (int i = 0; i < colliders.Length; i++)
{
if (colliders[i].gameObject != gameObject) //If we are overlapping something else than our self
{
return true;
}
}
}
}
return false;
}
}
As you can see I have a float called movementSpeed, which decides how fast the character goes and is declared intially as 1. I have it set in the handleInputs section that if right shift is pressed movementSpeed becomes 2 until the button is released. Unfortunately this did not work, and the internet has giving little help on making this work. DOes any body have an idea of what I can change to get the right shift to incease movementSpeed while pressed?