How can I make the player jump in unity 3d - c#

Hello can you help to make the player jump
also how to make the player crouch?
this is my move script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public CharacterController controller;
public Transform cam;
public float speed = 6f;
public float turnsmoothT = 0.1f;
float turnsmoothV;
void Update()
{
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;
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 turnsmoothV, turnsmoothT);
transform.rotation = Quaternion.Euler(0f, angle, 0f);
Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
controller.Move(moveDir.normalized * speed * Time.deltaTime);
}
}
}
..................................................................................................................................................................................................................................................................

See if this helps:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public CharacterController controller;
public Transform cam;
public float speed = 6f;
public float turnsmoothT = 0.1f;
private float turnsmoothV;
private bool jumping = false;
private float moveDirectionY = 0;
private float gravity = 9.81f;
private void Update()
{
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;
Vector3 moveDir = Vector3.zero;
if (jumping && controller.isGrounded)
{
jumping = false;
}
if (Input.GetKeyDown(KeyCode.Space) && !jumping && controller.isGrounded)
{
moveDirectionY = 3f;
jumping = true;
}
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 turnsmoothV, turnsmoothT);
transform.rotation = Quaternion.Euler(0f, angle, 0f);
moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
}
moveDirectionY -= gravity * Time.deltaTime;
moveDir.y = moveDirectionY;
controller.Move(moveDir * speed * Time.deltaTime);
}
}

Related

How do I make it so that the Rotation of the player object does not affect the Input.GetAxisRaw("Horizonatal")?

In my code, when I change the rotation of the player object, the Input.GetAxisRaw("Horizontal") also follows that rotation and messes the whole player controller up. How do I make it so that the Input.GetAxis is permanent and stays in place? The whole rotation is being done in the if statement of if Input.GetKey("a").
using UnityEngine;
public class JUSTMOVE : MonoBehaviour
{
public float speed = 7f;
Vector3 moveDirection;
public Rigidbody rb;
float horizontalMovement;
float verticalMovement;
public float movementMultiplier = 10f;
bool grounded;
public float groundDrag = 6;
public LayerMask whatIsGround;
public float airMultiplier = 3f;
public float playerHeight = 2f;
public float jumpForce = 5f;
void FixedUpdate()
{
grounded = Physics.Raycast(transform.position, Vector3.down, playerHeight * 0.5f + 0.2f, whatIsGround);
horizontalMovement = Input.GetAxisRaw("Horizontal");
if (grounded)
rb.drag = groundDrag;
else
rb.drag = 0;
moveDirection = transform.forward * verticalMovement + transform.right * horizontalMovement;
if(grounded)
{
rb.AddForce(moveDirection.normalized * speed * movementMultiplier, ForceMode.Force);
} else if(!grounded)
{
rb.AddForce(moveDirection.normalized * speed * movementMultiplier * airMultiplier, ForceMode.Force);
}
if(Input.GetKey("a"))
{
transform.localRotation = Quaternion.Euler(0,270,0);
}
Vector3 flatVel = new Vector3(rb.velocity.x, 0f,rb.velocity.z);
if(flatVel.magnitude > speed)
{
Vector3 limitedVel = flatVel.normalized * speed;
rb.velocity = new Vector3(limitedVel.x, rb.velocity.y, limitedVel.z);
}
if(Input.GetKey("w") && grounded)
{
rb.velocity = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
rb.AddForce(transform.up * jumpForce, ForceMode.Impulse);
}
}
}
If I get it right, you want a top/down controller instead of a first/third person controller ?
If so, you need to move align the camera rotation instead of you character rotation.
Replace this :
moveDirection = transform.forward * verticalMovement + transform.right * horizontalMovement;
By this :
moveDirection = Camera.main.transform.forward * verticalMovement + Camera.main.transform.right * horizontalMovement;

Turning the character towards the camera

