player controller jitters unity - c#

when I jump up to an object that is a cube I reach the step offset and it jitters for a little bit before falling to the ground again. I can remove the step offset altogether but that's not what I want as my game is baste around parkour. when I was making this I was following a Brackeys tutorial on YouTube. Brackeys tutorial. can anyone help me out? ,first person object , the object causing most problems, objects in scene
using System.collections;
using System.Collections.Generic;
using UnityEngine;
public class keymovement : MonoBehaviour
{
public CharacterController controller;
public float speed = 12f;
public float gravity = -10f;
public Transform groundcheck;
public float groundDistance = 0.5f;
public LayerMask groundMask;
public float jumpheight = 3f;
Vector3 velocity;
bool isgrounded;
void Update()
{
isgrounded = Physics.CheckSphere(groundcheck.position, groundDistance, groundMask);
if (isgrounded && velocity.y < 0)
{
velocity.y = -2;
}
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.GetButton("jump") && isgrounded)
{
velocity.y = Mathf.Sqrt(jumpheight * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
}
}

Basically, the Character controller is fighting with the velocity of the movement script because of how it checks for slopes and steps.
An easy fix is to set the controller's slopeLimit to 90f while you are jumping:
void Update()
{
isgrounded = Physics.CheckSphere(groundcheck.position, groundDistance, groundMask);
if (isgrounded && velocity.y < 0)
{
velocity.y = -2;
controller.slopeLimit = 45f;
}
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.GetButton("Jump") && isgrounded)
{
velocity.y = Mathf.Sqrt(jumpheight * -2f * gravity);
controller.slopeLimit = 90f;
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}

Related

How to make my player move faster/sprint when I hold down the shift key? Unity

so i tried to make my player move faster/make him sprint (it's in first person btw) put it doesn't really work.I wrote the code and everytime a press shift/hold the sprint speed just stacks and when i "walk" im not "walking" im just moving extremely fast.
Here's the entire code:
`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public CharacterController controller;
public float walkSpeed = 10f;
public bool isSprinting;
public float sprintMultiplier;
public float gravity = -9.81f;
public float jump = 1f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
Vector3 velocity;
bool isGrounded;
// Update is called once per frame
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
//Moving
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * walkSpeed * Time.deltaTime);
//Jumping
if (Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jump * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
//Sprinting
if (Input.GetKey(KeyCode.LeftShift))
{
isSprinting = true;
}
else
{
isSprinting = false;
}
if (isSprinting == true)
{
walkSpeed += sprintMultiplier;
}
}
}`
i follwed a bunch of other tutorials but none of them work. If anybody knows how to fix this or make it work please comment:)
This is where the problem is..
if (isSprinting == true)
{
walkSpeed += sprintMultiplier;
}
Every frame in which isSprinting is true, walkspeed is increased, but it never decreases.
You could add some more variables like these...
public float normalSpeed = 10f;
public float sprintSpeed = 20f;
and change your code to this...
if (isSprinting == true)
{
walkSpeed = sprintSpeed;
}
else
{
walkSpeed = normalSpeed;
}
So walkspeed is the variable that dictates how fast your player moves, and when they're walking it's set to normalSpeed, and when they're sprinting it's set to sprintSpeed.

I keep getting the error "Assets\ThirdPersonMovement.cs(49,30): error CS0117: 'Input' does not contain a definition for 'getAxis'"

Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ThirdPersonMovement : MonoBehaviour
{
public CharacterController controller;
public float speed = 6f;
public float turnSmoothTime = 0.1f;
public Transform cam;
private float verticalVelocity;
private float gravity = 14.0f;
private float jumpForce = 10.0f;
float turnSmoothVelocity;
// Update is called once per frame
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 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);
}
if (controller.isGrounded)
{
verticalVelocity = -gravity * Time.deltaTime;
if (Input.getKeyDown(KeyCode.Space))
{
verticalVelocity = jumpForce;
}
}
else
{
verticalVelocity -= gravity * Time.deltaTime;
}
Vector3 moveVector = Vector3.zero;
moveVector.x = Input.getAxis("Horizontal") * speed;
moveVector.y = verticalVelocity;
moveVector.z = Input.getAxis("Vertical") * speed;
controller.Move(moveVector * Time.deltaTime);
}
}
It has been giving me this error for a couple weeks and I can't figure it out.
I've tried seeing if anybody else has had any issues and looking back at how others have overcome this issue, but nothing seems to be working.
C# is case-sensitive.
moveVector.x = Input.GetAxis("Horizontal") * speed;
moveVector.y = verticalVelocity;
moveVector.z = Input.GetAxis("Vertical") * speed;

