Issue with Jumping and Movement
Hi, I'm trying to make movement where the character can go freely left and right but can only jump so far upwards (and not infinitely, like GetAxisRaw would allow). I'm having an issue with line 25 wherein jumping is "bool" and not "float", and I'm not sure how to correct this issue to still allow only one jump press at a time and avoid infinite jumping. I'm pretty new to coding so sorry if this is something obvious.
using UnityEngine;
using System.Collections;
public class VelocityMove : MonoBehaviour {
// UPDATED: Now Vector2 variables
public Vector2 velocity = new Vector2(15f,15f); // Used to store velocity
private Vector2 direction; // Used to store input directions (-1, 0, or 1)
public Rigidbody2D rb2D; // This gameObject's Rigidbody2D component
// Use this for initialization
void Start ()
{
// Store reference to the Rigidbody 2D attached to this gameObject
rb2D = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update ()
{
// More responsive input in Update()
// Use Input Manager for input (-1 for left, 1 for right, 0 for no movement)
direction.x = Input.GetAxisRaw ("Horizontal");
direction.y = Input.GetKeyDown (KeyCode.W);
}
// Update used for physics
void FixedUpdate()
{
rb2D.velocity = Vector2.Scale(velocity, direction);
}
}
Answer by Statement · Oct 10, 2015 at 08:07 PM
So your compile error is because you are trying to assign a bool to a float. You can convert it to a float like this:
if (Input.GetKeyDown(KeyCode.W))
direction.y = 1f;
else
direction.y = 0f;
// ... Or ...
direction.y = Input.GetKeyDown(KeyCode.W) ? 1f : 0f;
But this will likely not give you any nice effect since your direction.y will get set to 0 the next frame after pressing W.
I'll present you a modified version of your script that hopefully should give you a sense of how this works. I no longer update in Update but moved all to FixedUpdate. No longer setting the velocity directly but rather applying impulses to the rigidbody. This way we can also let the physics engine apply gravity over time.
using UnityEngine;
public class VelocityMove : MonoBehaviour
{
public float speed = 1f;
public float jumpForce = 5f;
private Rigidbody2D rb2D;
void Start()
{
rb2D = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
Vector2 force = Vector2.zero;
force.x = Input.GetAxisRaw("Horizontal") * speed;
force.y = Input.GetKeyDown(KeyCode.W) ? jumpForce : 0;
// Add force instead of adjusting velocity manually.
rb2D.AddForce(force, ForceMode2D.Impulse);
}
}