Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question Jump code?

Discussion in 'Physics' started by SuperDan11, Jul 16, 2020.

  1. SuperDan11

    SuperDan11

    Joined:
    Mar 17, 2020
    Posts:
    3
    I want to add a jump to this code here:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Move : MonoBehaviour {
    6.  
    7.     public CharacterController controller;
    8.  
    9.     public float speed = 6f;
    10.  
    11.     public float turnSmoothTime = 0.1f;
    12.     float turnSmoothVelocity;
    13.    
    14.     // Update is called once per frame
    15.     void Update () {
    16.         float horizontal = Input.GetAxisRaw("Horizontal");
    17.         float vertical = Input.GetAxisRaw("Vertical");
    18.         Vector3 direction = new Vector3(horizontal - horizontal*2, 0f, vertical - vertical*2).normalized;
    19.  
    20.         if(direction.magnitude >=0.1f){
    21.             float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg;
    22.             float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
    23.             transform.rotation = Quaternion.Euler(0f, angle, 0f);
    24.  
    25.             controller.Move(direction*speed*Time.deltaTime);
    26.  
    27.         }
    28.     }
    29. }
    I use Character Controller and I have no idea where to start with this, this would also help me with trying gravity.
     
  2. noyogiisMYusername

    noyogiisMYusername

    Joined:
    May 18, 2020
    Posts:
    21
    There are many different examples and tutorials on youtube. I would suggest watching a few different ones to see alternative methods for different situations.
    AddForce using ForceMode "Impulse" in the up direction.

    There are different methods of detecting whether or not your player should be able to jump, before the player can jump we might ask, "is your player Grounded" or "isGrounded"? In 2D I am using OnTriggerEnter2D (and its exit version) to detect when a collider attached to the player has been entered or exited. If a detection occurs, a function is called to "check for ground", that function "CheckForGround()" then uses a Physics2D.Boxcast to to check for colliders that on on the ground layer. There are several videos that compare different methods of ground detection, this is how I came to my setup.