c# Unity Jump Issue - c#

I'm new to programming in C#.
I have a sphere rigid body on a plane in unity.
I want to make this sphere jump when the spacebar is pressed and then bounce twice before coming to rest again when the key is released.
This will not always be on the plane it will sometimes be on an object and I would like the height of the bounce to reflect the distance dropped from the initial jump.
I currently have a camera facing onto the sphere from a side and have it following the ball from a set distance. The sphere can move in any direction but the camera always stays on the same side and distance from the sphere.
The issue is that my code currently says (to my knowledge) IF the spacebar is not pressed try to move the sphere's Y position down, then if the spacebar is pressed make the sphere jump and then come back down on spacebar release.
The way this code is written makes my plane jump as the ball is constantly bouncing into it when spacebar is not being pressed but if I take that part out the ball refuses to drop.
Example Code :
public class RollAdvancedScript : MonoBehaviour
{
public Transform camera;
public float posY;
void lol()
{
posY = transform.position.y;
}
void Update()
{
if (Input.GetKey(KeyCode.D))
{
Vector3 vectorToUse = camera.right;
vectorToUse.y = 0;
transform.position += vectorToUse * Time.deltaTime * 5;
}
if (Input.GetKey(KeyCode.A))
{
Vector3 vectorToUse = -camera.right;
vectorToUse.y = 0;
transform.position += vectorToUse * Time.deltaTime * 5;
}
if (Input.GetKey(KeyCode.S))
{
Vector3 vectorToUse = -camera.forward;
vectorToUse.y = 0;
transform.position += vectorToUse * Time.deltaTime * 5;
}
if (Input.GetKey(KeyCode.W))
{
Vector3 vectorToUse = camera.forward;
vectorToUse.y = 0;
transform.position += vectorToUse * Time.deltaTime * 5;
}
if (Input.GetKey(KeyCode.Space))
{
Vector3 vectorToUse = camera.up;
transform.position += vectorToUse * Time.deltaTime * 10;
}
else
{
if ( posY >= 0)
{Vector3 vectorToUse = camera.up;
transform.position -= vectorToUse * Time.deltaTime * 10;
}
else
{
Vector3 vectorToUse = camera.up;
vectorToUse.y = 0;
transform.position -= vectorToUse * Time.deltaTime * 10;
}
}
}
}
Example Image:
Please ignore the shadow as it's not working correctly just now.
TLDR; The best way to make an object jump and fall with a bounce on Keypress when moving in relation to a fixed camera position?

Are you trying to handle this in animation or in physics? Looking at the code it looks like pure controller animation, so I'd suggest that you track your jump state explicitly instead of just using the y > 0 check every update. It's a lot easier to see what's going on if you know the state of the object.
Your code makes it look like you pop up by (10 * deltaTime) when you hit space and then immediately pop down by 10 until you are below zero. Are you expecting the player to hold down space to fly, jetpack-style? Otherwise you should give an initial impulse up and then subtract from it to give a smooth fall.
Here's a very simple example. The up vector is world up (not Camera up as in your example) but if you're camera is not rolling the result would be the same.
public class DoJump : MonoBehaviour {
public float JumpSpeed = .25f;
public bool Jumping;
Vector3 jumpVec;
void Start () {
Jumping = false;
}
void Update () {
if (Jumping)
{
transform.position += jumpVec * Time.deltaTime;
jumpVec += (Vector3.down * Time.deltaTime);
//accelerate downward one unit per second per second
}
else
{
if (Input.anyKeyDown)
{
Jumping = true;
jumpVec = Vector3.up * (JumpSpeed * Time.SmoothDeltaTime);
// impulse up # jumpSpeed units per second
}
}
}
void LateUpdate()
{
if (transform.position.y < 0)
{
transform.position = new Vector3(transform.position.x, 0, transform.position.z);
Jumping = false;
}
}
}
If you're going to have uneven terrain, you should probably use physics colliders or raycast to know when to stop falling.

