How do I add a simple jump function to this script?
I'm trying to figure out how to add a simple jump function to this script, and am totally lost. I'm trying to learn, but this is so foreign to me that I can't figure it out. Perhaps if I had done the code myself, I may have had a better idea about all of it, but here it is. I did not write this code. I was simply given it and it works perfectly except my little ball cannot jump. Also, when I press "A" the ball moves right and "D" moves it left. Script below:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Rigidbody))]
public class SphereMovement : MonoBehaviour
{
[SerializeField] float speed = 1;
Rigidbody rigidbodyInstance;
float movementInput = 0;
void Start()
{
rigidbodyInstance = GetComponent<Rigidbody>();
}
void Update()
{
GetMovementInput();
}
void FixedUpdate()
{
Move();
}
void GetMovementInput()
{
movementInput = Input.GetAxis("Horizontal");
}
void Move()
{
Vector3 direction = new Vector3(movementInput, 0.0f, 0.0f);
rigidbodyInstance.AddForce(direction * speed);
}
}
As I've stated, I did not write this. Any help would be much appreciated, so thank you in advance
Answer by Ejpj123 · Apr 19, 2016 at 02:00 AM
2D:
using UnityEngine;
using System.Collections;
public class Jump : MonoBehaviour {
public bool grounded = true;
public float jumpPower = 1;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(!grounded && rigidbody2D.velocity.y == 0) {
grounded = true;
}
if (Input.GetButtonDown("Jump") && grounded == true) {
rigidbody2D.AddForce(transform.up*jumpPower);
grounded = false;
}
}
3D:
void FixedUpdate () {
if (Input.GetButton("Jump") && isFalling == false)
{
playerRigidbody.velocity = new Vector3(0f, jump, 0f);
isFalling = true;
}
}
//to make sure you can't jump while in mid-air I use the following: void OnCollisionStay () { isFalling = false; }
Answer by Buliaras · Apr 19, 2016 at 02:39 AM
I really appreciate your help, but for the life of me, I can't get it to work. I wanted to be able to add a line or however many into the existing code, but that's impossible at this stage for me. I tried making news scripts to get your code to work and for some reason, it doesn't. Keeps giving me parsing errors and such. Either way, once again, I appreciate the help
Your answer
Follow this Question
Related Questions
Does anyone have a good script that can be used to make a horse/vehicle rideable? 0 Answers
Continuously monitor childrens properties 1 Answer
How would i modify my current script to remove these UI buttons without killing my pause menu? 1 Answer
Why does NetworkServer.ReplacePlayerForConnection not recognize the instantiated object parameter? 0 Answers
[C#] StreamWriter throwing Sharing Violation on path 0 Answers