How to jump smoothly in Unity3D - unity3d

I add a CharacterController to Player.But when I test the jump function,I find that the Player will move upwards immediately.
if (Player.isGrounded)
{
if (jump)
{
Move.y = JumpSpeed;
jump = false;
Player.Move (Move * Time.deltaTime);
}
}
Move += Physics.gravity * Time.deltaTime * 4f;
Player.Move (Move * Time.fixedDeltaTime);`

You are calling Player.Move() twice in one frame. This might be an issue.
You are adding gravity to Move vector, which means it will always go upward when you call this code.
naming a variable like Move is not a good convention. It creates confusion while reading because there is already a method of same name. change it to moveDirection.
Here is sample code:
public class ExampleClass : MonoBehaviour {
public float speed = 6.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
CharacterController controller;
void Start()
{
controller = GetComponent<CharacterController>();
}
void Update() {
if (controller.isGrounded) {
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetButton("Jump"))
moveDirection.y = jumpSpeed;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
}
hope this helps.

Related

How to fix Character Controller jumping up steep slopes?

I'm using a 3d character controller for my player but I can't figure out how to stop it from being able to jump up steep slopes. I've looked around and could only find one video that fixes the issue but after the character slides down the slope it stays locked in the slide movement function and I'm not really sure why. I've edited out the code that doesn't matter for clarity, pls lmk if u know how to fix this!
Heres the code:
public class PlayerMovement : MonoBehaviour
{
public CharacterController controller;
public float speed = 12f;
public float gravity = -9.81f;
public float jumpHeight = 3f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
//SLOPES
private float groundRayDistance = 1;
private RaycastHit slopeHit;
public float slopeSlideSpeed;
Vector3 velocity;
bool isGrounded;
// Update is called once per frame
void Update()
{
HandleMovement();
HandleAnimations();
if(OnSteepSlope())
{
SteepSlopeMovement();
}
}
private void HandleMovement()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
if (Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
velocity = AdjustVelocityToSlope(velocity);
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
private Vector3 AdjustVelocityToSlope(Vector3 velocity)
{
var ray = new Ray(transform.position, Vector3.down);
if(Physics.Raycast(ray, out RaycastHit hitInfo, 0.2f))
{
var slopeRotation = Quaternion.FromToRotation(Vector3.up, hitInfo.normal);
var adjustedVelocity = slopeRotation * velocity;
if(adjustedVelocity.y < 0)
{
return adjustedVelocity;
}
}
return velocity;
}
private bool OnSteepSlope()
{
if (!isGrounded) return false;
if (Physics.Raycast(transform.position, Vector3.down, out slopeHit, (controller.height / 2) + groundRayDistance))
{
float slopeAngle = Vector3.Angle(slopeHit.normal, Vector3.up);
if (slopeAngle > controller.slopeLimit) return true;
}
return false;
}
private void SteepSlopeMovement()
{
Vector3 slopeDirection = Vector3.up - slopeHit.normal * Vector3.Dot(Vector3.up, slopeHit.normal);
float slideSpeed = speed + slopeSlideSpeed + Time.deltaTime;
velocity = slopeDirection * -slideSpeed;
velocity.y = velocity.y - slopeHit.point.y;
}
OnSteepSlope() wasnt returning false so I put the return false statement in an else loop, I also changed how I was moving the character in SteepSlopeMovement by using controller.Move() instead of directly changing the velocity. It works great now
I see you've got dot product check inside of SteepSlopeMovement might be useful to draw some rays with gizmos of the player's down and the normal of the surface. Then you can adjust the threshold value for when you can jump.

Jump in using Rigidbody or Character controller

i have been recreating my jump code, i have it all done but i can't add force or anything else.
Here's my code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class pBeh : MonoBehaviour
{
CharacterController characterController;
public float MovementSpeed = 1;
public float Gravity = 9.8f;
private float velocity = 0;
private Camera mainCam;
public Rigidbody rb;
public float jumpSpeed = 5.2f;
private Vector3 movingDirection = Vector3.zero;
public CharacterController controller;
public float speed;
float turnSmoothVelocity;
public float turnSmoothTime;
public bool canJump = false;
private void Start()
{
characterController = GetComponent<CharacterController>();
mainCam = Camera.main;
}
void Update()
{
// player movement - forward, backward, left, right
float horizontal = Input.GetAxis("Horizontal") * 10;
float vertical = Input.GetAxis("Vertical") * 10;
Vector3 camRightFlat = new Vector3(mainCam.transform.right.x, 0,
mainCam.transform.right.z).normalized;
Vector3 camForwardFlat = new Vector3(mainCam.transform.forward.x, 0,
mainCam.transform.forward.z).normalized;
characterController.Move((camRightFlat * horizontal + camForwardFlat * vertical)
* Time.deltaTime);
// Gravity
if (characterController.isGrounded)
{
velocity = 0;
}
else
{
velocity -= Gravity * Time.deltaTime;
characterController.Move(new Vector3(0, velocity, 0));
}
if (canJump == true && Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("Jumped");/*
transform.Translate(Vector3.up * 5.0f * Time.deltaTime);
rb.AddRelativeForce(Vector3.up * 8.0f);
rb.AddForce(Vector3.up * 8.0f)
i have tried a lot more, but it just doesn't work.
The sphere (Player) does nothing or shakes.
*/
}
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "enemy")
{
SceneManager.LoadScene("SampleScene");
}
}
void FixedUpdate()
{
if ((controller.collisionFlags & CollisionFlags.Below) != 0)
{
//Debug.Log("ground");
canJump = true;
}
else
{
canJump = false;
}
}
As i said it works just fine i just can't find reason why i cannot jump.
I have all character controller right and rigidbody too. If you could help i would be happy.
Btw i am beginner so i copied movement to be same as camera. Thanks!
From what I know, rigidbody and character controller do not work together (on the same object) so you have to choose one or the other, if you are using rigidbody then a ground check or similiar stuff would not be necessary since rigidbody is using unity physicis system so a lot of the stuff would be already done for you to simulate physics but you should still read thru the document

Movement and Rotation

So I'm currently learning Unity 3D but I stuck on a problem.
So Iv'e done this code that the player moves with WASD keys. The movement works fine.
I tried to aply some rotation, that way the player can turn back or move to different positions.
But the problem is, I put the rotarion and the player turns but when he does he swap W for S, so basically if I turn back, when I press W to go forward he go backward and when I press S instead of going Backward he goes Forward.
I don't to make a lot of changes in my code because I think it's very "basic" right now and easy to understand. So if someone can explain what I'm doing wrong I would appreciate.
using System.Collections.Generic;
using UnityEngine;
//[RequireComponent(typeof(Rigidbody))]
public class PlayerMov : MonoBehaviour
{
//Player mov speed
float MovSpeed = 10f;
//Player jump, jumpforce, check if is on the ground and rb(rigidbody component)
public Vector3 jump;
public float jumpForce = 2.0f;
public bool isGrounded;
Rigidbody rb;
public float TurnSpeed = 100f;
void Start()
{
rb = GetComponent<Rigidbody>();
jump = new Vector3(0.0f, 2.0f, 0.0f);
}
void OnCollisionStay()
{
isGrounded = true;
}
void Update()
{
if (Input.GetKey(KeyCode.W))
{
transform.position -= Vector3.forward * MovSpeed * Time.deltaTime;
//transform.Translate(Vector3.forward * MovSpeed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.A))
{
transform.position -= Vector3.left * MovSpeed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.S))
{
transform.position -= Vector3.back * MovSpeed * Time.deltaTime;
//transform.Translate(-Vector3.forward * MovSpeed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.D))
{
transform.position -= Vector3.right * MovSpeed * Time.deltaTime;
transform.Rotate(Vector3.up * TurnSpeed * Time.deltaTime);
}
if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
{
rb.AddForce(jump * jumpForce, ForceMode.Impulse);
isGrounded = false;
}
if (Input.GetKey(KeyCode.LeftArrow))
{
transform.Rotate(Vector3.up * TurnSpeed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.RightArrow))
{
transform.Rotate(Vector3.up * TurnSpeed * Time.deltaTime);
}
Why not use the Translate method? Please see its documentation. You can define a which space you want the transform to move in (global or local)
https://docs.unity3d.com/ScriptReference/Transform.Translate.html
As a side note: why check for each separate key? Using Input.GetAxis("Horizontal") and Input.GetAxis("Horizontal") vertical would be simpler.

how do i make something which moves with Velocity jump in Unity?

I was hoping I could get some help! I've been trying to make a platformer using velocity to move but I can't find a good way to do jumping using the system. Every frame the velocity's y just resets itself and I don't know how to create a jump. I have tried using ForceMode.VelocityChange and I have tried to write out equations. The player falls extremely slowly even with gravity turned on.
playerBody.AddForce(Vector3.up * jumpForce, ForceMode.VelocityChange);
I have the same issues when I try to set the y velocity to change with gravity
float MoveDirectionY = jumpForce * Physics.gravity.y;
enter image description here
Nothing seems to be working here. When i play the game gravity still pulls the object down slowly but if i turn off gravity it doesnt pull the object down at all.
The game does log the statement letting me know that it does know the space button was pressed.alt text
I want to also provide my code here:
using System.Collections;
using System.Collections.Generic;
using System.Transactions;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[SerializeField] private Rigidbody playerBody;
[SerializeField] private Vector3 inputVector;
[SerializeField] public float speed = 0.01f;
[SerializeField] public bool jump;
[SerializeField] private float turnSpeed = 45;
[SerializeField] public float jumpForce = 35000f;
[SerializeField] private bool isOnGround = true;
[SerializeField] float enemyPushForce = 100;
public int ingredient;
public GameManager gameManager;
public camSwitch cs;
public float horizontalInput;
public float verticalInput;
float playerFacingAngleY;
private GameObject FocalPoint;
// Start is called before the first frame update
void Start()
{
//Just making sure we have the rigid body of the game object the script is attached to so we can move it later
playerBody = gameObject.GetComponent<Rigidbody>();
FocalPoint = GameObject.Find("Focal Point");
}
// Update is called once per frame
//This is where the player script should be realizing we are using inputs
void Update()
{
horizontalInput = Input.GetAxis("Horizontal");
verticalInput = Input.GetAxis("Vertical");
playerFacingAngleY += horizontalInput * turnSpeed;
Vector3 playerFacingDirection = new Vector3(0, playerFacingAngleY, 0);
playerBody.rotation = Quaternion.Euler(playerFacingDirection);
float moveDirectionX = (FocalPoint.transform.position.x - gameObject.transform.position.x) *speed * verticalInput * Time.deltaTime;
float MoveDirectionY = jumpForce * Physics.gravity.y;
float moveDirectionZ = (FocalPoint.transform.position.z - gameObject.transform.position.z) * speed * verticalInput * Time.deltaTime;
Vector3 moveDirection = new Vector3(moveDirectionX, MoveDirectionY, moveDirectionZ);
playerBody.velocity = moveDirection;
if (Input.GetKeyDown(KeyCode.Space) && isOnGround == true)
{
playerBody.AddForce(Vector3.up * jumpForce, ForceMode.VelocityChange);
isOnGround = false;
print("player has jumped");
}
}
private void OnCollisionEnter(Collision collision)
{
isOnGround = true;
if (collision.gameObject.tag == "Enemy")
{
Debug.Log("Player ran into an enemy");
if (cs.inSky == true)
{
speed = 0;
}
else
{
speed = 10;
}
}
else if (collision.gameObject.tag == "Ingredient")
{
Debug.Log("Player collided with an ingredient");
collision.gameObject.SetActive(false);
ingredient++;
}
else if (collision.gameObject.tag == "Ground") {
isOnGround = true;
print("player has hit the ground");
}
}
}
Do not play with rigidbody in Update method. Use FixedUpdate() instead.
In addition, do not change velocity using rb.velocity = ... but use rigibody.AddForce() method. Try something like this:
void FixedUpdate() //using rigidbody? => ONLY FIXEDUPDATE
{
horizontalInput = Input.GetAxis("Horizontal");
verticalInput = Input.GetAxis("Vertical");
playerFacingAngleY += horizontalInput * turnSpeed;
Vector3 playerFacingDirection = new Vector3(0, playerFacingAngleY, 0);
playerBody.rotation = Quaternion.Euler(playerFacingDirection);
float moveDirectionX = (FocalPoint.transform.position.x - gameObject.transform.position.x) *speed * verticalInput * Time.deltaTime;
float moveDirectionZ = (FocalPoint.transform.position.z - gameObject.transform.position.z) * speed * verticalInput * Time.deltaTime;
Vector3 moveDirection = new Vector3(moveDirectionX, 0.0f, moveDirectionZ); //0.0f - just turn on gravity in rigidbody component or you can change it if you want some additional Vertical force
playerBody.AddForce(moveDirection, ForceMode.VelocityChange); //force mode change to whatever you want
if (Input.GetKeyDown(KeyCode.Space) && isOnGround == true)
{
playerBody.AddForce(Vector3.up * jumpForce, ForceMode.VelocityChange);
isOnGround = false;
print("player has jumped");
}
}

How do i make my character move in the direction of the camera (Unity)

In Unity I want to make it so that when I hold w, instead of going in a single direction I want it to go forward in the direction of my camera how do I do that? (Sorry I'm new to unity)
EDIT: The movement script is:
using UnityEngine;
using System.Collections;
public class Player_Movement : MonoBehaviour {
public float speed = 6.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
void Update() {
CharacterController controller = GetComponent<CharacterController>();
if (controller.isGrounded) {
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetButton("Jump"))
moveDirection.y = jumpSpeed;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
}
As indicated by #lockstock, the direction the camera is facing can be retrieved from its transform. Here is an example below if you want to know how to use it.
public class Player_Movement : MonoBehaviour
{
public float speed = 6.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
// Drag & Drop the camera in this field, in the inspector
public Transform cameraTransform ;
private Vector3 moveDirection = Vector3.zero;
void Update() {
CharacterController controller = GetComponent<CharacterController>();
if (controller.isGrounded) {
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = cameraTransform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetButton("Jump"))
moveDirection.y = jumpSpeed;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
}
This scripts works without any error. I've tested it in Unity myself.
The forward direction of the camera is obtained by using Camera.main.transform.forward
turn your player so the blue axis is facing the same direction as the blue axis on the camera. then drag and drop the camera onto the player. now when you move the player, the camera will follow, and stay behind the player