This script is on the character. When the character starts to move, his face turns towards the camera. This code needs to be redone so that the character always looks towards the camera, even if he is standing still.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TPM : MonoBehaviour
{
CharacterController controller;
public Transform cam;
public float speed = 6f;
public float turnSmoothTime = 0.1f;
float turnSmoothVelocity;
private void Start()
{
controller = GetComponent<CharacterController>();
}
private void Update()
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;
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;
controller.Move(moveDir.normalized * speed * Time.deltaTime);
}
}
}
use transform.LookAt(Camera.main.transform.position) in your Update.
Here is a suitable solution I found
public Transform cam;
public float speed = 5f;
private void FixedUpdate()
{
transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(0f, cam.rotation.eulerAngles.y, 0f), speed * Time.deltaTime);
}

"error CS0103: The name 'targetAngle' does not exist in the current context" in unity 3d while was trying to make a 3rd person camera

So, I've been trying to make a third-person camera for the game I'm making in Unity 3D. I'm new to game dev(but I understand some things in this because I tried to make games earlier and tried to learn Java a bit) so I used Brackeys' guide on this , but every time I'm trying to compile the code, it just says that variable targetAngle where's stored math Atan function cannot be used in another variable moveDir for some reason. this is the error "Assets\Scripts\PlayerMovement.cs(67,48): error CS0103: The name 'targetAngle' does not exist in the current context", and here's the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public CharacterController controller;
public Transform cam;
public float speed = 12f;
public float gravity = -9.81f;
public float jumpHeight = 3f;
public float _doubleJumpMultiplier = 1.5f;
public float turnSmoothTime = 0.1f;
private float turnSmoothVelocity;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
Vector3 velocity;
bool isGrounded;
private bool _canDoubleJump = false;
bool _playerMove = false;
private void Start() {
_playerMove = GetComponent<PlayerMovement>();
}
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if(isGrounded && velocity.y < 0) {
_canDoubleJump = true;
velocity.y = -2f;
}
else {
if(Input.GetButtonDown("Jump") && _canDoubleJump) {
velocity.y = 3f * _doubleJumpMultiplier;
_canDoubleJump = false;
}
}
float vertical = Input.GetAxisRaw("Vertical");
float horizontal = Input.GetAxisRaw("Horizontal");
Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;
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;
controller.Move(moveDir * speed * Time.deltaTime);
if(Input.GetButtonDown("Vertical") && isGrounded && _canDoubleJump) {
_playerMove = true;
}
else
if(!Input.GetButtonDown("Vertical") && isGrounded && _canDoubleJump) {
_playerMove = false;
}
if(Input.GetButtonDown("Horizontal") && isGrounded && _canDoubleJump) {
_playerMove = true;
}
else
if(!Input.GetButtonDown("Horizontal") && isGrounded && _canDoubleJump) {
_playerMove = false;
}
if(Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2 * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
You define targetAngle in this if statement:
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);
}
And attempt to use it outside of it in the following line. But here targetAngle is out of scope.
Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;

My spherical world player controller is jittering randomly

