How to make an object jump forward? - c#

I've been having problems with getting my character to jump Forward. I've got it set to jump in place but I can't seem to get the JumpFor() to move forward as it jumps. I've tried Vector3 but it only works in 1 direction and transform.forward doesn't seem to work at all.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
//VARIABLES
[SerializeField] private float moveSpeed;
[SerializeField] private float walkSpeed;
[SerializeField] private float runSpeed;
private Vector3 moveDirection;
private Vector3 velocity;
[SerializeField] private bool isGrounded;
[SerializeField] private float groundCheckDistance;
[SerializeField] private LayerMask groundMask;
[SerializeField] private float gravity;
[SerializeField] private float jumpHeight;
//REFERENCES
private CharacterController controller;
private Animator anim;
private Collider Collider;
private void Start()
{
controller = GetComponent();
anim = GetComponentInChildren();
Collider = GetComponent(); ;
}
private void Update()
{
Move();
}
private void Move()
{
isGrounded = Physics.CheckBox(Collider.bounds.center, Collider.bounds.extents, transform.rotation, groundMask);
if (isGrounded && velocity.y < 0)
velocity.y = -2f;
float moveZ = Input.GetAxis("Vertical");
moveDirection = new Vector3(0, 0, moveZ);
moveDirection = transform.TransformDirection(moveDirection);
if (isGrounded)
{
if (moveDirection != Vector3.zero && !Input.GetKey(KeyCode.LeftShift))
{
Walk();
}
else if (moveDirection != Vector3.zero && Input.GetKey(KeyCode.LeftShift))
{
Run();
}
else if (moveDirection == Vector3.zero)
{
Idle();
}
moveDirection *= moveSpeed;
if (isGrounded && Input.GetKeyDown(KeyCode.Space) && moveDirection == Vector3.zero )
{
Jump();
}
if (isGrounded && Input.GetKeyDown(KeyCode.Space) && Input.GetKey(KeyCode.W) && moveDirection != Vector3.zero)
{
JumpFor();
}
anim.SetBool("Jump", false);
anim.SetBool("JumpUp", false);
}
if (!isGrounded)
anim.SetBool("Jump", true);
controller.Move(moveDirection * Time.deltaTime);
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
private void Idle()
{
anim.SetFloat("Speed", 0, 0.02f, Time.deltaTime);
}
private void Walk()
{
moveSpeed = walkSpeed;
anim.SetFloat("Speed", 0.6f, 0.1f, Time.deltaTime);
}
private void Run()
{
moveSpeed = runSpeed;
anim.SetFloat("Speed", 1, 0.1f, Time.deltaTime);
}
private void Jump()
{
velocity.y = Mathf.Sqrt(jumpHeight * -2 * gravity);
}
private void JumpFor()
{
velocity.y = Mathf.Sqrt(jumpHeight * -2 * gravity);
}
}

