Unity 2D Platformer Jumping Issue - unity3d

I'm able to get my sprite to jump using a Axis.RawInput. This input also serves as a parameter to trigger the jumping animation when the RawInput is greater than 0. This issue with this is when you release the key, the sprite instantly falls back down. How can I perform a fixed jump when the key is pressed once or held down and then have the sprite fall at a fixed rate while also having the animations trigger?
This is what I have in my PlayerMover script now.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMover : MonoBehaviour
{
public Animator anim;
public Vector3 velocity = Vector3.zero;
public float runSpeed = 0f;
public float jumpSpeed = 0f;
private SpriteRenderer sp;
public float maxJump = 4f;
private void Awake()
{
sp = GetComponent<SpriteRenderer>();
}
void Update()
{
runSpeed = Input.GetAxisRaw("Horizontal");
jumpSpeed = Input.GetAxisRaw("Vertical");
anim.SetFloat("Jump", jumpSpeed);
anim.SetFloat("Speed", Mathf.Abs(runSpeed));
}
private void FixedUpdate()
{
Move(runSpeed, jumpSpeed*4);
}
void Move(float horizontal, float vertical)
{
if(horizontal > 0 || horizontal > 0 && vertical >0)
{
anim.SetBool("Idle", false);
sp.flipX = false;
}
else if(horizontal < 0 || horizontal <0 && vertical >0)
{
anim.SetBool("Idle", false);
sp.flipX = true;
}
else
anim.SetBool("Idle", true);
velocity.x = horizontal;
velocity.y = vertical;
transform.position += velocity * Time.fixedDeltaTime;
}
}
I've read about using something like
if(Input.GetKeyDown(GetKeyCode("Space"){
rigidbody2D.AddForce(new Vector2(0, 10), ForceMode2D.Impulse);
}
In order to move but it allows additional jumps whenever Space is pressed.

If you want to use something like:
if(Input.GetKeyDown(GetKeyCode("Space"))){
rigidbody2D.AddForce(new Vector2(0, 10), ForceMode2D.Impulse);
}
but need to stop the player from jumping when they're already in the air, just only allow them to do this when they're already on the floor. So:
if(Input.GetKeyDown(GetKeyCode("Space")) && isOnFloor()){
rigidbody2D.AddForce(new Vector2(0, 10), ForceMode2D.Impulse);
}
Where isOnFloor() is some function that checks if your character is on the floor. Depending on your game implementation this could be done several ways, but the most common one is to check if the player character is colliding with anything, and if so, if that collision object is below them. This stackexchange thread gives some code samples for how to achieve this.

In order to use this
if (Input.GetKeyDown(GetKeyCode("Space"))
{
rigidbody2D.AddForce(new Vector2(0, 10), ForceMode2D.Impulse);
}
you need to check if your player is colliding with the ground, so instead you would have a bool like bool isGrounded to check if you are touching the ground, to do this you can do it in the OnCollisionStay() to confirm it is true when you are colliding with the ground. You can use tags to check if the collider you are colliding with is the ground. Then when you jump, you need to say isGrounded = false; then it will not be true untill you land on the ground again
if (Input.GetKeyDown(GetKeyCode("Space") && isGrounded == true)
{
rigidbody2D.AddForce(new Vector2(0, 10), ForceMode2D.Impulse);
isGrounded = false;
}

Related

Input.GetKeyDown is won't work properly Unity 2D

I'm trying to make my square jump in Unity 2D when I press Space button. I have the following code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public float moveSpeed;
public float jumpSpeed;
float moveX;
Vector2 pos;
// Update is called once per frame
void Update()
{
MoveHorizontally();
Jump();
}
void MoveHorizontally(){
moveX = Input.GetAxis("Horizontal") * Time.deltaTime;
pos.x = moveX * moveSpeed;
transform.position = new Vector2(transform.position.x + pos.x,transform.position.y + pos.y);
}
void Jump(){
if (Input.GetKeyDown("space")){
GetComponent<Rigidbody2D>().AddForce(new Vector2(0,jumpSpeed * Time.deltaTime), ForceMode2D.Impulse);
Debug.Log("Jumped!");
}
}
}
When I press Space button, "Jumped!" message shows up, but my square not jumping. Any idea?
Thanks a lot.
I tried using Input.GetKey function. It works, but that function keeps making my square go upwards if i keep holding Space button.
U need to assing a value to jumpforce. and of course to the moveforce. if u dont wanna jump repeatly Just name a bool for checking if u are on ground. I use mine as" private bool = isGrounded".
and try the code below. It makes ur jump a condition as a function of touching ground.
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Ground"))
isGrounded = true;
}
and here is my code for jump.
public void PlayerJump() {
if (Input.GetButtonDown("Jump") && isGrounded) {
isGrounded = false;
myBody.AddForce(new Vector2(0f, jumpForce), ForceMode2D.Impulse);
}
}
whenever u jump it makes your bool variant false and whenever u touch ground it make ur bool true.
Make sure "Ground" must be same exactly the tag your ground has.
When you call AddForce() method you don't have to multiply with "Time.deltaTime".
What you can do is the following:
First cached your "Rigidbody2D" component from your Start() method because if you call it every frame it will affect your game performance.
private Rigidbody2D rigidbody2D;
void Start()
{
rigidbody2D = GetComponent<Rigidbody2D>();
}
Second, instead of Update() method you should call the FixedUpdate() method which is recommended when you deal with Physics
void FixedUpdate()
{
MoveHorizontally();
Jump();
}
Third, on your Jump() method as I said on top you should not multiply the jump force with Time.deltaTime, instead do the following:
public float jumpForce = 10f;
public void Jump()
{
if (Input.GetKeyDown(KeyCode.Space))
{
rigidbody2D.AddForce(Vector2.up*jumpForce);
}
}
You can adjust the jumpForce as you want.
Also Vector2.up is a shorthand for writing Vector2(0, 1)
You can read more about Vector2 here Vector2.up Unity's Documentation

Unity2D Enemy RigidBody Sticking To Player

Video example: https://imgur.com/a/d7MRjVG
Hello, my enemy object is getting stuck to my player object and dragged along. Normally, the enemy has a much lower movement speed than my player does. But when stuck to the player, the enemy essentially inherits my player's movement. I should note that this ONLY happens when the enemy is higher than my player ie has a greater Y position
Player is a rigidbody with Kinematic type
Enemy is a rigidbody with Dynamic type (I wanted this so I can push enemies aside)
Enemy is scripted not to attempt movement if too close to the player as well
The enemy has a pretty basic movement script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AI_Common : MonoBehaviour
{
public float moveSpeed; // Movement speed
public float contactDamageDistance; // offset for contact damage and when to stop walking
public ContactFilter2D movementFilter; // Filter of object types to collide with
Vector2 proposedMovement; // movement to check for collisions before executing
List<RaycastHit2D> castCollisions = new List<RaycastHit2D>(); // Collision list
float myX; // Used for incrementing movement
float myY; // Used for incrementing movement
GameObject player;
Rigidbody2D rBody;
Animator animator;
SpriteRenderer spriteRenderer;
// Start is called before the first frame update
void Start()
{
player = GameObject.FindWithTag("Player");
rBody = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
spriteRenderer = GetComponent<SpriteRenderer>();
}
// Update is called once per frame
void Update()
{
}
// Once per physics frame
private void FixedUpdate()
{
animator.SetBool("IsWalking", false);
// Attempt to move toward player if far enough away
if (Vector2.Distance(player.transform.position, rBody.transform.position) < contactDamageDistance)
return;
bool moveSuccess = false;
myX = 0;
myY = 0;
if (player.transform.position.x > rBody.position.x)
{
myX = moveSpeed * Time.fixedDeltaTime;
} else if (player.transform.position.x < rBody.position.x)
{
myX = -moveSpeed * Time.fixedDeltaTime;
}
// Flip X if needed
if(player.transform.position.x - rBody.position.x < -contactDamageDistance)
{
spriteRenderer.flipX = true;
}
else if (player.transform.position.x - rBody.position.x < contactDamageDistance)
{
spriteRenderer.flipX = false;
}
if (player.transform.position.y > rBody.position.y)
{
myY = moveSpeed * Time.fixedDeltaTime;
}
else if (player.transform.position.y < rBody.position.y)
{
myY = -moveSpeed * Time.fixedDeltaTime;
}
print($"MyX:{rBody.transform.position.x}, MyY:{rBody.transform.position.y}, PlayerX{player.transform.position.x}, playerY{player.transform.position.y}");
print($"Distance:{Vector2.Distance(player.transform.position, rBody.transform.position)}");
moveSuccess = TryMove(new Vector2(myX, myY));
// If move failed, try X only
if (!moveSuccess && myX != 0)
{
moveSuccess = TryMove(new Vector2(myX, 0));
}
// If move failed, try Y only
if (!moveSuccess && myY != 0)
{
moveSuccess = TryMove(new Vector2(0, myY));
}
animator.SetBool("IsWalking", moveSuccess);
}
private bool TryMove(Vector2 moveDirection)
{
// Check for collisions
int count = rBody.Cast(
moveDirection, // X and Y values -1 to 1
movementFilter, // Specifies which objects are considered for collision
castCollisions, // List of collisions detected by cast
moveSpeed * Time.fixedDeltaTime + contactDamageDistance); // Length of cast equal to movement plus offset
// If no collisions found, move
if (count == 0)
{
rBody.MovePosition(rBody.position + moveDirection);
return true;
}
return false;
}
}

Why is my raycast not detecting the object?

Im currently on a project where i need to detect if an object is in front of an other, so if it's the case the object can't move, because one is in front of it, and if not the object can move.
So im using here a raycast, and if the ray hit something I turn a bool to true. And in my scene, the ray hits but never turning it to true.
I precise that both of my objects as 2D colliders and my raycast is a 2DRaycast, I previously add to tick "Queries Start in colliders" in physics 2D so my ray won't detect the object where I cast it.
Please save me.
Here is my code :
float rayLength = 1f;
private bool freeze = false;
private bool moving = false;
private bool behindSomeone = false;
Rigidbody2D rb2D;
public GameObject cara_sheet;
public GameObject Monster_view;
public GameObject monster;
void Start()
{
rb2D = GetComponent<Rigidbody2D>();
}
void Update()
{
Movement();
DetectQueuePos();
}
private void Movement()
{
if(freeze || behindSomeone)
{
return;
}
if(Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("Move");
moving = true;
//transform.Translate(Vector3.up * Time.deltaTime, Space.World);
}
if(moving)
{
transform.Translate(Vector3.up * Time.deltaTime, Space.World);
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (!collision.CompareTag("Bar"))
{
return;
}
StartCoroutine(StartFreeze());
}
public void DetectQueuePos()
{
RaycastHit2D hit = Physics2D.Raycast(this.transform.position, this.transform.position + this.transform.up * rayLength, 2f);
Debug.DrawLine(this.transform.position, this.transform.position + this.transform.up * rayLength, Color.red, 2f);
if (hit.collider != null)
{
print(hit.collider.name);
}
if(hit.collider != null)
{
Debug.Log("Behind true");
//Destroy(hit.transform.gameObject);
behindSomeone = true;
}
}
IEnumerator StartFreeze()
{
yield return new WaitForSeconds(1f);
rb2D.constraints = RigidbodyConstraints2D.FreezeAll;
freeze = true;
moving = false;
cara_sheet.SetActive(true);
Monster_view.SetActive(true);
}
While Debug.DrawLine expects a start position and an end position a Physics2D.Raycast expects a start position and a direction.
You are passing in what you copied from the DrawLine
this.transform.position + this.transform.up * rayLength
which is a position, not a direction (or at least it will a completely useless one)! Your debug line and your raycast might go in completely different directions!
In addition to that you let the line have the length rayLength but in your raycasts you pass in 2f.
It should rather be
Physics2D.Raycast(transform.position, transform.up, rayLength)

Unity jumping issue, character is not jumping at all

(This is 2D project)
My character need to run left and right and jump on ground. It is my first experience with Unity and it latest available version of it, I manage to make my Character run left and right and flip when it is change direction, but it does not jump at all.
For the Character I am currently using 2 Box Collider 2Ds and Rigidbody 2D. Character has mass equal 1.
For the Ground I am currently using 2 Box Collider 2Ds. Ground is single sprite which is cover bottom part of screen.
Below is the code for jumping and grounded I am currently trying to use.
'''
{
public float maxSpeed = 10f;
public float jumpVelocity = 10f;
private bool isGrounded;
private float move = 0f;
private Rigidbody2D rb2d; //Store a reference to the Rigidbody2D component required to use 2D Physics.
private SpriteRenderer sprt_render;
// Start is called before the first frame update
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
isGrounded = true;
}
// Update is called once per frame
void Update()
{
GetInput();
}
private void GetInput()
{
move = Input.GetAxis("Horizontal");
if (transform.position.x > -6.2 && transform.position.x < 5.7)
{
rb2d.velocity = new Vector2(move * maxSpeed, rb2d.velocity.y);
}
else
{
rb2d.velocity = new Vector2(move * maxSpeed * -1, rb2d.velocity.y);
}
if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
{
Debug.Log("Jump");
rb2d.velocity = new Vector2(rb2d.velocity.x, jumpVelocity);
isGrounded = false;
//rb2d.AddForce(Vector2.up * jumpVelocity, ForceMode2D.Impulse);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
isGrounded = true;
}
}
}
'''
As you can see I try to use two different approach in connection with jump realisation using Velocity and using AddForce result is totally the same it is not jumping even first time. I check thought breakpoint it definitely go trough jumping code but nothing happened.

my character jumps too strong sometimes in unity 2d

My character's jump is working fine in a straight line collider, then I noticed that when every-time my character jumps in a curve shape collider, my jump always turns too strong abnormaly. How can I fix this? I'll provide my initial code for jump movement below.
Here is the img :
Here is jump code:
float checkgroundradius = 0.50f;
public bool isgrounded2;
public Transform grouncheckslot;
public LayerMask LM;
public float JumpPower;
public float movespeed;
Rigidbody2d RB;
void Update () {
if (isgrounded && Input.GetKeyDown(KeyCode.UpArrow))
{
isgrounded = false;
jumping = true;
myanim.SetBool("groundedanim", isgrounded);
myrb.AddForce(new Vector2(0, jumpower));
}
}
void FixedUpdate()
{
isgrounded = Physics2D.OverlapCircle(checkslot.position, groundradius, LM);
myanim.SetBool("groundedanim", isgrounded);
myanim.SetFloat("verticalspeed", myrb.velocity.y);
float move = Input.GetAxis ("Horizontal");
RB.velocity = new Vector 2 (move * movespeed, RB.velocity.y);
}
When jumping up the slope, your Physics2D.OverlapCircle intersects with the slope, thus making isgrounded=true, making you apply more force if the UpArrow is pressed.
Once solution could be to check that your character is not already moving upwards before jumping
if (isgrounded && Input.GetKeyDown(KeyCode.UpArrow) && myrb.velocity.y <= 0.0f)
this way you wont jump again if you are already heading upwards.
Maybe you could play around with a smaller groundradius and/or try moving the checkslot.position in a way that it doesnt intersect with the slope in the same manner.
For jumping people use Rigidbody2D.AddForce with Forcemode.Impulse.
Also, change
if (isgrounded && Input.GetKeyDown(KeyCode.UpArrow))
to
if (Input.GetKeyDown(KeyCode.UpArrow) && myrb.velocity.y == 0)
So you don't need to bool isgrounded
I hope it helps you :)