movement works fine right but not left - c#

I have a movement script that when I move right it is fine but when I move right it stutters. I have tried it without the camera moving same problem. I just cant understand why . The code is the same for both directions.
This is the code it gets it variables from other scripts but they don't have any other code than variables.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InputManager : MonoBehaviour
{
Rigidbody2D rb;
float jumpForce;
float downForce;
float speed;
float maxSpeed;
float maxJumps;
float currentJumps;
float cutJumpHeight;
float jumpBufferTimer;
float jumpBuffer;
float jumpRememberTimer;
float jumpRemember;
float x;
float y;
bool isGrounded = false;
AudioSource jumpSound;
Jump jumpScript;
Movement movementScript;
GameObject[] groundCheckPoints;
void Start()
{
jumpScript = GetComponent<Jump>();
movementScript = GetComponent<Movement>();
rb = GetComponent<Rigidbody2D>();
groundCheckPoints = GameObject.FindGameObjectsWithTag("Check Point");
}
void Update()
{
MyInput();
IsGrounded();
FlipCharacter();
jumpForce = jumpScript.jumpForce;
speed = movementScript.speed;
maxJumps = jumpScript.maxJumps;
cutJumpHeight = jumpScript.cutJumpHeight;
jumpRemember = jumpScript.jumpRememberTime;
jumpBuffer = jumpScript.jumpBufferTime;
jumpSound = jumpScript.jumpSound;
}
void FlipCharacter()
{
if (x > 0)
{
transform.rotation = Quaternion.Euler(0, 0, 0);
}else if(x < 0)
{
transform.rotation = Quaternion.Euler(0, 180, 0);
}
}
void IsGrounded()
{
for (int i = 0; i < groundCheckPoints.Length; i++)
{
isGrounded = Physics2D.OverlapCircle(groundCheckPoints[i].transform.position, 0.1f, LayerMask.GetMask("Ground"));
if (isGrounded)
{
break;
}
}
Jump();
}
void FixedUpdate()
{
MovementPlatformer();
}
void MyInput()
{
x = Input.GetAxisRaw("Horizontal");
y = Input.GetAxisRaw("Vertical");
}
void Jump()
{
jumpBufferTimer -= Time.deltaTime;
jumpRememberTimer -= Time.deltaTime;
if (isGrounded)
{
currentJumps = maxJumps;
}
if (currentJumps > 0)
{
jumpBufferTimer = jumpBuffer;
}
if (Input.GetKeyDown(KeyCode.Space))
{
jumpRememberTimer = jumpRemember;
}
if (jumpBufferTimer > 0 && jumpRememberTimer > 0)
{
jumpBufferTimer = 0;
jumpRememberTimer = 0;
jumpSound.Play();
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
currentJumps--;
}
if (Input.GetKeyUp(KeyCode.Space) && rb.velocity.y > 0)
{
rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * cutJumpHeight);
}
}
void MovementPlatformer()
{
rb.velocity = new Vector2(speed * x, rb.velocity.y);
}
}

It was something to do with the flip character function when i moved it to fixed update it fixed it.

Related

3D fps Game with gun adding recoil