I Solved it. I ended up using the velocity vector in JumpFor() and gave it a new Vector3 Then I put velocity= transform.TransformDirection(velocity) so it uses the local axis instead of the global one. After that is et it so velocity = Vector3.zero when the player grounds.
Blockquote
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
//VARIABLES
[SerializeField] private float moveSpeed;
[SerializeField] private float walkSpeed;
[SerializeField] private float runSpeed;
[SerializeField] private float JumpDist;
private Vector3 moveDirection;
private Vector3 velocity;
[SerializeField] private bool isGrounded;
[SerializeField] private float groundCheckDistance;
[SerializeField] private LayerMask groundMask;
[SerializeField] private float gravity;
[SerializeField] private float jumpHeight;
//REFERENCES
private CharacterController controller;
private Animator anim;
private Collider Collider;
private Rigidbody rb;
private Transform tran;
private void Start()
{
controller = GetComponent<CharacterController>();
anim = GetComponentInChildren<Animator>();
Collider = GetComponent<BoxCollider>(); ;
rb = GetComponent<Rigidbody>();
tran = GetComponent<Transform>();
}
private void Update()
{
Move();
}
private void Move()
{
isGrounded = Physics.CheckBox(Collider.bounds.center, Collider.bounds.extents, transform.rotation, groundMask);
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float moveZ = Input.GetAxis("Vertical");
moveDirection = new Vector3(0, 0, moveZ);
moveDirection = transform.TransformDirection(moveDirection);
if (isGrounded)
{
velocity = Vector3.zero;
if (moveDirection != Vector3.zero && !Input.GetKey(KeyCode.LeftShift))
{
Walk();
}
else if (moveDirection != Vector3.zero && Input.GetKey(KeyCode.LeftShift))
{
Run();
}
else if (moveDirection == Vector3.zero)
{
Idle();
}
moveDirection *= moveSpeed;
if (isGrounded && Input.GetKeyDown(KeyCode.Space) && moveDirection == Vector3.zero )
{
Jump();
}
if (isGrounded && Input.GetKeyDown(KeyCode.Space) && Input.GetKey(KeyCode.W) && moveDirection != Vector3.zero)
{
JumpFor();
}
anim.SetBool("Jump", false);
anim.SetBool("JumpUp", false);
}
if (!isGrounded)
{
anim.SetBool("Jump", true);
}
controller.Move(moveDirection * Time.deltaTime);
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
private void Idle()
{
anim.SetFloat("Speed", 0, 0.02f, Time.deltaTime);
}
private void Walk()
{
moveSpeed = walkSpeed;
anim.SetFloat("Speed", 0.6f, 0.1f, Time.deltaTime);
}
private void Run()
{
moveSpeed = runSpeed;
anim.SetFloat("Speed", 1, 0.1f, Time.deltaTime);
}
private void Jump()
{
velocity.y = Mathf.Sqrt(jumpHeight * -2 * gravity);
}
private void JumpFor()
{
velocity = new Vector3(0, Mathf.Sqrt(jumpHeight * -2 * gravity), Mathf.Sqrt(jumpHeight * -2 * gravity));
velocity= transform.TransformDirection(velocity);
}
}
Blockquote

Related

<RigidBody> Controller

