Hello,
I started using Unity about 4 days ago. So sorry from the beginning that the question will probably be pretty stupid.
I have written my current script together through various tutorials.
Now I tried to make my player jump. This works, but only so that he is teleported in the air and then lands again. What do I have to do differently so he jumps into the air? I hope the question is not too stupid. Maybe someone can help me. Thanks here is my hole Script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement2 : MonoBehaviour
{
public Transform cam;
public CharacterController controller;
public float speed = 6f;
public float turnSmoothTime = 0.1f;
float turnSmoothVelocity;
public float gravity;
private float currentGravity = 0f;
public float jumpSpeed;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;
Vector3 finalMovement;
if (direction.magnitude >= 0.1f)
{
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
transform.rotation = Quaternion.Euler(0f, angle, 0f);
Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
finalMovement = moveDir.normalized * speed + ApplyGravity();
if (Input.GetButtonDown("Jump") && controller.isGrounded)
{
finalMovement.y = jumpSpeed;
finalMovement.y -= gravity * Time.deltaTime;
controller.Move(finalMovement * Time.deltaTime);
}
else
{
controller.Move(finalMovement * Time.deltaTime);
}
}
else
{
finalMovement = ApplyGravity();
if (Input.GetButtonDown("Jump") && controller.isGrounded)
{
finalMovement.y = jumpSpeed;
finalMovement.y -= gravity * Time.deltaTime;
controller.Move(finalMovement * Time.deltaTime);
}
else
{
controller.Move(finalMovement * Time.deltaTime);
}
}
}
Vector3 ApplyGravity()
{
Vector3 gravityMovement = new Vector3(0, -currentGravity, 0);
currentGravity += gravity * Time.deltaTime;
if (controller.isGrounded)
{
if (currentGravity > 1f)
{
currentGravity = 1f;
}
}
return gravityMovement;
}
}