I wanted to add Guns with recoil to my 3d fps game. It worked but for some reason all the time when i look completely downwards i walk backwards or frontwards. This only happens when the gun is active.
The Gun Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GunScript : MonoBehaviour
{
[SerializeField] float Recoil = 500f;
[SerializeField] float TimeTillNextShoot;
[SerializeField] float Range = 100f;
[SerializeField] Transform GunTipposition;
[SerializeField] float recoilRadius = 100f;
public Camera PlayerCamera;
public Rigidbody rbPlayer;
private void Update()
{
Shoot();
}
public void Shoot()
{
if (Input.GetButtonDown("Fire1"))
{
RaycastHit hit;
if(Physics.Raycast(PlayerCamera.transform.position, PlayerCamera.transform.forward, out hit, Range))
{
Debug.Log(hit.transform.name);
Enemy Enemytarget = hit.transform.GetComponent<Enemy>();
if(Enemytarget != null)
{
Enemytarget.TakeDamage(true);
}
}
if (gameObject.CompareTag("ShotGun"))
{
Transform RecoilPosition = GunTipposition.transform;
rbPlayer.AddExplosionForce(Recoil, RecoilPosition.position, recoilRadius);
}
}
}
}
The player Movement:
// Some stupid rigidbody based movement by Dani
using System;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[Header("Assignables")]
[Tooltip("this is a reference to the MainCamera object, not the parent of it.")]
public Transform playerCam;
[Tooltip("reference to orientation object, needed for moving forward and not up or something.")]
public Transform orientation;
[Tooltip("LayerMask for ground layer, important because otherwise the collision detection wont know what ground is")]
public LayerMask whatIsGround;
private Rigidbody rb;
[Header("Rotation and look")]
private float xRotation;
[Tooltip("mouse/look sensitivity")]
public float sensitivity = 50f;
private float sensMultiplier = 1.5f;
[Header("Movement")]
[Tooltip("additive force amount. every physics update that forward is pressed, this force (multiplied by 1/tickrate) will be added to the player.")]
public float moveSpeed = 4500;
[Tooltip("maximum local velocity before input is cancelled")]
public float maxSpeed = 20;
[Tooltip("normal countermovement when not crouching.")]
public float counterMovement = 0.175f;
private float threshold = 0.01f;
[Tooltip("the maximum angle the ground can have relative to the players up direction.")]
public float maxSlopeAngle = 35f;
private Vector3 crouchScale = new Vector3(1, 0.5f, 1);
private Vector3 playerScale;
[Tooltip("forward force for when a crouch is started.")]
public float slideForce = 400;
[Tooltip("countermovement when sliding. this doesnt work the same way as normal countermovement.")]
public float slideCounterMovement = 0.2f;
private bool readyToJump = true;
private float jumpCooldown = 0.25f;
[Tooltip("this determines the jump force but is also applied when jumping off of walls, if you decrease it, you may end up being able to walljump and then get back onto the wall leading to infinite height.")]
public float jumpForce = 550f;
float x, y;
bool jumping;
private Vector3 normalVector = Vector3.up;
[Header("Wallrunning")]
private float actualWallRotation;
private float wallRotationVel;
private Vector3 wallNormalVector;
[Tooltip("when wallrunning, an upwards force is constantly applied to negate gravity by about half (at default), increasing this value will lead to more upwards force and decreasing will lead to less upwards force.")]
public float wallRunGravity = 1;
[Tooltip("when a wallrun is started, an upwards force is applied, this describes that force.")]
public float initialForce = 20f;
[Tooltip("float to choose how much force is applied outwards when ending a wallrun. this should always be greater than Jump Force")]
public float escapeForce = 600f;
private float wallRunRotation;
[Tooltip("how much you want to rotate the camera sideways while wallrunning")]
public float wallRunRotateAmount = 10f;
[Tooltip("a bool to check if the player is wallrunning because thats kinda necessary.")]
public bool isWallRunning;
[Tooltip("a bool to determine whether or not to actually allow wallrunning.")]
public bool useWallrunning = true;
[Header("Collisions")]
[Tooltip("a bool to check if the player is on the ground.")]
public bool grounded;
[Tooltip("a bool to check if the player is currently crouching.")]
public bool crouching;
private bool surfing;
private bool cancellingGrounded;
private bool cancellingSurf;
private bool cancellingWall;
private bool onWall;
private bool cancelling;
public static PlayerMovement Instance { get; private set; }
void Awake()
{
Instance = this;
rb = GetComponent<Rigidbody>();
//Create a physic material with no friction to allow for wallrunning and smooth movement not being dependant
//and smooth movement not being dependant on the in-built unity physics engine, apart from collisions.
PhysicMaterial mat = new PhysicMaterial("tempMat");
mat.bounceCombine = PhysicMaterialCombine.Average;
mat.bounciness = 0;
mat.frictionCombine = PhysicMaterialCombine.Minimum;
mat.staticFriction = 0;
mat.dynamicFriction = 0;
gameObject.GetComponent<Collider>().material = mat;
}
void Start()
{
playerScale = transform.localScale;
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
readyToJump = true;
wallNormalVector = Vector3.up;
}
private void FixedUpdate()
{
Movement();
}
private void Update()
{
MyInput();
Look();
}
private void LateUpdate()
{
//call the wallrunning Function
WallRunning();
WallRunRotate();
}
private void WallRunRotate()
{
FindWallRunRotation();
float num = 12f;
actualWallRotation = Mathf.SmoothDamp(actualWallRotation, wallRunRotation, ref wallRotationVel, num * Time.deltaTime);
playerCam.localRotation = Quaternion.Euler(playerCam.rotation.eulerAngles.x, playerCam.rotation.eulerAngles.y, actualWallRotation);
}
/// <summary>
/// Find user input. Should put this in its own class but im lazy
/// </summary>
private void MyInput()
{
x = Input.GetAxisRaw("Horizontal");
y = Input.GetAxisRaw("Vertical");
jumping = Input.GetButton("Jump");
crouching = Input.GetKey(KeyCode.LeftControl);
//Crouching
if (Input.GetKeyDown(KeyCode.LeftControl))
StartCrouch();
if (Input.GetKeyUp(KeyCode.LeftControl))
StopCrouch();
}
private void StartCrouch()
{
transform.localScale = crouchScale;
transform.position = new Vector3(transform.position.x, transform.position.y - 0.5f, transform.position.z);
if (rb.velocity.magnitude > 0.2f && grounded)
{
if (grounded)
{
rb.AddForce(orientation.transform.forward * slideForce);
}
}
}
private void StopCrouch()
{
transform.localScale = playerScale;
transform.position = new Vector3(transform.position.x, transform.position.y + 0.5f, transform.position.z);
}
private void Movement()
{
//Extra gravity
rb.AddForce(Vector3.down * Time.deltaTime * 10);
//Find actual velocity relative to where player is looking
Vector2 mag = FindVelRelativeToLook();
float xMag = mag.x, yMag = mag.y;
//Counteract sliding and sloppy movement
CounterMovement(x, y, mag);
//If holding jump && ready to jump, then jump
if (readyToJump && jumping) Jump();
//Set max speed
float maxSpeed = this.maxSpeed;
//If sliding down a ramp, add force down so player stays grounded and also builds speed
if (crouching && grounded && readyToJump)
{
rb.AddForce(Vector3.down * Time.deltaTime * 3000);
return;
}
//If speed is larger than maxspeed, cancel out the input so you don't go over max speed
if (x > 0 && xMag > maxSpeed) x = 0;
if (x < 0 && xMag < -maxSpeed) x = 0;
if (y > 0 && yMag > maxSpeed) y = 0;
if (y < 0 && yMag < -maxSpeed) y = 0;
//Some multipliers
float multiplier = 1f, multiplierV = 1f;
// Movement in air
if (!grounded)
{
multiplier = 0.5f;
multiplierV = 0.5f;
}
// Movement while sliding
if (grounded && crouching) multiplierV = 0f;
//Apply forces to move player
rb.AddForce(orientation.transform.forward * y * moveSpeed * Time.deltaTime * multiplier * multiplierV);
rb.AddForce(orientation.transform.right * x * moveSpeed * Time.deltaTime * multiplier);
}
private void Jump()
{
if ((grounded || isWallRunning || surfing) && readyToJump)
{
MonoBehaviour.print("jumping");
Vector3 velocity = rb.velocity;
readyToJump = false;
rb.AddForce(Vector2.up * jumpForce * 1.5f);
rb.AddForce(normalVector * jumpForce * 0.5f);
if (rb.velocity.y < 0.5f)
{
rb.velocity = new Vector3(velocity.x, 0f, velocity.z);
}
else if (rb.velocity.y > 0f)
{
rb.velocity = new Vector3(velocity.x, velocity.y / 2f, velocity.z);
}
if (isWallRunning)
{
rb.AddForce(wallNormalVector * jumpForce * 3f);
}
Invoke("ResetJump", jumpCooldown);
if (isWallRunning)
{
isWallRunning = false;
}
}
}
private void ResetJump()
{
readyToJump = true;
}
private float desiredX;
private void Look()
{
float mouseX = Input.GetAxis("Mouse X") * sensitivity * Time.fixedDeltaTime * sensMultiplier;
float mouseY = Input.GetAxis("Mouse Y") * sensitivity * Time.fixedDeltaTime * sensMultiplier;
//Find current look rotation
Vector3 rot = playerCam.transform.localRotation.eulerAngles;
desiredX = rot.y + mouseX;
//Rotate, and also make sure we dont over- or under-rotate.
xRotation -= mouseY;
float clamp = 89.5f;
xRotation = Mathf.Clamp(xRotation, -clamp, clamp);
//Perform the rotations
playerCam.transform.localRotation = Quaternion.Euler(xRotation, desiredX, 0);
orientation.transform.localRotation = Quaternion.Euler(0, desiredX, 0);
}
private void CounterMovement(float x, float y, Vector2 mag)
{
if (!grounded || jumping) return;
//Slow down sliding
if (crouching)
{
rb.AddForce(moveSpeed * Time.deltaTime * -rb.velocity.normalized * slideCounterMovement);
return;
}
//Counter movement
if (Math.Abs(mag.x) > threshold && Math.Abs(x) < 0.05f || (mag.x < -threshold && x > 0) || (mag.x > threshold && x < 0))
{
rb.AddForce(moveSpeed * orientation.transform.right * Time.deltaTime * -mag.x * counterMovement);
}
if (Math.Abs(mag.y) > threshold && Math.Abs(y) < 0.05f || (mag.y < -threshold && y > 0) || (mag.y > threshold && y < 0))
{
rb.AddForce(moveSpeed * orientation.transform.forward * Time.deltaTime * -mag.y * counterMovement);
}
//Limit diagonal running. This will also cause a full stop if sliding fast and un-crouching, so not optimal.
if (Mathf.Sqrt((Mathf.Pow(rb.velocity.x, 2) + Mathf.Pow(rb.velocity.z, 2))) > maxSpeed)
{
float fallspeed = rb.velocity.y;
Vector3 n = rb.velocity.normalized * maxSpeed;
rb.velocity = new Vector3(n.x, fallspeed, n.z);
}
}
/// <summary>
/// Find the velocity relative to where the player is looking
/// Useful for vectors calculations regarding movement and limiting movement
/// </summary>
/// <returns></returns>
public Vector2 FindVelRelativeToLook()
{
float lookAngle = orientation.transform.eulerAngles.y;
float moveAngle = Mathf.Atan2(rb.velocity.x, rb.velocity.z) * Mathf.Rad2Deg;
float u = Mathf.DeltaAngle(lookAngle, moveAngle);
float v = 90 - u;
float magnitue = rb.velocity.magnitude;
float yMag = magnitue * Mathf.Cos(u * Mathf.Deg2Rad);
float xMag = magnitue * Mathf.Cos(v * Mathf.Deg2Rad);
return new Vector2(xMag, yMag);
}
//a lot of math (dont touch)
private void FindWallRunRotation()
{
if (!isWallRunning)
{
wallRunRotation = 0f;
return;
}
_ = new Vector3(0f, playerCam.transform.rotation.y, 0f).normalized;
new Vector3(0f, 0f, 1f);
float num = 0f;
float current = playerCam.transform.rotation.eulerAngles.y;
if (Math.Abs(wallNormalVector.x - 1f) < 0.1f)
{
num = 90f;
}
else if (Math.Abs(wallNormalVector.x - -1f) < 0.1f)
{
num = 270f;
}
else if (Math.Abs(wallNormalVector.z - 1f) < 0.1f)
{
num = 0f;
}
else if (Math.Abs(wallNormalVector.z - -1f) < 0.1f)
{
num = 180f;
}
num = Vector3.SignedAngle(new Vector3(0f, 0f, 1f), wallNormalVector, Vector3.up);
float num2 = Mathf.DeltaAngle(current, num);
wallRunRotation = (0f - num2 / 90f) * wallRunRotateAmount;
if (!useWallrunning)
{
return;
}
if ((Mathf.Abs(wallRunRotation) < 4f && y > 0f && Math.Abs(x) < 0.1f) || (Mathf.Abs(wallRunRotation) > 22f && y < 0f && Math.Abs(x) < 0.1f))
{
if (!cancelling)
{
cancelling = true;
CancelInvoke("CancelWallrun");
Invoke("CancelWallrun", 0.2f);
}
}
else
{
cancelling = false;
CancelInvoke("CancelWallrun");
}
}
private bool IsFloor(Vector3 v)
{
return Vector3.Angle(Vector3.up, v) < maxSlopeAngle;
}
private bool IsSurf(Vector3 v)
{
float num = Vector3.Angle(Vector3.up, v);
if (num < 89f)
{
return num > maxSlopeAngle;
}
return false;
}
private bool IsWall(Vector3 v)
{
return Math.Abs(90f - Vector3.Angle(Vector3.up, v)) < 0.05f;
}
private bool IsRoof(Vector3 v)
{
return v.y == -1f;
}
/// <summary>
/// Handle ground detection
/// </summary>
private void OnCollisionStay(Collision other)
{
int layer = other.gameObject.layer;
if ((int)whatIsGround != ((int)whatIsGround | (1 << layer)))
{
return;
}
for (int i = 0; i < other.contactCount; i++)
{
Vector3 normal = other.contacts[i].normal;
if (IsFloor(normal))
{
if (isWallRunning)
{
isWallRunning = false;
}
grounded = true;
normalVector = normal;
cancellingGrounded = false;
CancelInvoke("StopGrounded");
}
if (IsWall(normal) && (layer == (int)whatIsGround || (int)whatIsGround == -1 || layer == LayerMask.NameToLayer("Ground") || layer == LayerMask.NameToLayer("ground"))) //seriously what is this
{
StartWallRun(normal);
onWall = true;
cancellingWall = false;
CancelInvoke("StopWall");
}
if (IsSurf(normal))
{
surfing = true;
cancellingSurf = false;
CancelInvoke("StopSurf");
}
IsRoof(normal);
}
float num = 3f;
if (!cancellingGrounded)
{
cancellingGrounded = true;
Invoke("StopGrounded", Time.deltaTime * num);
}
if (!cancellingWall)
{
cancellingWall = true;
Invoke("StopWall", Time.deltaTime * num);
}
if (!cancellingSurf)
{
cancellingSurf = true;
Invoke("StopSurf", Time.deltaTime * num);
}
}
private void StopGrounded()
{
grounded = false;
}
private void StopWall()
{
onWall = false;
isWallRunning = false;
}
private void StopSurf()
{
surfing = false;
}
//wallrunning functions
private void CancelWallrun()
{
//for when we want to stop wallrunning
MonoBehaviour.print("cancelled wallrun");
Invoke("GetReadyToWallrun", 0.1f);
rb.AddForce(wallNormalVector * escapeForce);
isWallRunning = false;
}
private void StartWallRun(Vector3 normal)
{
MonoBehaviour.print("wallrunning");
//cancels all y momentum and then applies an upwards force.
if (!grounded && useWallrunning)
{
wallNormalVector = normal;
if (!isWallRunning)
{
rb.velocity = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
rb.AddForce(Vector3.up * initialForce, ForceMode.Impulse);
}
isWallRunning = true;
}
}
private void WallRunning()
{
//checks if the wallrunning bool is set to true and if it is then applies
//a force to counter gravity enough to make it feel like wallrunning
if (isWallRunning)
{
rb.AddForce(-wallNormalVector * Time.deltaTime * moveSpeed);
rb.AddForce(Vector3.up * Time.deltaTime * rb.mass * 40f * wallRunGravity * -Physics.gravity.y);
}
}
}
I used a addForce funktion to add the recoil.Please help me.
This sentence is juist written because i need to add more details

