2D Character controller jump code is broken. any help would be appreciated
I am working on my first game and have made a character controller that is working for movement along the x axis but the jump code is broken and gets really buggy when i change the "jumpVelocity" float while the game is playing, changing the sprites y and making it slowly fall. in my jump command the if statement works because i tested it by putting a print() command inside but doesn't make my character jump. this is the movement script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public float RunSpeed = 4;
public float Jumpvelocity = 5;
public bool isGrounded = false;
public float flip = 0;
public Vector2 move;
public SpriteRenderer sr;
public Rigidbody2D rb;
// Start is called before the first frame update
private void Awake()
{
SpriteRenderer sr = GetComponent<SpriteRenderer>();
Rigidbody2D rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
//Input
Vector2 move = new Vector2(Input.GetAxis("Horizontal"), 0f);
//Move the player
rb.MovePosition(rb.position + move * RunSpeed * Time.deltaTime);
//jump command
Jump();
//Flipping While moveing
flipSprite();
}
void Jump(){
if(Input.GetButtonDown("Jump") && isGrounded == true){
rb.AddForce(new Vector2 (0f, Jumpvelocity), ForceMode2D.Impulse);
}
}
void flipSprite(){
flip = Input.GetAxis("Horizontal");
if(flip < 0){
if(sr != null){
sr.flipX = false;
}
}
if(flip > 0){
if(sr != null){
sr.flipX = true;
}
}
}
}
Your answer
Follow this Question
Related Questions
2D Side Scroller Help. I have a picture to show you! 0 Answers
I can't do jump in my 2D game 1 Answer
2D plaformer, Can bug me into wall 2 Answers
How do i move a cube like an actual cube?,How Can i Move a Cube? 0 Answers
Character jumps immediately after it's grounded when jump is pressed mid-air 2 Answers