- Home /
Jumping in only the direction of the last key pressed
Hai guys. I've been trying to figure this out for about 5 hours now, I have a first person controller script based on the Unity Standard Assets one and I'm trying to figure out how to jump to the direction of the key pressed and not be able to move in any other direction until the character is grounded again. Does anyone have any idea on how to do this?
This is my Player script
using UnityEngine;
using System.Collections;
using Random = UnityEngine.Random;
[RequireComponent(typeof (CharacterController))]
[RequireComponent(typeof (AudioSource))]
public class Player : MonoBehaviour {
public bool isWalking;
public float walkSpeed;
public float runSpeed;
[Range(0f, 1f)] public float runstepLenghten;
public float jumpSpeed;
public float stickToGroundForce;
public float gravityMultiplier;
public MouseLook mouseLook;
public bool useFovKick;
public FOVKick fovKick = new FOVKick();
public bool useHeadBob;
public CurveControlledBob headBob = new CurveControlledBob();
public LerpControlledBob jumpBob = new LerpControlledBob();
public float stepInterval;
public AudioClip[] footstepSounds;
public AudioClip jumpSound;
public AudioClip landSound;
private Camera camera = new Camera();
private bool jump;
private float yRotation;
private Vector2 input;
private Vector3 moveDir = Vector3.zero;
private CharacterController characterController;
private CollisionFlags collisionFlags;
private bool previouslyGrounded;
private Vector3 originalCameraPosition;
private float stepCycle;
private float nextStep;
private bool jumping;
private AudioSource audioSource;
private void Start(){
characterController = GetComponent<CharacterController>();
camera = Camera.main;
originalCameraPosition = camera.transform.localPosition;
fovKick.Setup(camera);
headBob.Setup(camera, stepInterval);
stepCycle = 0f;
nextStep = stepCycle / 2f;
jumping = false;
audioSource = GetComponent<AudioSource>();
mouseLook.Init(transform , camera.transform);
}
private void Update(){
RotateView();
// the jump state needs to read here to make sure it is not missed
if (!jump)
{
jump = Input.GetButtonDown("Jump");
}
if (!previouslyGrounded && characterController.isGrounded)
{
StartCoroutine(jumpBob.DoBobCycle());
PlayLandingSound();
moveDir.y = 0f;
jumping = false;
}
if (!characterController.isGrounded && !jumping && previouslyGrounded)
{
moveDir.y = 0f;
}
previouslyGrounded = characterController.isGrounded;
}
private void PlayLandingSound(){
audioSource.clip = landSound;
audioSource.Play();
nextStep = stepCycle + .5f;
}
private void FixedUpdate(){
float speed;
GetInput(out speed);
// always move along the camera forward as it is the direction that it being aimed at
Vector3 desiredMove = transform.forward * input.y + transform.right * input.x;
// get a normal for the surface that is being touched to move along it
RaycastHit hitInfo;
Physics.SphereCast(transform.position, characterController.radius, Vector3.down, out hitInfo, characterController.height / 2f);
desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized;
moveDir.x = desiredMove.x * speed;
moveDir.z = desiredMove.z * speed;
if (characterController.isGrounded)
{
moveDir.y = -stickToGroundForce;
if (jump)
{
moveDir.y = jumpSpeed;
PlayJumpSound();
jump = false;
jumping = true;
}
}
else
{
moveDir += Physics.gravity * gravityMultiplier * Time.fixedDeltaTime;
}
if (!characterController.isGrounded) {
}
collisionFlags = characterController.Move(moveDir * Time.fixedDeltaTime);
ProgressStepCycle(speed);
UpdateCameraPosition(speed);
}
private void PlayJumpSound(){
audioSource.clip = jumpSound;
audioSource.Play();
}
private void ProgressStepCycle(float speed){
if (characterController.velocity.sqrMagnitude > 0 && (input.x != 0 || input.y != 0))
{
stepCycle += (characterController.velocity.magnitude + (speed *(isWalking ? 1f : runstepLenghten)))*
Time.fixedDeltaTime;
}
if (!(stepCycle > nextStep))
{
return;
}
nextStep = stepCycle + stepInterval;
PlayFootStepAudio();
}
private void PlayFootStepAudio(){
if (!characterController.isGrounded)
{
return;
}
// pick & play a random footstep sound from the array,
// excluding sound at index 0
int n = Random.Range(1, footstepSounds.Length);
audioSource.clip = footstepSounds[n];
audioSource.PlayOneShot(audioSource.clip);
// move picked sound to index 0 so it's not picked next time
footstepSounds[n] = footstepSounds[0];
footstepSounds[0] = audioSource.clip;
}
private void UpdateCameraPosition(float speed){
Vector3 newCameraPosition;
if (!useHeadBob)
{
return;
}
if (characterController.velocity.magnitude > 0 && characterController.isGrounded)
{
camera.transform.localPosition = headBob.DoHeadBob(characterController.velocity.magnitude + (speed * (isWalking ? 1f : runstepLenghten)));
newCameraPosition = camera.transform.localPosition;
newCameraPosition.y = camera.transform.localPosition.y - jumpBob.Offset();
}
else
{
newCameraPosition = camera.transform.localPosition;
newCameraPosition.y = originalCameraPosition.y - jumpBob.Offset();
}
camera.transform.localPosition = newCameraPosition;
}
private void GetInput(out float speed){
// Read input
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
bool waswalking = isWalking;
isWalking = !Input.GetKey(KeyCode.LeftShift);
// set the desired speed to be walking or running
speed = isWalking ? walkSpeed : runSpeed;
input = new Vector2(horizontal, vertical);
// normalize input if it exceeds 1 in combined length:
if (input.sqrMagnitude > 1)
{
input.Normalize();
}
// handle speed change to give an fov kick
// only if the player is going to a run, is running and the fovkick is to be used
if (isWalking != waswalking && useFovKick && characterController.velocity.sqrMagnitude > 0)
{
StopAllCoroutines();
StartCoroutine(!isWalking ? fovKick.FOVKickUp() : fovKick.FOVKickDown());
}
}
private void RotateView(){
mouseLook.LookRotation (transform, camera.transform);
}
private void OnControllerColliderHit(ControllerColliderHit hit){
Rigidbody body = hit.collider.attachedRigidbody;
//dont move the rigidbody if the character is on top of it
if (collisionFlags == CollisionFlags.Below)
{
return;
}
if (body == null || body.isKinematic)
{
return;
}
body.AddForceAtPosition(characterController.velocity * 0.1f, hit.point, ForceMode.Impulse);
}
}
Sorry for the extremely long script. And please tell me if I wasn't clear enough with my question.
Based on your request as worded, couldn't you just disallow all input while not grounded?
The whole "steering in the air" concept is fairly common in FPS games, but it's altogether unrealistic unless the character is part flying-squirrel. Only allowing input in the launch direction is almost fruitless unless you've got a very specific need. Like a jet pack or something? In which case, you could use that "jetpack-jump" button to control the duration of the boost, without caring about x,y input (use the last grounded input to establish the non-changing direction).
If you really want exactly what you're asking for, keep a record of the last frame's input, and when you're not grounded, only respond to input in that direction until you're grounded again.
You can compare vectors in a useful way here by responding to input according to its Dot Product versus your recorded "last grounded input".
How would I go about recording the last frame's input? Sorry, a bit of a novice over here :p
Easy! $$anonymous$$eep a class-scope vector lastInput.
Vector2 lastInput;
void Update() {
Vector2 currentInput = new Vector2( Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
// make use of the currentInput, including any logic which
// makes comparisons between last & current input
// at the end of Update, write
lastInput = currentInput;
}
Right, I seemed to have gone in a massive circle. One of my original problems was the character stopping dead then jumping rather than jumping into the direction that the player last moved in, do you have any idea? P.S I can show you the code if you'd like?
Your answer
Follow this Question
Related Questions
Character not jumping high enough 1 Answer
Super Ghouls 'n Ghosts style jumps & double jumps? 1 Answer
Jumping mechanism 1 Answer
Jump higher when holding button 5 Answers