This is my code, hope it can help you:
public class Player : MonoBehaviour
{
public float m_gravity=10f;
void Jump()
{
if (m_ch.isGrounded) //this is the point
{
m_Gravity = 10;
if (Input.GetKeyDown(KeyCode.Space))
{
m_Gravity = -8;
}
}
else
{
m_Gravity += 10f * Time.deltaTime;
if (m_Gravity >= 10) { m_Gravity = 10; }
}
}
}

Related

Make a Tank Aim Properly

Hi I am trying to make my tank fire, but it doesn't seem to work.
My tank's gun has a firing point which is used to fire the object. FirePoint is the point from which the laser beam is instantiated. When I turn my turret though the point goes off. The point is a child of the gun turret. What do I need to do? If I haven't explained it enough, please ask and I will try my best to help.
This is my player controller script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float Speed = 0;
public float MaxSpeed;
public float TurnSpeed;
public float AccelRate = 1;
public float BrakeSpeed = 1;
public GameObject LaserBeam;
public GameObject FirePoint;
public Vector3 Offset;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
// Increase forward when up arrow pressed
if (Input.GetKey(KeyCode.UpArrow))
{
Speed = Speed + AccelRate;
}
// Move backward when down arrow pressed
if (Input.GetKey(KeyCode.DownArrow))
{
Speed = Speed - AccelRate;
}
// Turn when left arrow pressed
if (Input.GetKey(KeyCode.LeftArrow))
{
transform.Rotate(Vector3.down * Time.deltaTime * TurnSpeed);
}
// Turn when right arrow pressed
if (Input.GetKey(KeyCode.RightArrow))
{
transform.Rotate(Vector3.up * Time.deltaTime * TurnSpeed);
}
// Reset vehicle rotation
if (Input.GetKey(KeyCode.Return))
{
transform.eulerAngles = new Vector3(0, 0, 0);
}
// Press the brakes
if (Input.GetKey(KeyCode.Space) && (Speed > 0 || Speed < 0))
{
Speed = Speed - BrakeSpeed;
if (Speed < 0) { Speed = 0; }
}
//Ensure vehicle does not pass the maxspeed
if (Speed > MaxSpeed)
{
Speed = MaxSpeed;
}
//Move vehicle
transform.Translate(Vector3.right * Time.deltaTime * Speed);
if (Input.GetKey(KeyCode.UpArrow) == false && Speed > 0)
{
Speed = Speed - AccelRate;
}
//Fire
if (Input.GetKeyDown(KeyCode.F))
{
Instantiate(LaserBeam, FirePoint.transform.position + Offset, FirePoint.transform.rotation);
}
}
}
I fixed it! I simply set the offset to 0,0,0 and it worked.

Dash against slopes using physics in Unity 2D