Why do objects stutter while I move and the camera is rotating?

I have began developing an fps script and followed a tutorial to help with the script. Everything works great now but the only issue is any objects in the view seem to stutter whenever the player is moving and rotating at the same time.
The script for the player's movement and camera rotation is below.
Can anybody point me in the right direction?
Thank you.
{
public Transform cam;
public Rigidbody rb;
public float camRotationSpeed = 5f;
public float camMinimumY = -60f;
public float camMaximumY = 75f;
public float rotationSmoothSpeed = 10f;
public float walkSpeed = 9f;
public float runSpeed = 14f;
public float maxSpeed = 20f;
public float jumpPower = 30f;
public float extraGravity = 45;
float bodyRotationX;
float camRotationY;
Vector3 directionIntentX;
Vector3 directionIntentY;
float speed;
public bool grounded;
void Update()
{
LookRotation();
Movement();
ExtraGravity();
GroundCheck();
if(grounded && Input.GetButtonDown("Jump"))
{
Jump();
}
}
void LookRotation()
{
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
bodyRotationX += Input.GetAxis("Mouse X") * camRotationSpeed;
camRotationY += Input.GetAxis("Mouse Y") * camRotationSpeed;
camRotationY = Mathf.Clamp(camRotationY, camMinimumY, camMaximumY);
Quaternion camTargetRotation = Quaternion.Euler(-camRotationY, 0, 0);
Quaternion bodyTargetRotation = Quaternion.Euler(0, bodyRotationX, 0);
transform.rotation = Quaternion.Lerp(transform.rotation, bodyTargetRotation, Time.deltaTime * rotationSmoothSpeed);
cam.localRotation = Quaternion.Lerp(cam.localRotation, camTargetRotation, Time.deltaTime * rotationSmoothSpeed);
}
void Movement()
{
directionIntentX = cam.right;
directionIntentX.y = 0;
directionIntentX.Normalize();
directionIntentY = cam.forward;
directionIntentY.y = 0;
directionIntentY.Normalize();
rb.velocity = directionIntentY * Input.GetAxis("Vertical") * speed + directionIntentX * Input.GetAxis("Horizontal") * speed + Vector3.up * rb.velocity.y;
rb.velocity = Vector3.ClampMagnitude(rb.velocity, maxSpeed);
if (Input.GetKey(KeyCode.LeftShift))
{
speed = runSpeed;
}
if (!Input.GetKey(KeyCode.LeftShift))
{
speed = walkSpeed;
}
}
void ExtraGravity()
{
rb.AddForce(Vector3.down * extraGravity);
}
void GroundCheck()
{
RaycastHit groundHit;
grounded = Physics.Raycast(transform.position, -transform.up, out groundHit, 1.25f);
}
void Jump()
{
rb.AddForce(Vector3.up * jumpPower, ForceMode.Impulse);
}
}
This probably happens because the frame needs to update the camera rotation and the player position at the same time. i would suggest doing the rotation of the camera in fixed update. because this will run at the end of each frame.
like this:
void FixedUpdate()
{
LookRotation();
}
another thing i would suggest is to move the player while the groundcheck is being ran, because if you do it seperately i can see a bug coming up when the player moves faster then the code can run or something. so a tip would be or to run it inside the movement method, or call the method while you are calling the movement method.
this:
void Movement()
{
directionIntentX = cam.right;
directionIntentX.y = 0;
directionIntentX.Normalize();
directionIntentY = cam.forward;
directionIntentY.y = 0;
directionIntentY.Normalize();
rb.velocity = directionIntentY * Input.GetAxis("Vertical") * speed + directionIntentX * Input.GetAxis("Horizontal") * speed + Vector3.up * rb.velocity.y;
rb.velocity = Vector3.ClampMagnitude(rb.velocity, maxSpeed);
if (Input.GetKey(KeyCode.LeftShift))
{
speed = runSpeed;
}
if (!Input.GetKey(KeyCode.LeftShift))
{
speed = walkSpeed;
}
GroundCheck();
}
or litteraly copy and paste the code within your movement method.