I've got a problem with my spherical world player controller. It randomly jitter all the time.
Planet uses Mesh Collider, and it's rigidbody is set too: "is kinematic" and continous collisions.
Player's rigidbody is set to: "interpolate" and continous collisions.
Here is player controller:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[SerializeField] Transform cam, body, groundCheck;
[Space][SerializeField] float sensivity = 100f;
[SerializeField] float mass = 1f;
[SerializeField] float moveSpeed = 1f;
[SerializeField] float jumpHeight = 1f;
[SerializeField] LayerMask ground;
[SerializeField] float rotationChangeSpeed = 1f;
float xRotation = 0f;
Rigidbody rb;
Vector3 moveAmount, smoothMove;
Vector3 localUp;
bool grounded = false;
Quaternion targetRot;
float jumpTime = 0f;
Transform currentPlanet;
//On start
void Awake() {
Cursor.lockState = CursorLockMode.Locked;
rb = GetComponent<Rigidbody>();
}
//Physics simulation
void FixedUpdate() {
Grav();
FindingRotation();
Movement();
grounded = IsGrounded();
}
//Applying movement
void Movement() {
Vector3 localMove = transform.TransformDirection(moveAmount) * Time.fixedDeltaTime;
rb.MovePosition(rb.position + localMove);
}
//Simulating gravity
void Grav() {
List<CelestialBody> bodies = CelestialBody.bodies;
if(bodies.Count == 0) return;
Vector3 acceleration = Vector3.zero;
float maxForce = -1f;
for(int i = 0; i < bodies.Count; ++i) {
CelestialBody body = bodies[i];
float distance = Vector3.Distance(body.GetComponent<Transform>().position, transform.position);
float force = GravityManager.bigG * mass * body.mass / (distance * distance);
Vector3 direction = Vector3.Normalize(body.GetComponent<Transform>().position - transform.position);
if(force > maxForce) {
maxForce = force;
currentPlanet = body.transform;
}
acceleration += direction * force;
}
if(!grounded) GetComponent<Rigidbody>().AddForce(acceleration);
}
//Rotating according to body with highest gravity
void FindingRotation() {
localUp = Vector3.Normalize(transform.position - currentPlanet.position);
targetRot = Quaternion.FromToRotation(transform.up, localUp) * rb.rotation;
rb.rotation = Quaternion.Slerp(rb.rotation, targetRot, Time.fixedDeltaTime * rotationChangeSpeed);
}
//Per frame
void Update() {
CameraControls();
InputManager();
jumpTime -= Time.deltaTime;
}
//Camera controls
void CameraControls() {
float mouseX = Input.GetAxis("Mouse X") * sensivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * sensivity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
cam.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
body.Rotate(Vector3.up * mouseX);
}
//Moving and jumping
void InputManager() {
Vector3 inputRaw = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")).normalized;
Vector3 input = inputRaw * moveSpeed;
moveAmount = Vector3.SmoothDamp(moveAmount, input, ref smoothMove, .15f);
if(grounded) {
if(Input.GetKeyDown(KeyCode.Space)) {
rb.AddForce(transform.up * jumpHeight, ForceMode.VelocityChange);;
jumpTime = .2f;
grounded = false;
}
else {
if(jumpTime <= 0f) rb.AddForce (-transform.up, ForceMode.VelocityChange);
}
}
}
//TODO: Improve with ray
bool IsGrounded() {
return (Physics.OverlapSphere(groundCheck.position, .1f, ground).Length > 0);
}
}
And here is Celestial Body:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CelestialBody : MonoBehaviour
{
public static List<CelestialBody> bodies = new List<CelestialBody>();
public float mass;
//public Vector3 speed;
void OnEnable() {
bodies.Add(this);
}
void OnDisable() {
bodies.Remove(this);
}
}
I will be really grateful for any advice.

How do I add the feature to make player jump higher by holding down space?

I'm quite new to coding and making games. I created this script with the help of some YT tutorials and I was wondering how to make my character jump higher while holding doing the space bar. I tried different things but non worked properly. Here's my character code. Thanks!
using System;
using UnityEngine;
using UnityEngine.UI;
public class TPMovementScript : MonoBehaviour
{
public CharacterController controller;
public Transform cam;
public float speed = 6f;
public float jump = 10f;
public float gravity = -9.81f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
public float jumpHeight = 3f;
Vector3 velocity;
bool isGrounded;
public float turnSmoothTime = 0.1f;
float turnSmoothVelocity;
// Update is called once per frame
void Update()
{
//Checks if player is grounded & resets velocity
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
//Makes Player move Using WASD or upDownLeftRight
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized.normalized;
if (isGrounded && Input.GetKey(KeyCode.Space))
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
//Makes Character face direction and makes forward to camera position
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;
controller.Move(moveDir.normalized * speed * Time.deltaTime);
}
}
}
This looks like answer to your problem https://www.youtube.com/watch?v=j111eKN8sJw and code is similar.

Categories