0
\$\begingroup\$

I've got animations and simple movements down as well as attacking, although I'm having my difficulties with jumping and I'm not sure how to make it work.

using UnityEngine;

public class Player : MonoBehaviour
{   
    private Rigidbody rb;
    public float speed = 100f;
    public float jumpforce = 50f;
    public float movement = 0f;
    public Vector3 jump;
    public LayerMask ground;
    public bool onground;
    public float groundcheckradius;
    public Transform groundcheck;

    void OncollisionStay() { onground = true; }

    void Start()
    {
        rb = GetComponent<Rigidbody>();
        jump = new Vector3(0f, 50f, 0f);
    }

    void FixedUpdate()
    {
        onground = Physics.OverlapSphere(groundcheck.position, groundcheckradius, ground);

        if(Input.GetKeyDown(KeyCode.Space)&& onground) {
            rb.AddForce(jumpforce * jump, ForceMode.Impulse);
            onground = false;
        }   

        if (Input.GetKey(KeyCode.W))
        {    
            rb.velocity = new Vector3(0, 0, speed * Time.deltaTime);
        }
        {
            if (Input.GetKey(KeyCode.S))
            {    
                rb.velocity = new Vector3(0, 0, -speed * Time.deltaTime);
            }
            if (Input.GetKey(KeyCode.D))
            {    
                rb.velocity = new Vector3(speed * Time.deltaTime, 0, 0);
            }
            if (Input.GetKey(KeyCode.A))
            {   
                rb.velocity = new Vector3(-speed * Time.deltaTime, 0, 0);
            }   
        }
    }
}
\$\endgroup\$
2
  • 2
    \$\begingroup\$ It looks like you're using Unity (don't forget to tag your question!) - there are probably hundreds of tutorials on how to implement a jump in Unity - have none of them been able to solve your problem? Where specifically have you run into trouble implementing one of this immense wealth of available examples? \$\endgroup\$
    – DMGregory
    Apr 22 '20 at 20:14
  • \$\begingroup\$ Two obvious errors though: don't update your onground in OnCollisionStay if you're already doing it in FixedUpdate. Don't multiply a speed by deltaTime when assigning it to a velocity. (A speed times a time duration is a distance, not a speed/velocity anymore) \$\endgroup\$
    – DMGregory
    Apr 22 '20 at 20:19

Your Answer

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

Browse other questions tagged or ask your own question.