how do I change this to move around when i jump

using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

public class PlayerBehaviour : MonoBehaviour
{
public Transform bulletSpawn;
public GameObject bullet;
public int fireRate;

public BulletManager bulletManager;

[Header(“Movement”)]
public float speed;
public bool isGrounded;

public RigidBody3D body;
public CubeBehaviour cube;
public Camera playerCam;

void start()
{

}

// Update is called once per frame
void Update()
{
_Fire();
_Move();
}

private void _Move()
{
if (isGrounded)
{
if (Input.GetAxisRaw(“Horizontal”) > 0.0f)
{
// move right
body.velocity = playerCam.transform.right * speed * Time.deltaTime;
}

if (Input.GetAxisRaw(“Horizontal”) < 0.0f)
{
// move left
body.velocity = -playerCam.transform.right * speed * Time.deltaTime;
}

if (Input.GetAxisRaw(“Vertical”) > 0.0f)
{
// move forward
body.velocity = playerCam.transform.forward * speed * Time.deltaTime;
}

if (Input.GetAxisRaw(“Vertical”) < 0.0f)
{
// move Back
body.velocity = -playerCam.transform.forward * speed * Time.deltaTime;
}

body.velocity = Vector3.Lerp(body.velocity, Vector3.zero, 0.9f);
body.velocity = new Vector3(body.velocity.x, 0.0f, body.velocity.z); // remove y

if (Input.GetAxisRaw(“Jump”) > 0.0f)
{
body.velocity = transform.up * speed * 0.1f * Time.deltaTime;
}

transform.position += body.velocity;
}
}

private void _Fire()
{
if (Input.GetAxisRaw(“Fire1”) > 0.0f)
{
// delays firing
if (Time.frameCount % fireRate == 0)
{

var tempBullet = bulletManager.GetBullet(bulletSpawn.position, bulletSpawn.forward);
tempBullet.transform.SetParent(bulletManager.gameObject.transform);
}
}
}

void FixedUpdate()
{
GroundCheck();

}

private void GroundCheck()
{
isGrounded = cube.isGrounded;
}

}

When showing code in a forum post, use the “Code <>” tool from the toolbar as it is more readable and scrollable.

You “seem” to be updating rigidbody velocity and then using that to move the transform in Update(). If you want to update RigidBody, it probably should be done in FixedUpdate() as you are changing Physics.

For a jump while moving, you want to add the up direction rather than just setting the movement to the jump direction.

+= transform.up * speed * 0.1f * Time.deltaTime

Here is a code snippet from one of our character controllers.

if (isFixedUpdate)
{
    rBody.MovePosition(currentWorldPosition);
    rBody.MoveRotation(currentWorldRotation);
}
else
{
    transform.SetPositionAndRotation(currentWorldPosition, currentWorldRotation);
}

Generally, you probably want to be changing the RigidBody OR the transform position, but not both at the same time.

1 Like

Thank you so much for the code snippet.
Works for me and for my site too, sstrong:)

1 Like