Making a (unity) moment script that allows my character to have dynamic jump, coyote time, jump buffering, and dash

I am new to unity and am trying to take two scripts that I have written based on youtube tutorials and make a script that allows my character to have dynamic jump, coyote time, jump buffering, and dash. Everything is working except for the dash now. When I play, all of the features work, including the anti-gravity during the dash, but my character does not speed up; it remains at the same speed as when walking. I think the two IEnumerator may be conflicting, but I am unsure of how to resolve it. So far, everything I have tried has not worked. I appreciate the help! enter image description here
using System.Collections;
using UnityEngine;
public class PlayerMovementBendux : MonoBehaviour
{
private float horizontal;
public float speed = 8f;
public float jumpingPower = 16f;
private bool isFacingRight = true;
private bool isJumping;
private float coyoteTime = 0.2f;
private float coyoteTimeCounter;
private float jumpBufferTime = 0.2f;
private float jumpBufferCounter;
private bool canDash = true;
private bool isDashing;
public float dashingPower = 24f;
public float dashingTime = 0.2f;
public float dashingCooldown = 1f;
[SerializeField] private Rigidbody2D rb;
[SerializeField] private Transform groundCheck;
[SerializeField] private LayerMask groundLayer;
[SerializeField] private TrailRenderer tr;
private void Update()
{
if (isDashing)
{
return;
}
horizontal = Input.GetAxisRaw("Horizontal");
if (IsGrounded())
{
coyoteTimeCounter = coyoteTime;
}
else
{
coyoteTimeCounter -= Time.deltaTime;
}
if (Input.GetButtonDown("Jump"))
{
jumpBufferCounter = jumpBufferTime;
}
else
{
jumpBufferCounter -= Time.deltaTime;
}
if (coyoteTimeCounter > 0f && jumpBufferCounter > 0f && !isJumping)
{
rb.velocity = new Vector2(rb.velocity.x, jumpingPower);
jumpBufferCounter = 0f;
StartCoroutine(JumpCooldown());
}
if (Input.GetButtonUp("Jump") && rb.velocity.y > 0f)
{
rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * 0.5f);
coyoteTimeCounter = 0f;
}
if (Input.GetKeyDown(KeyCode.LeftShift) && canDash)
{
StartCoroutine(Dash());
}
Flip();
}
private void FixedUpdate()
{
rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);
}
private bool IsGrounded()
{
return Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);
}
private void Flip()
{
if (isFacingRight && horizontal < 0f || !isFacingRight && horizontal > 0f)
{
Vector3 localScale = transform.localScale;
isFacingRight = !isFacingRight;
localScale.x *= -1f;
transform.localScale = localScale;
}
}
private IEnumerator JumpCooldown()
{
isJumping = true;
yield return new WaitForSeconds(0.4f);
isJumping = false;
}
private IEnumerator Dash()
{
canDash = false;
isDashing = true;
float originalGravity = rb.gravityScale;
rb.gravityScale = 0f;
rb.velocity = new Vector2(transform.localScale.x * dashingPower, 0f);
tr.emitting = true;
yield return new WaitForSeconds(dashingTime);
tr.emitting = false;
rb.gravityScale = originalGravity;
isDashing = false;
yield return new WaitForSeconds(dashingCooldown);
canDash = true;
}
}

