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

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;
}

Related

Player 1 controls player 2 and vice versa

When i create room, and player 2 connect to room, i control him, and he controls me. What should I do?
Player controller combined with unity3d fps basicrigidbodypush script and mouse look.
Unity 3d 2020.3.26f version, development mode off. Video of it (left button and input field is creating room, right button and input field is joining room)https://dropmefiles.com/XPPa3.
In resources folder there is player prefab.
Player prefab contains mesh renderer, player controller script (below), character controller, photon view, photon transform view classic (synchronize position and rotation turned on), rigidbody and photon rigidbody view (all enabled)
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
public class PlayerController : MonoBehaviour
{
PhotonView view;
public LayerMask pushLayers;
public bool canPush;
[Range(0.5f, 5f)] public float strength = 1.1f;
public float jumpHeight = 3f;
public GameObject camera;
public LayerMask groundMask;
public Transform groundCheck;
public CharacterController controller;
public float speed = 10f;
public float gravity = -9.8f;
public float groundDistance = 0.4f;
Vector3 velocity;
bool isGrounded;
public Transform PlayerBody;
public float MouseSensitivity = 100f;
float xRotation = 0f;
// Start is called before the first frame update
void Start()
{
Cursor.visible = false;
view = GetComponent<PhotonView>();
}
// Update is called once per frame
void Update()
{
if (view.IsMine) {
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if (isGrounded && velocity.y < 0) {
velocity.y = -7f;
}
if (isGrounded && Input.GetButtonDown("Jump")) {
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
if(Input.GetKeyDown(KeyCode.F)) {
CursorTrigger();
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
float mouseX = Input.GetAxis("Mouse X") * MouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * MouseSensitivity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
camera.transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
PlayerBody.Rotate(Vector3.up * mouseX);
}
}
private void PushRigidBodies(ControllerColliderHit hit)
{
if (view.IsMine) {
Rigidbody body = hit.collider.attachedRigidbody;
if (body == null || body.isKinematic) return;
var bodyLayerMask = 1 << body.gameObject.layer;
if ((bodyLayerMask & pushLayers.value) == 0) return;
if (hit.moveDirection.y < -0.3f) return;
Vector3 pushDir = new Vector3(hit.moveDirection.x, 0.0f, hit.moveDirection.z);
body.AddForce(pushDir * strength, ForceMode.Impulse);
}
}
private void OnControllerColliderHit(ControllerColliderHit hit)
{
if (view.IsMine) {
if (canPush) PushRigidBodies(hit);
}
}
public void CursorTrigger() {
if (view.IsMine) {
Cursor.visible = !Cursor.visible;
}
}
}```
I usually go about this in a different way. Try the following:
if(!view.isMine)
{
return;
}
And then continue with your code afterwards.

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.

Unity 3D character c# script, jump not working?

So I have this first person player controller c# script, (I followed brackeys' tutorial) and I have the jump input coded, basically word for word, but for some reason it doesn't jump, instead once I start the game, the player just floats up infinitely, which is definitely not what I want. Here's the script incase any of you know how to fix it(sorry if the error is a typo or something, but this would help greatly):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public CharacterController controller;
public float speed = 12f;
public float gravity = -9.81f;
public LayerMask groundMask;
public float groundDistance = 0.4f;
public Transform groundCheck;
public float jumpHeight = 3f;
Vector3 velocity;
bool isGrounded;
void Update()
{
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.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
Thanks in advance.

Stop my first person character controller going through the wall in Unity using C#?

As seen in the video here: https://i.gyazo.com/ad45ef9e231fd2f9ec6d4cf76889aece.mp4
My code:
MouseLook.cs:
using UnityEngine;
using System.Collections;
public class MouseLook : MonoBehaviour
{
public enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2 }
public RotationAxes axes = RotationAxes.MouseXAndY;
public float sensitivityX = 3F;
public float sensitivityY = 3F;
public Camera playerCamera;
public float minimumX = -360F;
public float maximumX = 360F;
public float minimumY = -60F;
public float maximumY = 60F;
private float rotationX = 0F;
private float rotationY = 0F;
private Quaternion originalRotation;
void Update()
{
if (axes == RotationAxes.MouseXAndY)
{
rotationX += Input.GetAxis("Mouse X") * sensitivityX;
rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
rotationX = ClampAngle(rotationX, minimumX, maximumX);
rotationY = ClampAngle(rotationY, minimumY, maximumY);
Quaternion xQuaternion = Quaternion.AngleAxis(rotationX, Vector3.up);
Quaternion yQuaternion = Quaternion.AngleAxis(rotationY, -Vector3.right);
transform.localRotation = originalRotation * xQuaternion * yQuaternion;
}
if (axes == RotationAxes.MouseX)
{
rotationX += Input.GetAxis("Mouse X") * sensitivityX;
rotationX = ClampAngle(rotationX, minimumX, maximumX);
Quaternion xQuaternion = Quaternion.AngleAxis(rotationX, Vector3.up);
transform.localRotation = originalRotation * xQuaternion;
}
if (axes == RotationAxes.MouseY || playerCamera != null)
{
rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
rotationY = ClampAngle(rotationY, minimumY, maximumY);
Quaternion yQuaternion = Quaternion.AngleAxis(-rotationY, Vector3.right);
if (playerCamera != null)
{
playerCamera.transform.localRotation = originalRotation * yQuaternion;
}
else
{
transform.localRotation = originalRotation * yQuaternion;
}
}
}
void Start()
{
/*
if (gameObject.GetComponent<Rigidbody>())
{
gameObject.GetComponent<Rigidbody>().freezeRotation = true;
}
*/
originalRotation = transform.localRotation;
}
public static float ClampAngle(float angle, float min, float max)
{
if (angle < -360F)
{
angle += 360F;
}
if (angle > 360F)
{
angle -= 360F;
}
return Mathf.Clamp(angle, min, max);
}
}
FirstPersonController.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
using Cursor = UnityEngine.Cursor;
public class FirstPersonController : MonoBehaviour
{
private float speed = 5;
private float jumpPower = 4;
Rigidbody rb;
CapsuleCollider col;
public GameObject crossHair;
bool isActive;
float HorizontalInput;
float VerticalInput;
void Start()
{
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
rb = GetComponent<Rigidbody>();
col = GetComponent<CapsuleCollider>();
crossHair = GameObject.FindWithTag("CrossHair");
}
void Update()
{
HorizontalInput = Input.GetAxisRaw("Horizontal");
VerticalInput = Input.GetAxisRaw("Vertical");
if (Input.GetKeyDown("escape"))
{
Cursor.lockState = CursorLockMode.None;
}
if (Input.GetButtonDown("Sprint"))
{
speed = 15;
}
if (Input.GetButtonUp("Sprint"))
{
speed = 5;
}
if (Input.GetKeyDown(KeyCode.H))
{
isActive = !isActive;
}
if (isActive)
{
crossHair.SetActive(true);
}
else
{
crossHair.SetActive(false);
}
}
void FixedUpdate()
{
Vector3 xMovement = transform.right * speed * HorizontalInput * Time.deltaTime;
Vector3 zMovement = transform.forward * speed * VerticalInput * Time.deltaTime;
rb.velocity = new Vector3(HorizontalInput, 0, VerticalInput) * speed;
if (isGrounded() && Input.GetButtonDown("Jump"))
{
rb.AddForce(Vector3.up * jumpPower, ForceMode.Impulse);
}
}
private bool isGrounded()
{
return Physics.Raycast(transform.position, Vector3.down, col.bounds.extents.y + 0.1f);
}
}
Is there anything wrong I am doing in this code, if so how do I fix it?
Entire project can be downloaded here: https://github.com/Some-T/FirstPersonController-CSharp
Project has relevant colliders and rigidbodies set up!
Someone has advised me to use shapecast, but I believe that may incorrect? I can't see how that would work as my player does not have character controller component added to it?
Overall how do I stop my first person character controller going through the wall like in the initial video specified above?
Upon further research I have discovered the following:
The answer is to use:
https://docs.unity3d.com/ScriptReference/Rigidbody.AddForce.html as a quick fix.
But definitively for flawlessness use:
https://docs.unity3d.com/ScriptReference/Rigidbody-velocity.html
As to how in C# I am not so sure, but here is a screen shot I did in bolt asset.
Currently I have movmement working with velocity but it does not work properly, not sure as to why? So overall my question now is how do I get movement working using velocity? I added a line in FirstPersonController.cs that moves the character using velocity of rb.velocity = new Vector3(HorizontalInput, 0, VerticalInput) * speed; so my only question and issue now is my player does not move in the direction the camera on my player is facing so I am not sure how to fix this specific thing overall?
In your project code is different from one that you provided here.
Try to enable rigidbody`s rotation constraint - freeze X and Z rotation, leave only Y. When you rotate your capsule collider (as it works in your project), it can "climb" on a wall.
Do the isGrounded check when you move, and lock movement, if not grounded.
Try to increase Collider.contactOffset
If above does not helps, try to use Rigidbody.velocity instead of Rigidbody.MovePosition.
You can also reduce Rigidbody.drag
In general, pretty good technique is to use NavMesh for movement - in this way, you able to explicitly lock player from movement outside of navmesh surface. But, of course, it doesn`t fit to many gameplays.
Hope, it helps.
upd
You move your player like this:
void FixedUpdate()
{
Vector3 xMovement = transform.right * speed * HorizontalInput * Time.deltaTime;
Vector3 zMovement = transform.forward * speed * VerticalInput * Time.deltaTime;
}
Note, that you not even apply it to rigidbody;
But you get your input this way:
float HorizontalInput = Input.GetAxis("Horizontal");
float VerticalInput = Input.GetAxis("Vertical");
in Update, so input just stays inside Update, and does not applied at all. You declared your variables twice, once on class top, another in Update().

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.

Categories