Slowly decrease movement speed after releasing left shift - c#

So, I am still developing a game in Unity, where my only problem now is that I can't figure out how to slowly decrease the speed of my character after releasing left shift. Slowly increasing speed while holding shift is the only one I had worked out because I used the incrementing technique, but the speed slowly decreasing after releasing left shift is not. Can someone help me? Here's the code, I apologize, I am literally a beginner at this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public CharacterController controller;
//Codes for setting walk and sprint speed (You should put speed in "Default Speed". "Walk Speed" is public so I can see if my speed is increasing)
public float defaultSpeed = 8f;
public float walkSpeed = 8f;
public float sprintIncrease = 15f;
public float sprintLimit = 16f;
//Gravity force
public float gravity = -60f;
//Probably jump height?
public float jumpHeight = 2f;
//For checking if you're on the ground
public Transform groundCheck;
public float groundDistance = 0.5f;
public LayerMask groundMask;
//Code to check if you are on the ground
Vector3 velocity;
bool isGrounded;
// Update is called once per frame
void Update()
{
//For checking again if you're on the ground
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
//Code to slowly increase sprint FORWARD while holding left shift
if (Input.GetKey(KeyCode.LeftShift) && Input.GetAxis("Vertical") > 0)
{
walkSpeed += sprintIncrease * Time.deltaTime;
}
//Code to prevent sprinting while holding S and when combined with A or D
else if (Input.GetKey(KeyCode.LeftShift) && Input.GetAxis("Vertical") < 0)
{
walkSpeed = defaultSpeed;
}
//Code for allowing to slowly increase sprint LEFT sideways
else if (Input.GetKey(KeyCode.LeftShift) && Input.GetAxis("Horizontal") < 0)
{
walkSpeed += sprintIncrease * Time.deltaTime;
}
//Code for allowing to slowly increase sprint RIGHT sideways
else if (Input.GetKey(KeyCode.LeftShift) && Input.GetAxis("Horizontal") > 0)
{
walkSpeed += sprintIncrease * Time.deltaTime;
}
//To stop Sprint Speed while holding shift from exceeding Sprint Limit
if (walkSpeed > sprintLimit)
{
walkSpeed = sprintLimit;
}
//Executes when shift is released, to slowly go back to default speed(This is my problem)
if (Input.GetKeyUp(KeyCode.LeftShift))
{
walkSpeed = defaultSpeed;
}
//To check if you're grounded so velocity doesn't increase
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
//The basic horizontal and vertical axises
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
//The basic code for movement
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * walkSpeed * Time.deltaTime);
//The code for jumping
if (Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
I thank everyone in advance.

if (!Input.GetKey(KeyCode.LeftShift))
{
walkSpeed -= sprintIncrease * Time.deltaTime;
}
the above code will do what you asked for. Just a heads up, the way you're implementing stuff is beginner-friendly but not performance friendly.

Ok, I have figured this out myself. I rearrange my ifs and else statement to look more organized. I added the else statement where if you don't hold shift while walking, it continuously subtracts the walk speed with the sprint increase, but to stop it from being lower than the default speed, I added an if statement where if the walk speed becomes lower than the default speed, it becomes equal to the default speed. Note that I rearranged my statements to trigger an else statement.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public CharacterController controller;
//Codes for setting walk and sprint speed (You should put speed in "Default Speed". "Walk Speed" is public so I can see if my speed is changing or not)
public float defaultSpeed = 8f;
public float walkSpeed = 8f;
public float sprintIncrease = 15f;
public float sprintLimit = 16f;
//Gravity force
public float gravity = -60f;
//Probably jump height?
public float jumpHeight = 2f;
//For checking if you're on the ground
public Transform groundCheck;
public float groundDistance = 0.5f;
public LayerMask groundMask;
//Code to check if you are on the ground
Vector3 velocity;
bool isGrounded;
// Update is called once per frame
void Update()
{
//For checking again if you're on the ground
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
//Code to prevent sprinting while holding S and when combined with A or D(New Code)
if (Input.GetKey(KeyCode.LeftShift) && Input.GetAxis("Vertical") < 0)
{
walkSpeed -= sprintIncrease * Time.deltaTime;
}
//Code to slowly increase sprint FORWARD while holding left shift
else if (Input.GetKey(KeyCode.LeftShift) && Input.GetAxis("Vertical") > 0)
{
walkSpeed += sprintIncrease * Time.deltaTime;
}
//Code for allowing to slowly increase sprint LEFT sideways
else if (Input.GetKey(KeyCode.LeftShift) && Input.GetAxis("Horizontal") < 0)
{
walkSpeed += sprintIncrease * Time.deltaTime;
}
//Code for allowing to slowly increase sprint RIGHT sideways
else if (Input.GetKey(KeyCode.LeftShift) && Input.GetAxis("Horizontal") > 0)
{
walkSpeed += sprintIncrease * Time.deltaTime;
}
//To make sure that your speed decrease smoothly if not holding left shift(New code)
else
{
walkSpeed -= sprintIncrease * Time.deltaTime;
}
//To stop Sprint Speed while holding shift from exceeding Sprint Limit
if (walkSpeed > sprintLimit)
{
walkSpeed = sprintLimit;
}
//To stop Walk Speed from getting lower than Default Speed(New Code)
if (walkSpeed < defaultSpeed)
{
walkSpeed = defaultSpeed;
}
//To check if you're grounded so velocity doesn't increase
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
//The basic horizontal and vertical axises
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
//The basic code for movement
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * walkSpeed * Time.deltaTime);
//The code for jumping
if (Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}

Related

How to make jump independent on FPS?

I almost made a 3D horror game in which the Player can walk, run and jump, but I noticed that jump depends on FPS. The more FPS, the higher the jump. I want to Player jump doesn't depend on FPS. How to solve the problem?
Script Player (just Update):
void Update{
// Jump when Player is on the Ground
Ground = Physics.CheckSphere(GroundCheck.position, groundDistance, Groundmask);
if (Ground && velocity.y < 0) { velocity.y = -0.5f; }
posX = Input.GetAxis("Horizontal"); posZ = Input.GetAxis("Vertical");
Vector3 Move = transform.right * posX + transform.forward * posZ;
controller.Move(Move * speed * Time.deltaTime);
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity);
if ((Input.GetMouseButton(0) || Input.GetKey(KeyCode.Return)) && Ground)
{
{ velocity.y = Mathf.Sqrt(3 - gravity); }
}
}