I am working on a rigidbody controller and as of right now it has some issues I cant solve. I would like my movement to be continous and if though i am checking if the player is grounded it is still jumping while in the air. Thanks in advance for any feedback its greatly appreciated!
using UnityEngine;
using UnityEngine.InputSystem;
public class Player : MonoBehaviour
{
private Rigidbody _playerRB;
private PlayerInputSystem _playerInput;
private float playerIdNumber;
private string uniquePlayName;
private float jumpForce = 10.0f;
[Header("IsGounded")]
public LayerMask whatIsGround;
public Transform groundCheck;
private float groundCheckRadius = 0.1f;
private float speed = 10.0f;
private float acceleration = 1.0f;
private float currentSpeed;
private void Awake()
{
_playerRB = GetComponent<Rigidbody>();
_playerInput = new PlayerInputSystem();
_playerInput.Player.Enable();
}
private void OnEnable()
{
_playerInput.Player.Jump.performed += Jump;
_playerInput.Player.Move.performed += Move;
}
private void OnDisable()
{
_playerInput.Player.Jump.performed -= Jump;
_playerInput.Player.Move.performed -= Move;
}
private void Jump(InputAction.CallbackContext obj)
{
if (Physics.CheckSphere(groundCheck.position, groundCheckRadius, whatIsGround))
{
_playerRB.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
}
private void Move(InputAction.CallbackContext obj)
{
float horizontal = obj.ReadValue<Vector2>().x;
float vertical = obj.ReadValue<Vector2>().y;
transform.rotation *= Quaternion.Euler(new Vector3(0, horizontal, 0));
currentSpeed += vertical * acceleration * Time.deltaTime;
currentSpeed = Mathf.Clamp(currentSpeed, 0, speed);
transform.position += transform.right * currentSpeed * Time.deltaTime;
}
}
Again thanks in advance for the help.

After adding gravity I can't run and walk faster

I'm trying to make move script but it seems impossible to me because I stared at code for like an hour I even rewrote it but same problem. It appears that after I added gravity and groundcheck things, my character cant run or even walk at set speed (he is moving very slow). Can someone please help me with it please cuz' I'm lost
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
//VARIABLES
[SerializeField] private float moveSpeed;
[SerializeField] private float walkSpeed;
[SerializeField] private float runSpeed;
private Vector3 moveDirection;
private Vector3 velocity;
[SerializeField] private bool isGrounded;
[SerializeField] private float groundCheckDistance;
[SerializeField] private LayerMask groundMask;
[SerializeField] private float gravity;
//REFERENCES
private CharacterController controller;
private void Start()
{
controller = GetComponent<CharacterController>();
}
private void Update()
{
Move();
}
private void Move()
{
isGrounded = Physics.CheckSphere(transform.position, groundCheckDistance, groundMask);
if(isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float moveZ = Input.GetAxis("Vertical");
moveDirection = new Vector3(0, 0, moveZ);
if(isGrounded)
{
if(moveDirection != Vector3.zero && !Input.GetKey(KeyCode.LeftShift))
{
Walk();
}
else if(moveDirection != Vector3.zero && Input.GetKey(KeyCode.LeftShift))
{
Run();
}
else if(moveDirection == Vector3.zero)
{
Idle();
}
moveDirection *= moveSpeed;
}
controller.Move(moveDirection * Time.deltaTime);
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
private void Idle()
{
}
private void Walk()
{
moveSpeed = walkSpeed;
}
private void Run()
{
moveSpeed = runSpeed;
}
}
I found the problem. Problem was with spawn area or call it how you want. If you'll move further the problem is no longer there.
Look at this video here: https://youtu.be/xfxgwmuPQsA

Why it says expected ',' but i don't see why to use it

I tried to make this
tutorial:https://www.youtube.com/watch?v=QGDeafTx5ug, on player
movement 2d and i get this errors: Assets\PlayerController.cs(51,37):
error CS1001: Identifier expected Assets\PlayerController.cs(51,37):
error CS1003: Syntax error, ',' expected
Assets\PlayerController.cs(54,44): error CS1001: Identifier expected
Assets\PlayerController.cs(54,44): error CS1003: Syntax error, ','
expected
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed;
public float jumpForce;
private float moveInput;
private Rigidbody2D rb;
private bool facingRight = true;
private bool isGrounded;
public Transform groundCheck;
public float checkRadius;
public LayerMask whatIsGround;
private int extraJumps;
public int extraJumpsValue;
void Start()
{
extraJumps = extraJumpsValue;
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
isGrounded = Physics2D.OverlapCircle(groundCheck.position, checkRadius, whatIsGround);
moveInput = Input.GetAxisRaw("Horizontal");
Debug.Log(moveInput);
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
if(facingRight == false && moveInput > 0){
Flip();
} else if(facingRight == true && moveInput < 0){
Flip();
}
}
void Update()
{
if(isGrounded == true){
extraJumps = extraJumpsValue;
}
if(Input.GetKeyDown(KeyCode."W") && extraJumps > 0){
rb.velocity = Vector2.up * jumpForce;
extraJumps--;
} else if(Input.GetKeyDown(KeyCode."w") && extraJumps == 0 && isGrounded == true){
rb.velocity = Vector2.up * jumpForce;
}
}
void Flip()
{
facingRight = !facingRight;
Vector3 Scaler = transform.localScale;
Scaler.x *= -1;
transform.localScale = Scaler;
}
}
The problem is with KeyCode."W"
This should be KeyCode.W
see https://docs.unity3d.com/ScriptReference/KeyCode.html

character mesh is going underneath the character controller

I'm not sure if someone is going to help me with this problem but here is my issue any ways
My player movement script was working perfectly fine before I enter this code and I'm pretty sure it's something in my script from the past that is causing my character mesh to have a huge offset downwards from my character controller yes, I have the curves set up probably here is the Ik tutorial I followed to get this issue. Thanks for your help you're a life saver for anyone who does help. Here is the video https://www.youtube.com/watch?v=MonxKdgxi2w
public class PlayerMovement : MonoBehaviour
{
#region Variables
private Vector3 Velocity;
private Vector3 PlayerMovementInput;
private Vector2 PlayerMouseInput;
private float xRot;
private CharacterController controller;
public Transform PlayerCamera;
Animator anim;
public float DefaultSpeed;
public float Speed;
public float RunSpeed;
public float Jumpforce;
public float Sensitivity;
public float Gravity = -9.81f;
private Vector3 rightFootPosition, leftFootPosition, leftFootIKPosition, rightFootIkPosition;
private Quaternion leftFootIkRotation, rightFootIKRotation;
private float lastPekvisPositionY, lastRightFootPositioonY, lastLeftFootPositionY;
[Header("Feet Grounder")]
public bool enableFeetIk = true;
[Range(0, 2)] [SerializeField] private float heightFromGroundRaycast = 1.14f;
[Range(0, 2)] [SerializeField] private float raycastDownDIstance = 1.5f;
[SerializeField] private LayerMask environmentLayer;
[SerializeField] private float pelvisOffset = 0f;
[Range(0, 1)] [SerializeField] private float pelvisUpAndDownSpeed = 0.28f;
[Range(0, 1)] [SerializeField] private float feetToIkPositionSpeed = 0.5f;
public string LeftFotAnimVariableName = "LeftFootCurve";
public string rightFootAnimVariableName = "RightFootCurve";
public bool useProIkFeature = false;
public bool showSolverDebug = true;
#endregion
# region Initialization
private void Start()
{
controller = GetComponentInChildren<CharacterController>();
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
anim = GetComponentInChildren<Animator>();
}
private void Update()
{
PlayerMovementInput = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
PlayerMouseInput = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
MovePlayer();
MoveCamera();
}
#endregion
#region PlayerMovement
private void MovePlayer()
{
Vector3 MoveVector = transform.TransformDirection(PlayerMovementInput);
if (PlayerMovementInput != Vector3.zero && !Input.GetKey(KeyCode.LeftShift))
{
Speed = DefaultSpeed;
//WALK
anim.SetFloat("Speed", 0.5f, 0.1f, Time.deltaTime);
}
else if (PlayerMovementInput != Vector3.zero && Input.GetKey(KeyCode.LeftShift))
{
Speed = RunSpeed;
//RUN
anim.SetFloat("Speed", 1, 0.1f, Time.deltaTime);
}
else if (PlayerMovementInput == Vector3.zero)
{
//IDLE
anim.SetFloat("Speed", 0, 0.1f, Time.deltaTime);
}
if (controller.isGrounded)
{
Velocity.y = -1f;
if (Input.GetKeyDown(KeyCode.Space))
{
StartCoroutine(Jump());
Velocity.y = Jumpforce;
}
}
else
{
Velocity.y -= Gravity * -2f * Time.deltaTime;
}
controller.Move(MoveVector * Speed * Time.deltaTime);
controller.Move(Velocity * Time.deltaTime);
}
private void MoveCamera()
{
xRot -= PlayerMouseInput.y * Sensitivity;
transform.Rotate(0f, PlayerMouseInput.x * Sensitivity, 0f);
PlayerCamera.transform.localRotation = Quaternion.Euler(xRot, 0f, 0f);
xRot = Mathf.Clamp(xRot, -90f, 90f);
}
private IEnumerator Jump()
{
anim.SetLayerWeight(anim.GetLayerIndex("Jump Layer"), 1);
anim.SetTrigger("Jump");
yield return new WaitForSeconds(0.983f);
anim.SetLayerWeight(anim.GetLayerIndex("Jump Layer"), 0);
}
#endregion
#region FeetGrounding
private void FixedUpdate()
{
if(enableFeetIk == false) { return; }
if( anim == null) { return; }
AdjustFeetTarget(ref rightFootPosition, HumanBodyBones.RightFoot);
AdjustFeetTarget(ref leftFootPosition, HumanBodyBones.LeftFoot);
FeetPositionSolver(rightFootPosition, ref rightFootIkPosition, ref rightFootIKRotation);
FeetPositionSolver(leftFootPosition, ref leftFootIKPosition, ref leftFootIkRotation);
}
private void OnAnimatorIK(int layerIndex)
{
if (enableFeetIk == false) { return; }
if (anim == null) { return; }
MovePelvisHeight();
anim.SetIKPositionWeight(AvatarIKGoal.RightFoot, 1);
if(useProIkFeature)
{
anim.SetIKPositionWeight(AvatarIKGoal.RightFoot, anim.GetFloat(rightFootAnimVariableName));
}
MoveFeetToIkPoint(AvatarIKGoal.RightFoot, rightFootIkPosition, rightFootIKRotation, ref lastRightFootPositioonY);
anim.SetIKPositionWeight(AvatarIKGoal.RightFoot, 1);
if (useProIkFeature)
{
anim.SetIKPositionWeight(AvatarIKGoal.LeftFoot, anim.GetFloat(LeftFotAnimVariableName));
}
MoveFeetToIkPoint(AvatarIKGoal.LeftFoot, leftFootIKPosition, leftFootIkRotation, ref lastLeftFootPositionY);
}
#endregion
#region FeetGroundingMethods
void MoveFeetToIkPoint (AvatarIKGoal foot, Vector3 positionIkHolder, Quaternion rotationIkHolder, ref float lastFootPositionY)
{
Vector3 targetIkPosition = anim.GetIKPosition(foot);
if(positionIkHolder != Vector3.zero)
{
targetIkPosition = transform.InverseTransformDirection(targetIkPosition);
positionIkHolder = transform.InverseTransformPoint(positionIkHolder);
float yVariable = Mathf.Lerp(lastFootPositionY, positionIkHolder.y, feetToIkPositionSpeed);
targetIkPosition.y += yVariable;
lastFootPositionY = yVariable;
targetIkPosition = transform.TransformPoint(targetIkPosition);
anim.SetIKRotation(foot, rotationIkHolder);
}
anim.SetIKPosition(foot, targetIkPosition);
}
private void MovePelvisHeight()
{
if(rightFootIkPosition == Vector3.zero || leftFootIKPosition == Vector3.zero || lastPekvisPositionY == 0)
{
lastPekvisPositionY = anim.bodyPosition.y;
return;
}
float lOffsetPosition = leftFootIKPosition.y = transform.position.y;
float rOffsetPosition = rightFootIkPosition.y = transform.position.y;
float totalOffset = (lOffsetPosition < rOffsetPosition) ? lOffsetPosition : rOffsetPosition;
Vector3 newPelvisPosition = anim.bodyPosition + Vector3.up * totalOffset;
newPelvisPosition.y = Mathf.Lerp(lastPekvisPositionY, newPelvisPosition.y, pelvisUpAndDownSpeed);
anim.bodyPosition = newPelvisPosition;
lastPekvisPositionY = anim.bodyPosition.y;
}
private void FeetPositionSolver(Vector3 fromSkyPosition, ref Vector3 feetIkPositon, ref Quaternion feetIkRotations)
{
RaycastHit feetOutHit;
if (showSolverDebug)
Debug.DrawLine(fromSkyPosition, fromSkyPosition + Vector3.down * (raycastDownDIstance + heightFromGroundRaycast), Color.yellow);
if(Physics.Raycast(fromSkyPosition, Vector3.down, out feetOutHit, raycastDownDIstance + heightFromGroundRaycast, environmentLayer ))
{
feetIkPositon = fromSkyPosition;
feetIkPositon.y = feetOutHit.point.y + pelvisOffset;
feetIkRotations = Quaternion.FromToRotation(Vector3.up, feetOutHit.normal) * transform.rotation;
return;
}
feetIkPositon = Vector3.zero;
}
private void AdjustFeetTarget (ref Vector3 feetPositions, HumanBodyBones foot)
{
feetPositions = anim.GetBoneTransform(foot).position;
feetPositions.y = transform.position.y + heightFromGroundRaycast;
}
#endregion
}

my player can fly for some reason, i have gravity on the rigidbody of the player

Im trying to make a 3d game with unity, but i dont know how to implement gravity, so i turned gravity for the rigidbody on. Also how could i implement jumping and wallrunning into this code?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
float playerHeight = 2f;
public float moveSpeed = 6f;
float horizontalMovement;
float verticalMovement;
Vector3 moveDirection;
Rigidbody rb;
private void Start()
{
rb = GetComponent <Rigidbody>();
rb.freezeRotation = true;
}
bool isGrounded;
private void Update()
{
isGrounded = Physics.Raycast(transform.position, Vector3.down, playerHeight / 2 + 0.01f);
print (isGrounded);
MyInput();
}
void MyInput()
{
horizontalMovement = Input.GetAxisRaw("Horizontal");
verticalMovement = Input.GetAxisRaw("Vertical");
moveDirection = transform.forward * verticalMovement + transform.right * horizontalMovement;
}
private void FixedUpdate()
{
MovePlayer();
}
void MovePlayer()
{
rb.AddForce(moveDirection.normalized * moveSpeed, ForceMode.Acceleration);
}
}

Categories

Resources