I'm working on a 2D project in Unity.
The character controller is physics based, so I use rigidbody to move the player. Everything is working fine except when I try to apply a high speed movement to the character, like a dash.
This is how the code looks like.
I just check if the player is dashing, so I increase the Vector2 movement in a certain amount.
private void DashMovement() {
if (isDashing) {
movement.x *= dashFactor;
}
}
I'm also calculating the ground angle, so I set the movement vector to follow the ground inclination.
private void OnSlopeMovement() {
if (isGrounded && !isJumping) {
float moveDistance = Mathf.Abs(movement.x);
float horizontalOnSlope = Mathf.Cos(groundAngle * Mathf.Deg2Rad) * moveDistance * Mathf.Sign(movement.x);
float verticalOnSlope = Mathf.Sin(groundAngle * Mathf.Deg2Rad) * moveDistance;
if (horizontalOnSlope != 0)
movement.x = horizontalOnSlope;
if (isGrounded && verticalOnSlope != 0)
movement.y = verticalOnSlope;
}
SetMaxFallVelocity();
}
So I set the rigidbody velocity for making it move.
private void Move() {
movement.x *= Time.fixedDeltaTime;
if(isGrounded && !isJumping) movement.y *= Time.fixedDeltaTime;
Vector3 targetVelocity = new Vector2(movement.x, movement.y);
PlayerController.rb2d.velocity = Vector3.SmoothDamp(PlayerController.rb2d.velocity, targetVelocity, ref velocity, movementSmoothing);
}
The problem appears when I apply a speed high enough. I understand this issue is because of physics.
I think the ray that checks the ground and is used to calculate the groundAngle doesn't work fast enough to keep track of that movement, so I can not keep the player fixed on the ground.
I would like to find a solution without making the player kinematic, or stopping the dash on slopes.
This is how it looks ingame.
And this is how the rigidbody movement remain right over the ground, following the slopes angle.
EDIT:
This is how I get the ground angle:
private void GroundAngle() {
Vector2 rayOrigin = feetCollider.bounds.center;
rayOrigin.y += 0.1f;
Vector2 rayDirection = (Input.GetAxisRaw("Horizontal") == 0) ? Vector2.right : new Vector2(Input.GetAxisRaw("Horizontal"), 0);
int groundCollisions = Physics2D.RaycastNonAlloc(rayOrigin, Vector2.down, groundResults, Mathf.Infinity, groundMask);
if (groundCollisions > 0) {
groundAngle = Vector2.Angle(groundResults[0].normal, rayDirection) - 90f;
//Debug.DrawRay(rayOrigin, Vector2.down, Color.green);
if (groundAngle > 0 && !isDashing) {
rayOrigin.x += Input.GetAxisRaw("Horizontal") * .125f;
Physics2D.RaycastNonAlloc(rayOrigin, Vector2.down, groundResults, Mathf.Infinity, groundMask);
groundAngle = Vector2.Angle(groundResults[0].normal, rayDirection) - 90f;
//Debug.DrawRay(rayOrigin, Vector2.down, Color.blue);
}
}
}
Thanks to #Ruzhim for the help. I just post a first "solution" for the problem.
According to Ruzhim advises, I've used him code this way.
private void SetPositionAfterTick() {
if (isDashMovement) {
Vector2 currentPosition = new Vector2(transform.position.x, transform.position.y);
currentPosition.y = feetCollider.bounds.min.y;
Vector2 feetPosAfterTick = currentPosition + PlayerController.rb2d.velocity * Time.deltaTime;
float maxFloorCheckDist = .1f;
RaycastHit2D groundCheckAfterTick = Physics2D.Raycast(feetPosAfterTick + Vector2.up * maxFloorCheckDist, Vector2.down, maxFloorCheckDist * 5f);
if (groundCheckAfterTick) {
Vector2 wantedFeetPosAfterTick = groundCheckAfterTick.point;
if (wantedFeetPosAfterTick != feetPosAfterTick) {
//PlayerController.rb2d.transform.position = (wantedFeetPosAfterTick + new Vector2(0f, feetCollider.bounds.min.y - PlayerController.rb2d.position.y));
PlayerController.rb2d.velocity = Vector2.zero;
}
}
}
}
This is how it looks like.
This is good enough to continue polishing that mechanic. I still need to set the position in some way. The rigidbody's position calculation is not working as it
is raised right now, as the condition (wantedFeetPosAfterTick != feetPosAfterTick) is always true, so the character goes throw the floor and fall.
As you can see, I also need to control the down slopes movement, as it uses the slopes movement sometimes, and dash straight forward others.
This is how asker Rubzero implemented the below code to work for them:
private void SetPositionAfterTick() {
if (isDashMovement) {
Vector2 currentPosition = new Vector2(transform.position.x, transform.position.y);
currentPosition.y = feetCollider.bounds.min.y;
Vector2 feetPosAfterTick = currentPosition + PlayerController.rb2d.velocity * Time.deltaTime;
float maxFloorCheckDist = .1f;
RaycastHit2D groundCheckAfterTick = Physics2D.Raycast(feetPosAfterTick + Vector2.up * maxFloorCheckDist,
Vector2.down, maxFloorCheckDist * 5f);
if (groundCheckAfterTick) {
Vector2 wantedFeetPosAfterTick = groundCheckAfterTick.point;
if (wantedFeetPosAfterTick != feetPosAfterTick) {
//PlayerController.rb2d.transform.position = (wantedFeetPosAfterTick + new Vector2(0f, feetCollider.bounds.min.y -
PlayerController.rb2d.position.y));
PlayerController.rb2d.velocity = Vector2.zero;
}
}
}
}
This is how it looks like.
This is good enough to continue polishing that mechanic. I still need
to set the position in some way. The rigidbody's position calculation
is not working as it is raised right now, as the condition
(wantedFeetPosAfterTick != feetPosAfterTick) is always true, so the
character goes throw the floor and fall.
As you can see, I need to control the down slopes movement, as it uses
the slopes movement sometimes, and dash straight forward others.
I agree with AresCaelum; using physics to do slope movement is pretty much the opposite of what you want to be doing if you don't want to preserve momentum when you're done going up/down the slope. Specifically, your problem is here:
float moveDistance = Mathf.Abs(movement.x);
float horizontalOnSlope = Mathf.Cos(groundAngle * Mathf.Deg2Rad) * moveDistance * Mathf.Sign(movement.x);
float verticalOnSlope = Mathf.Sin(groundAngle * Mathf.Deg2Rad) * moveDistance;
This is a problem because the more the player moves horizontally in a frame, the more they will move vertically based on the slope of the ramp they are on. However, this assumption doesn't hold if they should only be traveling up the ramp during only part of the movement during the frame. So, you need a way to handle that situation.
One solution is to use a raycast from where the player would be then if it's above the floor, alter the vertical velocity so that it would place them at that floor's position instead.
First, determine if slope movement has occurred in a physics frame...
private bool slopeMovementOccurred = false;
void FixedUpdate() {
slopeMovementOccurred = false;
// ...
}
private void OnSlopeMovement() {
if (isGrounded && !isJumping) {
slopeMovementOccurred = true;
// ...
}
SetMaxFallVelocity();
}
... and if it has, determine where the player is going to be after the physics update. Then do a physics2d raycast from above that position (by some amount) downward (double the previous amount) to find where the player's position should be, and then change the rb2d.velocity such that it will place the player exactly at the height they should be at.
Assuming you can calculate some kind of Vector2 feetOffset that has the local position of the player's feet:
void FixedUpdate() {
// ...
StickToSlopeLanding();
}
void StickToSlopeLanding() {
if (slopeMovementOccurred) {
Vector2 curVelocity = PlayerController.rb2d.velocity;
Vector2 feetPosAfterTick = PlayerController.transform.position
+ PlayerController.feetOffset
+ curVelocity * Time.deltaTime;
float maxFloorCheckDist = 1.0f;
// determine where the player should "land" after this frame
RaycastHit2D groundCheckAfterTick = Physics2D.Raycast(
feetPosAfterTick + Vector2.up * maxFloorCheckDist,
-Vector2.up, maxFloorCheckDist * 2f);
if (groundCheckAfterTick.collider != null) {
Vector2 wantedFeetPosAfterTick = groundCheckAfterTick.point;
// if basic physics won't take them to landing position
if (wantedFeetPosAfterTick != feetPosAfterTick) {
Vector2 wantedVelocity = curVelocity
+ Vector2.up
* ((wantedFeetPosAfterTick.y - feetPosAfterTick.y)
/ Time.deltaTime);
// adjust velocity so that physics will take them to landing position
PlayerController.rb2d.velocity = wantedVelocity;
// optionally, set a flag so that next frame
// it knows the player should be grounded
}
}
}
}
Hopefully this gets you towards a solution that will work.
Note: you may need to also move the rigidbody so that it doesn't try to clip through the corner at the top of the ramp, and you can determine where to put the rigidbody using another raycast, setting the velocity from that point to be horizontal:
void StickToSlopeLanding() {
if (slopeMovementOccurred) {
Vector2 curVelocity = PlayerController.rb2d.velocity;
Vector2 feetPosAfterTick = PlayerController.transform.position
+ PlayerController.feetOffset
+ curVelocity * Time.deltaTime;
float maxFloorCheckDist = 1.0f;
// determine where the player should "land" after this frame
RaycastHit2D groundCheckAfterTick = Physics2D.Raycast(
feetPosAfterTick + Vector2.up * maxFloorCheckDist,
-Vector2.up, maxFloorCheckDist * 2f);
if (groundCheckAfterTick.collider != null) {
Vector2 wantedFeetPosAfterTick = groundCheckAfterTick.point;
// if basic physics won't take them to landing position
if (wantedFeetPosAfterTick != feetPosAfterTick) {
// look for corner of ramp+landing.
// Offsets ensure we don't raycast from inside/above it
float floorCheckOffsetHeight = 0.01f;
float floorCheckOffsetWidth = 0.5f;
RaycastHit2D rampCornerCheck = Physics2D.Raycast(
wantedFeetPosAfterTick
- floorCheckOffsetHeight * Vector2.up
- floorCheckOffsetWidth * Mathf.Sign(movement.x) * Vector2.right,
Mathf.Sign(movement.x) * Vector2.right);
if (rampCornerCheck.collider != null) {
// put feet at x=corner position
Vector2 cornerPos = Vector2(rampCornerCheck.point.x,
wantedFeetPosAfterTick.y);
PlayerController.rb2d.position = cornerPos
- PlayerController.feetOffset;
// adjust velocity so that physics will take them from corner
// to landing position
Vector2 wantedVelocity = (wantedFeetPosAfterTick - cornerPos)
/ Time.deltaTime;
PlayerController.rb2d.velocity = wantedVelocity;
// optionally, set a flag so that next frame
// it knows the player should be grounded
}
}
}
}
}

