I wrote a character controller script on my own but I can’t seem to jump forward when I am running I can jump Front when I walk but I can’t do it if I run… : ( can someone help me, please?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour {
public Transform RaycastPt;
[Range(0,40)]
public float speedFb;
[Range(0, 20)]
public float speedLr;
private bool isGrounded;
private bool isStill;
private Vector3 moveAmount;
private Vector3 jumpMovement;
private float oldSpeedFb;
private float oldSpeedLr;
private Vector3 oldMoveAmount;
public float jumpSpeed = 100f;
private float velocityY = 0;
private float oldJumpSpeed;
private float dirFb;
private float dirLr;
float jumpMx;
float jumpMy;
public Rigidbody rb;
// Use this for initialization
void Start () {
Rigidbody rb = GetComponent<Rigidbody>();
oldSpeedFb = speedFb;
oldJumpSpeed = jumpSpeed;
}
// Update is called once per frame
void Update () {
}
void FixedUpdate()
{
CheckIsGrounded();
DirBefJump();
Movement();
Jump();
}
void CheckIsGrounded()
{
RaycastHit hitInfo;
float maxDistance = 1f;
if (Physics.Raycast(RaycastPt.position, Vector3.down, out hitInfo, maxDistance))
{
//print("Found an object - distance: " + hitInfo.distance);
isGrounded = true;
//print("true");
}
else
{
isGrounded = false;
//print("false");
}
}
void Movement()
{
if (isGrounded)
{
if (Input.GetKey(KeyCode.LeftShift))
{
speedFb = 3f * oldSpeedFb;
jumpSpeed = 1.5f * oldJumpSpeed;
}
else
{
speedFb = oldSpeedFb;
jumpSpeed = oldJumpSpeed;
}
Vector3 input = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
if (input == Vector3.zero)
{
isStill = true;
}
else
{
isStill = false;
}
Vector3 direction = input.normalized;
Vector3 moveAmount = new Vector3(direction.x * speedLr * Time.deltaTime, 0, direction.z * speedFb * Time.deltaTime);
transform.Translate(moveAmount);
}
}
void Jump()
{
if(isStill == true)
{
jumpMovement = Vector3.up;
}
if (Input.GetKeyDown(KeyCode.Space))
{
print("SpacePressed");
if (isGrounded)
{
velocityY = 1;
rb.AddForce(jumpMovement * jumpSpeed, ForceMode.VelocityChange);
print("forceAdded: " + new Vector3(jumpMovement.x, velocityY * jumpSpeed, jumpMovement.y));
//transform.Translate(oldMoveAmount);
}
}
}
void DirBefJump()
{
if (Input.GetKey(KeyCode.W))
{
dirFb = 1;
}
else if (Input.GetKey(KeyCode.S))
{
dirFb = -1;
}
else
{
dirFb = 0f;
}
if (Input.GetKey(KeyCode.D))
{
dirLr = 1;
}
else if (Input.GetKey(KeyCode.A))
{
dirLr = -1;
}
else
{
dirLr = 0f;
}
float dirMag = Mathf.Sqrt(Mathf.Pow(dirLr + dirFb, 2) - 2 * dirLr * dirFb);
float jumpMx = dirLr / dirMag;
float jumpMy = dirFb / dirMag;
jumpMovement = new Vector3(jumpMx, velocityY, jumpMy);
}
}