Players can't jump well

I am able to move player referring to this YouTube video.
FIRST PERSON MOVEMENT in Unity - FPS Controller
However, when a player jumps, if the direction of travel is a wall, the player cannot jump well.
like this
If I jump from a distance, I can jump onto the wall.
Camera Script:
public float mouseSensitivity;
[SerializeField]
Transform playerBody = default;
float xRotation = 0f;
private void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
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);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
playerBody.Rotate(Vector3.up * mouseX);
}
Movement Script:
[SerializeField]
CharacterController CharacterController = default;
[SerializeField]
LayerMask groundMask = default;
[SerializeField]
Transform groundCheck = default;
float groundDistance = 0.4f;
bool isGrounded = false;
public float playerSpeed;
public float playerGravity;
public float playerJumpSpeed;
Vector3 velocity;
private 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;
CharacterController.Move(move * playerSpeed * Time.deltaTime);
if (Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(playerJumpSpeed * -2f * playerGravity);
}
velocity.y += playerGravity * Time.deltaTime;
CharacterController.Move(velocity * Time.deltaTime);
}
Please tell me someone
i think it has something to do with these lines.
if (isGrounded && velocity.y < 0)
velocity.y = -2f;
Also check if the wall is on the ground mask because if it is it will be make the isGrounded be true which would be why it the player is falling like that
also i would recommend using a raycast instead of this:
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
Setting Step Offset of Character controller to 0 eliminated vibration. It can no longer walk on small steps, but now I can jump well.

Unity collider prefab doesn't work on one side

