The question is answered, right answer was accepted
Realistic Jumping Help
Hi, im trying to implement a realistic movement for my game. The code i have yet looks like this: (GroundedCheck does work, so thats not the issue):
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour
{
//Movment Variables
private float moveX;
private float moveY;
public float moveSpeed;
public float jumpSpeed;
public bool isGrounded;
// Update is called once per frame
void FixedUpdate()
{
if (Input.GetKey(KeyCode.A) && isGrounded)
{
transform.Translate(new Vector2(1, 0) * -moveSpeed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.D) && isGrounded)
{
transform.Translate(new Vector2(1, 0) * moveSpeed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.Space) && isGrounded)
{
GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, jumpSpeed);
}
}
}
The problem is that i don't want the character to be able to move left or right while he is in the air, i get this to work with the grounded check also the character cant jump when already in the air. The thing is if i walk and jump the character just jumps vertically and lands exactly where he started, i want a jump in the direction where the character is walking in.
Do you know how to implement this ?
Ok i found a kind of solution, it now works like i want but i have to see how the animation look later, maybe the character slides too much
void FixedUpdate()
{
if (Input.Get$$anonymous$$ey($$anonymous$$eyCode.A) && isGrounded)
{
GetComponent<Rigidbody2D>().AddForce(new Vector2(1, 0) * -moveSpeed);
//transform.Translate(new Vector2(1, 0) * -moveSpeed * Time.deltaTime);
}
if (Input.Get$$anonymous$$ey($$anonymous$$eyCode.D) && isGrounded)
{
GetComponent<Rigidbody2D>().AddForce(new Vector2(1, 0) * moveSpeed);
// transform.Translate(new Vector2(1, 0) * moveSpeed * Time.deltaTime);
}
if (Input.Get$$anonymous$$ey($$anonymous$$eyCode.Space) && isGrounded)
{
GetComponent<Rigidbody2D>().AddForce(new Vector2(0, 1) * jumpSpeed * 10);
//GetComponent<Rigidbody2D>().velocity += jumpSpeed * Vector2.up;
}
}
I fixed everything, if anyone is interested:
public class Player : $$anonymous$$onoBehaviour
{
public float maxSpeed = 10f;
public float jumpForce;
public bool facingRight = true;
public bool isGrounded;
void Start()
{
}
void FixedUpdate()
{
if (!isGrounded)
{
return;
}
float move = Input.GetAxis("Horizontal");
GetComponent<Rigidbody2D>().velocity = new Vector2(move * maxSpeed, GetComponent<Rigidbody2D>().velocity.y);
if (move > 0 && !facingRight)
{
Flip();
}
else if (move < 0 && facingRight)
{
Flip();
}
}
void Update()
{
if (isGrounded && Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.Space))
{
GetComponent<Rigidbody2D>().AddForce(new Vector2(0, 1 * jumpForce * 20));
}
}
void Flip()
{
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}