- Home /
How do i stop my character from jumping midair when i press W and Space togheter
I have this problem here is code of player: using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Player : MonoBehaviour {
public float moveSpeed; float xInput, yInput;
Vector2 targetPos;
Rigidbody2D rb;
public float jumpForce; bool isGrounded; public Transform groundCheck; public LayerMask groundlayer;
public Vector3 respawnPoint; private void Awake() { rb = GetComponent(); }
void Start()
{
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
if(isGrounded)
{
Jump();
}
}
}
private void FixedUpdate()
{
xInput = Input.GetAxis("Horizontal");
yInput = Input.GetAxis("Vertical");
transform.Translate(xInput * moveSpeed, yInput * moveSpeed, 0);
PlatformerMove();
isGrounded = Physics2D.OverlapCircle(groundCheck.position,0.01f,groundlayer);
}
void Jump()
{
rb.velocity = Vector2.up * jumpForce;
}
void PlatformerMove()
{
rb.velocity = new Vector2(moveSpeed * xInput, rb.velocity.y);
}
void OnTriggerEnter2D(Collider2D other)
{
if(other.tag == "Enemy")
{
transform.position = respawnPoint;
}
}
}
Answer by HellsHand · Apr 27, 2021 at 08:26 PM
transform.Translate(xInput * moveSpeed, yInput * moveSpeed, 0);
Why does my character shoot into the air when I hit W would have been a better question.
Now that I'm aware of what the question actually is, the line above is your problem. It moves the character separate from rigidbody and Input.GetAxis("Vertical") uses the w and s keys for it's input. So you are moving the character up when you hit w. If you press s your character will go through the floor. When using RigidBodies you should not be using transform.Translate` as this kind of ignores collisions.
Just need to remove the transform.Translate line from your script. You also technically don't need yInput as you are getting your jump input from your space bar already. Although I have to assume it was meant to serve some purpose. What exactly were you intending for the yInput to do?
Your answer
Follow this Question
Related Questions
Huge lag when toggling between Tile maps in one scene. 0 Answers
Problem with akward wave "Rendering",Tilemap/Grid akward wave effect 0 Answers
What is the best/easiest way to align a 2D rigidbody to specific sections of a sprite? 1 Answer
Why is there a gap between my player and the wall during wall slide? SOLVED 2 Answers
My 2D tiles have holes in them 0 Answers