I have a collider prefab (a cube, with a box collider the size of the cube). In one scene, my player collides perfectly with it, but in another scene, the player glitches and phases through one side of the collider but not the other. Rotating it changes the side that it glitches out on, so it always faces the same global direction.
What could be causing this? I've made sure the prefab for both the player and collider object are exactly the same across scenes, and nothing effects the collisions besides the player controller script which moves the player and has a condition for OnCollisionExit that sets the rigidbody's velocity to 0.
Added the code below. The input is with joysticks (think the joysticks in a helicopter). Like I said, the collision works perfectly usually, but for some reason only in this scene it doesn't. I suspect it's some kind of hierarchy or rigidbody problem but I've checked seemingly everything.
https://github.com/ben-humphries/FRC-Driving-Simulation
using UnityEngine;
using UnityEngine.UI;
public class ChassisController : MonoBehaviour {
public UIController uiController;
public Canvas PauseCanvas;
public float speedLinear = 10f;
public float speedAngular = 100f;
public float joyDeadZone = 0.5f;
public float rotationOffset = 3f;
public bool squaredMovement = false;
public DriveModes driveMode = DriveModes.Tank;
[HideInInspector]
public bool paused = false;
private Rigidbody rigidbody;
Vector3 lastLinearPosition;
float lastAngularPosition;
void Start () {
rigidbody = GetComponent<Rigidbody> ();
lastLinearPosition = Vector3.zero;
lastAngularPosition = 0f;
paused = false;
}
void FixedUpdate () {
if (!paused) {
/*
* INPUT
*/
if (driveMode == DriveModes.Tank) {
if (Mathf.Abs (Input.GetAxis ("VerticalLeft")) > joyDeadZone) {
Vector3 rotatePoint = (transform.position) + transform.TransformDirection (Vector3.right) * rotationOffset;
Vector3 rotateAxis = transform.TransformDirection (Vector3.up);
Debug.DrawRay (rotatePoint, rotateAxis * 10f, Color.red);
transform.RotateAround (rotatePoint, rotateAxis, -speedAngular * Input.GetAxis ("VerticalLeft") * Time.fixedDeltaTime * (squaredMovement ? Mathf.Abs (Input.GetAxis ("VerticalLeft")) : 1));
}
if (Mathf.Abs (Input.GetAxis ("VerticalRight")) > joyDeadZone) {
Vector3 rotatePoint = (transform.position) + transform.TransformDirection (Vector3.left) * rotationOffset;
Vector3 rotateAxis = transform.TransformDirection (Vector3.up);
Debug.DrawRay (rotatePoint, rotateAxis * 10f, Color.red);
transform.RotateAround (rotatePoint, rotateAxis, speedAngular * Input.GetAxis ("VerticalRight") * Time.fixedDeltaTime * (squaredMovement ? Mathf.Abs (Input.GetAxis ("VerticalRight")) : 1));
}
} else if (driveMode == DriveModes.Mecanum) {
if (Mathf.Abs (Input.GetAxis ("VerticalRight")) > joyDeadZone) {
transform.Translate (Vector3.forward * -speedLinear * Input.GetAxis ("VerticalRight") * Time.fixedDeltaTime * (squaredMovement ? Mathf.Abs (Input.GetAxis ("VerticalRight")) : 1));
}
if (Mathf.Abs (Input.GetAxis ("HorizontalRight")) > joyDeadZone) {
transform.Translate (Vector3.right * speedLinear / 5f * Input.GetAxis ("HorizontalRight") * Time.fixedDeltaTime * (squaredMovement ? Mathf.Abs (Input.GetAxis ("HorizontalRight")) : 1));
}
if (Mathf.Abs (Input.GetAxis ("TwistRight")) > joyDeadZone) {
transform.Rotate (0, speedAngular * Input.GetAxis ("TwistRight") * Time.fixedDeltaTime * (squaredMovement ? Mathf.Abs (Input.GetAxis ("TwistRight")) : 1), 0);
}
}
float linearVelocity = Mathf.Round (((transform.position - lastLinearPosition) / Time.fixedDeltaTime).magnitude * 100f) / 100f;
lastLinearPosition = transform.position;
float angularVelocity = Mathf.Round ((transform.eulerAngles.y - lastAngularPosition) / Time.fixedDeltaTime * Mathf.Deg2Rad * 100f) / 100f;
lastAngularPosition = transform.eulerAngles.y;
uiController.UpdateVelocities (linearVelocity, angularVelocity);
}
}
void OnCollisionExit(Collision col){
rigidbody.isKinematic = true;
rigidbody.velocity = Vector3.zero;
rigidbody.angularVelocity = Vector3.zero;
rigidbody.isKinematic = false;
}
public enum DriveModes{
Tank,
Mecanum
}
public void setDriveMode(){
int index = PauseCanvas.transform.GetChild (1).GetComponent<Dropdown> ().value;
if (index == 0) {
driveMode = DriveModes.Tank;
} else if (index == 1) {
driveMode = DriveModes.Mecanum;
}
uiController.UpdateDriveMode (index == 0 ? "Tank" : "Mecanum");
}
}
When GameObject has Rigidbody and Collider and you want collision, do not move the Object by transform.Translate or rotate it with transform.Rotate or transform.RotateAround. When you do this there will be no collision.
The right way to move GameObject with a Rigidbody and Collision is with the Rigidbody.MovePosition function.
The correct way to rotate it is to use the Rigidbody.MoveRotation function.
Example of Rigidbody.MovePosition:
float h = Input.GetAxisRaw("Horizontal");
float v = Input.GetAxisRaw("Vertical");
Vector3 tempVect = new Vector3(h, 0, v);
tempVect = tempVect.normalized * speed * Time.deltaTime;
rb.MovePosition(transform.position + tempVect);
Example of Rigidbody.MoveRotation:
Quaternion deltaRotation = Quaternion.Euler(eulerAngleVelocity * Time.deltaTime);
rb.MoveRotation(rb.rotation * deltaRotation);
You need to replace transform.Translate, transform.Rotate and transform.RotateAround with these.

Categories

Resources