-1
\$\begingroup\$

Ok so I'm new to Unity and I am trying to make this simple ball game. Now in a situation I want the ball to jump in a diagonal manner (i.e W + D ). Script that I have makes the ball jump only up and not in like a upper right direction. Can some one please suggest some change in the following script:

using UnityEngine;
using System.Collections;

public class BasicMovement : MonoBehaviour {

    public float rotation_Speed = 100;
    public float jump_Height = 1;

    private bool Falling = false;


    void Update ()
    {
        // FOR ROTATION
        float Rotation = Input.GetAxis ("Horizontal") * rotation_Speed * Time.deltaTime; // USING FORMULA DISTANCE = SPEED * TIME
        GetComponent<Rigidbody> ().AddRelativeTorque (Vector3.back * Rotation);  // APPLYING TORQUE TO THE BALL


        if (Input.GetKeyDown (KeyCode.W) && Falling == false ) 
        {
                GetComponent<Rigidbody> ().velocity = new Vector3 (1, 10, 0) * jump_Height;
                Falling = true;
        }
    }

    void OnCollisionStay()
    {
        Falling = false;
    }
}
\$\endgroup\$
  • \$\begingroup\$ Oops The Vector3 is actually (0,10,0) . \$\endgroup\$ – Hemang Bhogayata Mar 28 '16 at 16:57
0
\$\begingroup\$

Couple of things you are doing in more expensive way actually. Well, you should just apply force on Rigidbody instead of setting velocity explicitly.

You can improve your script as,

using UnityEngine;
using System.Collections;

public class BasicMovement : MonoBehaviour {

    public float rotation_Speed = 100;
    public float jump_Height = 1;

    private bool Falling = false;

    Rigidbody _rb;
    float _jumpXRatio = 1;
    float _jumpYRatio = 10;

    void Start()
    {
        _rb = GetComponent<Rigidbody> (); // it will keep reference
    }

    void Update ()
    {
        // FOR ROTATION
        float Rotation = Input.GetAxis ("Horizontal") * rotation_Speed * Time.deltaTime; // USING FORMULA DISTANCE = SPEED * TIME
        _rb.AddRelativeTorque (Vector3.back * Rotation);  // APPLYING TORQUE TO THE BALL


        if (Input.GetKeyDown (KeyCode.W) && Falling == false ) 
        {
                // Now set ratios and axes according to your needs
                _rb.AddForce (new Vector3 (_jumpXRatio, _jumpYRatio, 0) * jump_Height);
                Falling = true;
        }
    }

    void OnCollisionStay()
    {
        Falling = false;
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.