Unity 3d - player is moving constantly after touching a wall

After my player object touches the wall it sometimes starts to move and rotate on it's own. I tried to increase player object weight and it helps, but i don't think it's a good approach as tiny movement never dissapears.
Player is rigidbody with box collider attached.
isKinematic - false;
useGravity - true;
XYZ rotation is fixed and Y coordinate position is fixed.
Walls have box collider but have no rigidbody.
Ground has no collider as Y position is fixed and player object doesn't touch the ground.
Game is network based so i have photon rigidbody view component attached to player as well.
Code (C#) which moves player:
public void Update()
{
if (!photonView.IsMine || !controllable)
{
return;
}
if (shootingTimer > 0.0)
{
shootingTimer -= Time.deltaTime;
}
m_MovementInputValue = Input.GetAxis(m_MovementAxisName);
if (m_MovementInputValue == 0.0f)
{
m_MovementInputValue = joystick.Vertical;
}
m_TurnInputValue = Input.GetAxis(m_TurnAxisName);
if (m_TurnInputValue == 0.0f)
{
m_TurnInputValue = joystick.Horizontal;
}
Vector3 vector = new Vector3(
m_TurnInputValue,
rigidbody.velocity.y,
m_MovementInputValue
);
MovementVector = Quaternion.AngleAxis(60, Vector3.up) * vector;
EngineAudio();
}
public void FixedUpdate()
{
if (!photonView.IsMine || !controllable)
{
return;
}
Move();
Turn();
}
private void Move()
{
// Adjust the position of the tank based on the player's input.
// Vector3 movement = transform.forward * m_MovementInputValue * m_Speed * Time.deltaTime;
// rigidbody.MovePosition(rigidbody.position + movement);
Vector3 movement = MovementVector * m_Speed * Time.deltaTime;
rigidbody.MovePosition(rigidbody.position + movement);
}
private void Turn()
{
// Adjust the rotation of the tank based on the player's input.
// float turn = m_TurnInputValue * m_TurnSpeed * Time.deltaTime;
// Quaternion turnRotation = Quaternion.Euler(0f, turn, 0f);
// rigidbody.MoveRotation(rigidbody.rotation * turnRotation);
if (m_TurnInputValue != 0.0f || m_MovementInputValue != 0.0f)
{
rigidbody.rotation = Quaternion.LookRotation(MovementVector);
}
}
Check to make sure the component (such as a rigidbody) is attached to the right object (gameobject - parent vs. child objects). Also, the fact that it is constantly rotating is curious... it makes me think it has something to do with the Time.DeltaTime, but I see that's only being applied to your Vector3 movement, and not in your rotation function... Just curious, what happens when you remove the Time.DeltaTime part from your movement Vector3?

Camera Behaviour

This camera script is intended to rotate and look at the player while it is moving and snapping to the player slowly while it isn't. (Player passes over a Vector3 beforeMoving before it is starting movement). My issue is I want to "feed" the deltaPosition slowly so it isn't a sudden snap but rather a slow and smooth transition, also stop adding if arrived.
private void LateUpdate()
{
if (player.isMoving)
{
desiredPosition = player.beforeMoving + offset;
}
else
{
Vector3 deltaPosition = player.transform.position - player.beforeMoving;
desiredPosition += deltaPosition * Time.deltaTime;
}
Quaternion camTurnAngle =
Quaternion.AngleAxis(input * rotationSpeed, Vector3.up);
desiredPosition = camTurnAngle * desiredPosition;
transform.position = Vector3.Slerp(transform.position, desiredPosition, smoothFactor);
transform.LookAt(player.transform);
}
Edit: I thought I would share the final code.
private void LateUpdate()
{
Quaternion rotation = Quaternion.Euler(GetDegree(), input.x * rotationSpeed, 0f);
if (player.isMoving)
{
desiredPosition = player.beforeMoving + offset;
CalculatePanTime();
}
else if (!player.isMoving)
{
desiredPosition = player.transform.position + offset;
}
transform.position = Vector3.Slerp(transform.position, rotation * desiredPosition, GetSpeed());
transform.LookAt(player.transform);
}
private void CalculatePanTime()
{
stoppedTime = Time.time;
playerDelta = Vector3.Distance(player.transform.position, player.beforeMoving);
timeToPan = (playerDelta / snappingSpeed) * Time.deltaTime;
}
private float GetSpeed()
{
if (Time.time < stoppedTime + timeToPan)
{
controlsDisabled = true; return snappingSpeed;
}
else
{
controlsDisabled = false; return smoothSpeed;
}
}
You are telling us what you want the code to do, that is good. You are also posting the code you implemented to achieve your goal, that is also good. Can you also tell us what is not working as you want it to work as a result of that code?
From what I understand it is the "Vector3 deltaPosition = player.transform.position - player.beforeMoving;
desiredPosition += deltaPosition * Time.deltaTime; " that is not behaving as you expect it to
maybe try something like this:
private void LateUpdate()
{
// snap the rotation center slowly to the player's position if not moving, or player's position before he started moving
desiredPosition = Vector3.Lerp(desiredPosition, player.beforeMoving, 0.1f);
// rotate around rotation center
Quaternion camTurnAngle = Quaternion.AngleAxis(rotationSpeed * Time.time, Vector3.up);
desiredPosition += camTurnAngle * offset;
// set the position to rotate around rotation center, and look towards player
transform.position = Vector3.Lerp(transform.position, desiredPosition, smoothFactor);
transform.LookAt(player.transform);
}
the problem with your code is that you are overshooting. If you want to implement something that decides how fast the camera snaps, or how much time it should take to snap, try introducing a float player.timeStopMoving = Time.time that you can use to correctly compute the position correction while he is not moving.
if(player.isMoving)
{
desiredPosition = player.beforeMoving;
}
else
{
const float timeNeededToSnap = 2f;
// or float timeNeededToSnap = (player.transform.position - player.beforeMoving).magnitude; // (which you could compute only once in player script, when he stops moving, and then reuse the value instead of performing a ".magnitude" every frame)
if(Time.time < player.timeStopMoving + timeNeededToSnap)
{
desiredPosition = Vector3.Lerp(desiredPosition, player.transform.position, (Time.time - player.timeStopMoving) / timeNeededToSnap);
}
else
{
// an other problem here is: if the player starts moving AGAIN before your desiredPosition got the value, do you want desired position to glich to the new player.beforeMoving?...
desiredPosition = player.transform.position;
}
}
EDIT:
To make he lerp less linear, you can use:
if(Time.time < player.timeStopMoving + timeNeededToSnap)
{
var t = Mathf.Cos(Maths.Pi * 0.5f * (Time.time - player.timeStopMoving) / timeNeededToSnap); // as timeDelta/totalTime goes from 0->1, multiply it by Pi/2 and the Cos will also go from 0->1 but with a smoothing speed
desiredPosition = Vector3.Lerp(desiredPosition, player.transform.position, t);
}

Moving player horizontally while in lerp jump Unity C#

The code I have allows a player object to move around the circumference of a circle and then "jump" to the center of that circle.
What I am trying to do is allow the player to continue their movement around the circle while jumping so that the player can alter their position while jumping.
This is the full code I have so far.
using UnityEngine;
using System.Collections;
public class Movement : MonoBehaviour
{
//editable property if made public
public float playerSpeed = 20f;//This is how fast the player moves
float playerAngle = 0; //This is the players movement variable
float radius = 4f; //This is the radius of how big the circle is (Circumference track 2piRadius
float startTime; //This is the time the game started
float gameTime; //This will be player points BASE THIS OFF OF HOW LONG THE GAMES RUNNING
float playerRadius = .5f; //CHANGE TO THE PLAYER OBJECT VARIABLE, is how offset the player will be from the lvlradius.
private bool jumping = false; //This effects movement during the game
private Vector3 playerPosition; //This is the playerPosition in the game
void Start()
{
//Called at the start of the game
}
void Update()
{
if (jumping)
{
return;
}
else if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.RightArrow))
{
circularMove();
}
else if (Input.GetKeyDown(KeyCode.Space))
{
StartCoroutine(jumpPlayer());
}
}
void FixedUpdate()
{
//Called before performing physics calculations
}
void circularMove()
{
//player variables
//The angle the player is at is equal to the speed of the player divided by radius times time in the game and the addition of the left right keys
playerAngle += Input.GetAxis("Horizontal") * Time.deltaTime * (playerSpeed / radius);
//This is the movement on the x axis
float x = Mathf.Cos(playerAngle) * (radius - playerRadius);
//this is the movement on the y axis
float y = Mathf.Sin(playerAngle) * (radius - playerRadius);
//the player does not move forward at this time THIS WILL BE HOW TO MOVE THE PLAYER
float z = 0;
//move the player in the direction that they clicked but add the original coordinates to the players location
transform.position = new Vector3(x, y, z);
//Move the player;
playerPosition = transform.position;
}
private IEnumerator jumpPlayer()
{
Vector3 playerEndPos = new Vector3(0f, 0f, 0f);
Vector3 playerStartPos = playerPosition;
float i = 0.0f;
float rate = .1f / Time.deltaTime;
jumping = true;
while (i< 1.0)
{
i += Time.deltaTime * rate;
transform.position = Vector3.Lerp(playerStartPos, playerEndPos, i);
yield return null;
}
transform.position = playerEndPos;
i = 0.0f;
while (i < 1.0)
{
i += Time.deltaTime * rate;
transform.position = Vector3.Lerp(playerEndPos, playerStartPos, i);
yield return null;
}
transform.position = playerStartPos;
jumping = false;
yield break;
}
}
With the current Update your idea will never be possible, because if a user is jumping, you are ignoring the input of the left and right key.
By shifting the if(jumping) to the actual jump statement you could probably bypass this.
void Update()
{
if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.RightArrow))
{
circularMove();
}
else if (Input.GetKeyDown(KeyCode.Space))
{
if (!jumping)
StartCoroutine(jumpPlayer());
}
}

Categories