Why does my dash only function properly if you aren't moving?

Here is the complete player controller file.
using UnityEngine;
public class PlayerCont : MonoBehaviour
{
[Header("Movement Variables")]
public float moveSpeed;
private float speed;
public float maxSpeed;
public float acceleration;
public float dropSpeed;
public float slideSpeed;
public int direction = 1;
[Header("Jump Variables")]
public float jumpForce;
public int extraJumps;
private float jumpTimeCounter;
public float jumpTime;
private bool isJumping;
private int jumpNum;
[Header("Dash Variables")]
public float dashSpeed;
public float dashLength = .5f;
public float dashCooldown = 1f;
private float dashCounter;
public float dashCoolCounter;
private KeyCode _lastKeyCode;
private float doubleTapTime = 0.05f;
private bool doubleTap;
public bool isDashing;
public float dashTime;
public float maxDashTime;
[Header("GroundCheck Variables")]
public Transform groundCheck;
public float checkRadius;
public LayerMask whatIsGround;
[Header("Debug Variables")]
public Rigidbody2D rb;
public float moveInputX;
public float moveInputY;
public bool facingRight = true;
public bool isGrounded;
public bool downKey;
public float rbxVel;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
speed = moveSpeed;
jumpNum = extraJumps;
}
void FixedUpdate()
{
}
// Update is called once per frame
void Update()
{
moveInputX = Input.GetAxisRaw("Horizontal");
moveInputY = Input.GetAxisRaw("Vertical");
isGrounded = Physics2D.OverlapCircle(groundCheck.position, checkRadius, whatIsGround);
KeyChecks();
Jump();
GroundPound();
Move();
Dash();
}
void KeyChecks()
{
//restricts movement in Y to only be downward
if (moveInputY > 0)
{
moveInputY = 0;
}
//checks for player drop
if (!isGrounded && moveInputY < 0)
{
downKey = true;
}
else
{
downKey = false;
}
//changes direction relative to keypress
if (Input.GetKeyDown(KeyCode.A))
{
direction = -1;
}
if (Input.GetKeyDown(KeyCode.D))
{
direction = 1;
}
}
void Jump()
{
//sets jump number to user specified amount after touching ground
if (isGrounded)
{
extraJumps = jumpNum;
}
//jumps and decrements extrajumps by 1
if (Input.GetKeyDown(KeyCode.Space) && !downKey && extraJumps > 0)
{
isJumping = true;
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
extraJumps--;
}
//basic jump off of ground
else if (Input.GetKeyDown(KeyCode.Space) && extraJumps == 0 && isGrounded && !downKey)
{
isJumping = true;
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
}
//checks for longkeypress of spacebar and increases length of jump
if (Input.GetKey(KeyCode.Space) && extraJumps > 1 && isJumping) // allows a hold down increase to jump while grounded
{
if (jumpTimeCounter > 0)
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
jumpTimeCounter -= Time.deltaTime;
}
else
{
jumpTimeCounter = jumpTime;
isJumping = false;
}
}
}
void GroundPound()
{
//ground pound keypress check
if (!isGrounded && Input.GetKeyDown(KeyCode.S))
{
if (!doubleTap && doubleTapTime > Time.time && _lastKeyCode == KeyCode.S)
{
rb.velocity = new Vector2(rb.velocity.x, -1 * dropSpeed);
Debug.Log("dashing right");
}
else
{
doubleTapTime = Time.time + 0.5f;
}
_lastKeyCode = KeyCode.S;
}
}
void Move()
{
//changes movement relative to input
if (!isDashing)
{
if (isGrounded && Input.GetKey(KeyCode.S))
{
rb.velocity = new Vector2(rb.velocity.x * .999f, rb.velocity.y);
}
else if (moveInputX == 0 && isGrounded)
{
speed = moveSpeed;
rb.velocity = new Vector2(rb.velocity.x * .99f, rb.velocity.y);
}
else if (moveInputX == 0 && !isGrounded)
{
speed = moveSpeed;
}
else
{
rb.velocity = new Vector2(moveInputX * speed, moveInputY / 10 + rb.velocity.y);
}
}
//checks player velocity
rbxVel = rb.velocity.x;
//increases speed relative to input direction
if (moveInputX > 0 || moveInputX < 0)
{
speed += acceleration;
}
//caps speed
if (speed > maxSpeed)
{
speed = maxSpeed;
}
//caps min speed
if (speed < moveSpeed)
{
speed = moveSpeed;
}
}
void Dash()
{
if (Input.GetKeyDown(KeyCode.LeftShift))
{
isDashing = true;
if (isDashing && dashCoolCounter <= 0)
{
dashTime -= Time.deltaTime;
dashCoolCounter = dashCooldown;
rb.velocity = new Vector2(dashSpeed * direction, rb.velocity.y);
Debug.Log("Dash Started");
}
}
else
{
dashTime = maxDashTime;
isDashing = false;
Debug.Log("No Dash");
}
//resets dash cooldown
if (dashCoolCounter > 0)
{
dashCoolCounter -= Time.deltaTime;
}
}
void Flip()
{
facingRight = !facingRight;
Vector3 Scaler = transform.localScale;
Scaler.x *= -1;
transform.localScale = Scaler;
}
}
When using the keys for movement (A, S) the dash doesn't function. Oddly enough the code is executing (I see my debug statement in console) but nothing physically changes.
When rewriting the code for the dash from: rb.velocity = new Vector2(dashSpeed * direction, rb.velocity.y) to: rb.velocity = dashspeed the dash will work without issue. The only downside to that is that the Y component of the RigidBody is being manipulated as well.
This has been an issue for days now, and I am just rewriting the post.
Any and all help is welcomed.
You're setting isDashing = false too soon. It gets set to false as soon as you let go of Shift which allows Move to execute its code and change your rigidbody's velocity back to normal move.
Didn't test this, but give it a shot and see if it works the way you want it to.
void Dash()
{
if (Input.GetKeyDown(KeyCode.LeftShift))
{
if (!isDashing && dashCoolCounter <= 0)
{
isDashing = true;
dashTime = 0;
dashCoolCounter = dashCooldown;
rb.velocity = new Vector2(dashSpeed * direction, rb.velocity.y);
Debug.Log("Dash Started");
}
else if(isDashing)
{
rb.velocity = new Vector2(dashSpeed * direction, rb.velocity.y);
dashTime += Time.deltaTime;
if(dashTime >= maxDashTime)
{
isDashing = false;
Debug.Log("No Dash");
}
}
}
// resets dash cooldown
if (dashCoolCounter > 0)
{
dashCoolCounter -= Time.deltaTime;
}
}