im getting a problem with infinite jumps into the air [duplicate]

This question already has an answer here:
hello, i was recently working on my new game, and im getting a problem with *Infinite jumping*
(1 answer)
Closed 10 months ago.
im acttualy losing my mind at this point, been having this issue for the past 3 days, cant figure out any solutions, this might sound lazy and all but if you can troubleshoot my code
that'd great because i dont wanna lose more sanity, Thanks in Advance
code:
public class playermovement : MonoBehaviour
{
public CharacterController controller;
public float speed = 12f;
Vector3 velocity;
public float gravity = -9.81f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
bool isGrounded;
public float jumpHeight = 3f;
void Start()
{
isGrounded = true;
}
// Update is called once per frame
void FixedUpdate()
{
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");
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
if (Input.GetKeyDown("space"))
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
if (Input.GetKeyDown("space"))
{
isGrounded = false;
}
if ()
{
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
You are forcing isGrounded to false when you push space, try removing that, and you aren't actually checking isGrounded to perform the jump. Here's a bandaid
if (Input.GetKeyDown("space"))
{
if (isGrounded){
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
} else return;
}

Unity PlayerMovement Delayed Stopping

I was making a PlayerMovement script today for a small 3D game I wanted to start. After some experimentation with the script, I realized that when you release a button to move, it won't instantly stop and instead the character body starts to slide.
For the most part, I had used Brackey's tutorial on PlayerMovement scripts but added a .Normalize() to make sure diagonals did not have more speed.
Does anyone know how to fix this? This is my PlayerMovement script.
public class PlayerMovement : MonoBehaviour
{
public float speed = 12f;
public float gravity = -0.05f;
public float jumpHeight = 4f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
Vector3 velocity;
Vector3 move;
private bool isGrounded;
public CharacterController controller;
void FixedUpdate()
{
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");
Vector3 move = transform.right * x + transform.forward * z;
move.Normalize();
controller.Move(Time.deltaTime * speed * move);
if (Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
Thank you for any help or guidance!
Instead of Input.GetAxis, try using Input.GetAxisRaw, which returns the non-smoothed value for a target axis, resulting in a more FPS-like controller, more responsive and fast, without smoothing.

Issue with flipping sprite in Unity 2D

I'm new to unity and I was following a youtube guide on scripting a 2D platformer, I have gotten to the point now where I am trying to add a flip to the sprite when I turn to go in the opposite direction.
I have added a code and now this is constantly flipping left to right. If I understand correctly its probably because I am constantly applying > 0.1f when moving resulting in the function to continuously run but honestly I am lost so any help would be appreciated.
using UnityEngine;
using System.Collections;
[RequireComponent (typeof (Controller2D))]
public class Player : MonoBehaviour {
public float jumpHeight = 4;
public float timeToJumpApex = .4f;
float accelerationTimeAirbourne = .2f;
float acceleratinTimeGrounded =.1f;
public float moveSpeed = 6;
float jumpVelocity;
float gravity;
Vector3 velocity;
float velocityXSmoothing;
Controller2D controller;
void Start(){
controller = GetComponent<Controller2D>();
gravity = -(2 * jumpHeight) / Mathf.Pow (timeToJumpApex, 2);
jumpVelocity = Mathf.Abs(gravity) * timeToJumpApex;
print ("gravity: " + gravity + " Jump Velocity: " + jumpVelocity);
}
void Update(){
if (controller.collisions.above || controller.collisions.above) {
velocity.y = 0;
}
Vector2 input = new Vector2 (Input.GetAxisRaw ("Horizontal"),
Input.GetAxisRaw ("Vertical"));
if (Input.GetKeyDown (KeyCode.Space) && controller.collisions.below) {
velocity.y = jumpVelocity;
}
float targetVelocityX = input.x * moveSpeed;
velocity.x = Mathf.SmoothDamp(velocity.x, targetVelocityX, ref
velocityXSmoothing, (controller.collisions.below)?
acceleratinTimeGrounded:accelerationTimeAirbourne);
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
void FixedUpdate(){
if ((Input.GetAxis("Horizontal") > 0.1f && this.transform.localScale.x != 1)
|| (Input.GetAxis("Horizontal") < -0.1f && this.transform.localScale.x !=
-1))
{
flip();
}
}
void flip()
{
this.transform.localScale = new Vector3(this.transform.localScale.x *
-1,
this.transform.localScale.y, this.transform.localScale.z);
}
}
Your error is here
void FixedUpdate(){
if ((Input.GetAxis("Horizontal") > 0.1f && this.transform.localScale.x != 1)|| (Input.GetAxis("Horizontal") < -0.1f && this.transform.localScale.x !=
-1)){
flip();
}
}
After you flip, the condition still evaluates to true. You will need a boolean hasflipped to check if you have already flipped, and if you have don't flip again :)
Fixed update is causing this check to happen once per frame, so you're going to get a bunch of flickering as your sprite flips every frame, unless you specify only to flip once

Controlling the Speed of the Car

I have been trying to control the speed of the car in Unity4. I am providing the code details below. Do I need to upgrade the code? As because when the brake(space bar) is pressed the Speed is set to Zero but when the brake is released the Speed is increasing again.
using UnityEngine;
using System.Collections;
public class CarMovementScript : MonoBehaviour
{
public Vector3 com;
public Rigidbody rb;
public WheelCollider FrontLeft;
public WheelCollider FrontRight;
public WheelCollider RearRight;
public WheelCollider RearLeft;
public float maxspeed = 40;
public float carspeed = 0;
public float speed = 0.0f;
float braking = 75.0f;
float turning = 30.0f;
void Start()
{
rb = GetComponent<Rigidbody>();
rb.centerOfMass = new Vector3(rb.centerOfMass.x, -0.9f, rb.centerOfMass.z);
}
void Update()
{
if (speed <= maxspeed)
{
Debug.Log(speed);
//this code makes car go forward
RearRight.motorTorque = Input.GetAxis("Vertical") * speed;
RearLeft.motorTorque = Input.GetAxis("Vertical") * speed;
speed += 0.05f;
}
//this code works for braking of the car
RearRight.brakeTorque = 0;
RearLeft.brakeTorque = 0;
//this code is for turning
FrontRight.steerAngle = Input.GetAxis("Horizontal") * turning;
FrontLeft.steerAngle = Input.GetAxis("Horizontal") * turning;
//Breaking
if (Input.GetKey(KeyCode.Space))
{
RearRight.brakeTorque = braking;
RearLeft.brakeTorque = braking;
speed = 0.0f;
}
}
}
Based on your statement:
when the brake is released the Speed is increasing again.
My guess is that your this piece of code needs attention:
if (speed <= maxspeed)
{
Debug.Log(speed);
//this code makes car go forward
RearRight.motorTorque = Input.GetAxis("Vertical") * speed;
RearLeft.motorTorque = Input.GetAxis("Vertical") * speed;
speed += 0.05f;
}
When you apply break, the speed goes to zero, but since speed <= maxspeed so it returns true and car starts moving due to speed += 0.05f. So you should probably block this condition unless there is an input for vertical axis. Like: (untested, to give you an idea)
float vertical = Input.GetAxis("Vertical");
if ((speed != 0 && speed <= maxspeed) ||
(speed == 0.0 && vertical > 0.0))
{
Debug.Log(speed);
//this code makes car go forward
RearRight.motorTorque = vertical * speed;
RearLeft.motorTorque = vertical * speed;
speed += 0.05f;
}
This way, if condition will execute iff either brake applied and from vertical axis there is a gain in speed or there is already a gain in speed and speed is limited with maxspeed
Hope it helps!
don't set speed to 0 instead decrement it by 0.05f.
remove this
if (speed <= maxspeed)
{
Debug.Log(speed);
//this code makes car go forward
RearRight.motorTorque = Input.GetAxis("Vertical") * speed;
RearLeft.motorTorque = Input.GetAxis("Vertical") * speed;
speed += 0.05f;
}
and change
if (Input.GetKey(KeyCode.Space))
{
RearRight.brakeTorque = braking;
RearLeft.brakeTorque = braking;
speed = 0.0f;
}
to
if (Input.GetKey(KeyCode.Space))
{
RearRight.brakeTorque = braking;
RearLeft.brakeTorque = braking;
speed -= 0.05f;
}
else if (speed <= maxspeed)
{
Debug.Log(speed);
//this code makes car go forward
RearRight.motorTorque = Input.GetAxis("Vertical") * speed;
RearLeft.motorTorque = Input.GetAxis("Vertical") * speed;
speed += 0.05f;
}
This is the code for turning. But the turning gets multiplied automatically at the beginning. What Code changes must be done to adjust the turning?
FrontRight.steerAngle = Input.GetAxis("Horizontal") * turning;
FrontLeft.steerAngle = Input.GetAxis("Horizontal") * turning;
paste this in update function/method.
void Update()
{
//20.0f is maxSpeed
GetComponent<Rigidbody>().velocity = Vector3.ClampMagnitude(GetComponent<Rigidbody>().velocity, 20.0f);
}

Categories