Unity jump issue

I make 3rd person game, where i have script for control model of my character.
Problem is that when i jump and don't push any button he stack in the air, but if i jump with pushing controlling button he worked normally.
Thanks in advance.
Player controller script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(CharacterController))]
public class RelativeMovement : MonoBehaviour
{
[SerializeField] private Transform target;
public float rotSpeed = 5.0f;
public float moveSpeed = 6.0f;
public float jumpSpeed = 15.0f;
public float gravity = -9.8f;
public float terminalVelocity = -20.0f;
public float minFall = -1.5f;
private float _vertSpeed;
private CharacterController _charController;
private ControllerColliderHit _contact;
void Start()
{
_vertSpeed = minFall;
_charController = GetComponent<CharacterController>();
}
void Update()
{
Vector3 movement = Vector3.zero;
float horInput = Input.GetAxis("Horizontal");
float vertInput = Input.GetAxis("Vertical");
if(horInput != 0 || vertInput != 0)
{
movement.x = horInput * moveSpeed;
movement.z = vertInput * moveSpeed;
movement = Vector3.ClampMagnitude(movement, moveSpeed);
Quaternion tmp = target.rotation;
target.eulerAngles = new Vector3(0, target.eulerAngles.y, 0);
movement = target.TransformDirection(movement);
target.rotation = tmp;
Quaternion direction = Quaternion.LookRotation(movement);
transform.rotation = Quaternion.Lerp(transform.rotation,
direction, rotSpeed * Time.deltaTime);
bool hitGround = false;
RaycastHit hit;
if(_vertSpeed < 0 && Physics.Raycast(transform.position, Vector3.down, out hit))
{
float check =
(_charController.height + _charController.radius) / 1.9f;
hitGround = hit.distance <= check;
}
if(hitGround)
{
if (Input.GetButtonDown("Jump"))
{
_vertSpeed = jumpSpeed;
}
else
{
_vertSpeed = minFall;
}
}
else
{
_vertSpeed += gravity * 5 * Time.deltaTime;
if(_vertSpeed < terminalVelocity)
{
_vertSpeed = terminalVelocity;
}
if(_charController.isGrounded)
{
if(Vector3.Dot(movement, _contact.normal) < 0)
{
movement = _contact.normal * moveSpeed;
}
else
{
movement += _contact.normal * moveSpeed;
}
}
}
movement.y = _vertSpeed;
movement *= Time.deltaTime;
_charController.Move(movement);
}
}
void OnControllerColliderHit(ControllerColliderHit hit)
{
_contact = hit;
}
}
Jesus photo:
enter image description here
I didn't go through all of the code but I can immediately see what can cause the problem you describe:
your entire logic happen under this if statement:
if(horInput != 0 || vertInput != 0)
So everything inside this logic block will happen only when you actively press a movement button.
You can remove it (or better yet, close the if block at the right spot.. I think it would be 2 lines down)
The answer of this question is:
if((horInput == 0 || vertInput == 0) || (horInput != 0 && vertInput != 0))
{
movement.x = horInput * moveSpeed;
movement.z = vertInput * moveSpeed;
if(horInput != 0 || vertInput != 0)
{
movement = Vector3.ClampMagnitude(movement, moveSpeed);
Quaternion tmp = target.rotation;
target.eulerAngles = new Vector3(0, target.eulerAngles.y, 0);
movement = target.TransformDirection(movement);
target.rotation = tmp;
Quaternion direction = Quaternion.LookRotation(movement);
transform.rotation = Quaternion.Lerp(transform.rotation,
direction, rotSpeed * Time.deltaTime);
}
Thanks Joe

Clipping and zooming platformer

I am currently in the process of developing my first platformer, and I've decided that I want to bake my own acceleration and deceleration for movement instead of using unity's wonky physics.
This has brought up two roadblocks, one being that my character will just clip through objects like walls to jump over or off of, and the other is that if I try to switch directions while decelerating, my character will turn around, but it won't change directions and my acceleration will bypass the limit I set for it (in layman's, it zooms backwards).
I need help fixing this and can describe any of the functions of the variables if asked. There is no physics material on my character, and I am using physics for the jump.
All of the variables are defined in the unity editor for easier tweaking except for currentSpeed, jumpCount, FallTime and canJump, which I have serialized so I can observe them during testing.
I've tried changing
newPos = new Vector2(transform.position.x + currentSpeed, transform.position.y);
transform.position = newPos;
to addForce but it messed with the jumping.
public class PlayerControls : MonoBehaviour {
//walk Vars
[SerializeField] float currentSpeed;
[SerializeField] float maxSpeed;
[SerializeField] float jumpstart;
[SerializeField] float acceleration;
[SerializeField] float deceleraton;
int isFlip = 1;
Vector2 newPos;
Quaternion flip;
//jump Vars
[SerializeField] public int jumpCount;
[SerializeField] public int jumpCountMax;
[SerializeField] public float jumpVel;
[SerializeField] public float fallMulti;
[SerializeField] public float shortMulti;
[SerializeField] public float fallTime;
[SerializeField] public float coyoteTime;
[SerializeField] bool canJump = true;
[SerializeField] bool didJump;
//references
Rigidbody2D rb;
private void Awake() {
rb = GetComponent<Rigidbody2D>();
}
//walk Functions
private void speedCalc() {
currentSpeed += jumpstart * isFlip;
if (currentSpeed * isFlip >= maxSpeed) {
currentSpeed = maxSpeed * isFlip;
}
else {
currentSpeed = (currentSpeed * acceleration);
}
}
private void Start() {
currentSpeed = 0;
}
private void Update() {
//calculate coyote time
if (fallTime == coyoteTime) {
if (didJump == false) {
jumpCount += 1;
}
}
if (jumpCount >= jumpCountMax) {
canJump = false;
} else {
canJump = true;
}
if (rb.velocity.y == 0) {
jumpCount = 0;
didJump = false;
}
//calculate isFlip
if (Input.GetButton("Right")) {
flip = Quaternion.Euler(0, 0, 0);
transform.rotation = flip;
isFlip = 1;
} else if (Input.GetButton("Left")) {
flip = Quaternion.Euler(0, 180, 0);
transform.rotation = flip;
isFlip = -1;
}
//calculate acceleration & deceleration
if (!Input.GetButton("Right") && !Input.GetButton("Left")) {
if (currentSpeed * isFlip <= jumpstart) {
currentSpeed = 0;
} else {
currentSpeed = (currentSpeed / deceleraton);
}
} else {
speedCalc();
}
//implement falling and dyanamic jumping
if (rb.velocity.y < 0) {
fallTime += 1;
rb.velocity += Vector2.up * Physics2D.gravity * (fallMulti - 1) * Time.deltaTime;
} else if (rb.velocity.y == 0) {
fallTime = 0;
} else if (rb.velocity.y > 0 && !Input.GetButton("Jump")) {
rb.velocity += Vector2.up * Physics2D.gravity * (shortMulti - 1) * Time.deltaTime;
}
//execute jump
if (Input.GetButtonDown("Jump") && canJump == true) {
didJump = true;
rb.velocity = Vector2.up * jumpVel;
jumpCount += 1;
}
//move character position
newPos = new Vector2(transform.position.x + currentSpeed, transform.position.y);
transform.position = newPos;
}
}
There where no error messages or anything but I'm 80% sure its my logic and ordering. The acceleration might be overlapping with the deceleration and the isFlip.

Categories