I’m actually making the platformer game but somehow I want to get the player knockback after colliding with the wall and it didn’t work and make the player fly to the top of the map. How can I fix it?
here’s the code from 2 scripts:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WallKnockback : MonoBehaviour
{
public Dichuyen diChuyen;
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Player")
{
diChuyen.KBCounter = diChuyen.KBTotalTime;
if (collision.transform.position.x <= transform.position.x)
{
//Player hit the right wall
diChuyen.KnockFromRight = true;
}
if (collision.transform.position.x >= transform.position.x)
{
//Player hit the left wall
diChuyen.KnockFromRight = false;
}
}
}
}
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class Dichuyen : MonoBehaviour
{
public float walkSpeed;
public float moveInput;
public bool isGrounded;
public Rigidbody2D rb;
public LayerMask groundMask;
public PhysicsMaterial2D bounceMat, normalMat;
public bool canJump = true;
public float JumpValue = 0.0f;
public float maxJumpValue = 10.0f; // Thêm biến giới hạn nhảy
public float KBForce;
public float KBCounter;
public float KBTotalTime;
public bool KnockFromRight;
void Update()
{
moveInput = Input.GetAxisRaw("Horizontal");
if (JumpValue == 0.0f && isGrounded)
{
rb.velocity = new Vector2(moveInput * walkSpeed, rb.velocity.y);
}
isGrounded = Physics2D.OverlapBox(new Vector2(gameObject.transform.position.x, gameObject.transform.position.y - 0.5f), new Vector2(0.9f, 0.4f), 0f, groundMask);
if (JumpValue > 0)
{
rb.sharedMaterial = bounceMat;
}
else
{
rb.sharedMaterial = normalMat;
}
if (Input.GetKey("space") && isGrounded && canJump)
{
JumpValue += 0.1f;
if (JumpValue > maxJumpValue) // Kiểm tra giới hạn nhảy
{
JumpValue = maxJumpValue;
}
}
if (Input.GetKeyDown("space") && isGrounded && canJump)
{
rb.velocity = new Vector2(0.0f, rb.velocity.y);
}
if (JumpValue >= 20f && isGrounded) // Điều kiện này có vẻ không cần thiết nữa
{
float tempx = moveInput * walkSpeed;
float tempy = JumpValue;
rb.velocity = new Vector2(tempx, tempy);
Invoke("ResetJump", 0.2f);
}
if (Input.GetKeyUp("space"))
{
if (isGrounded)
{
rb.velocity = new Vector2(moveInput * walkSpeed, JumpValue);
JumpValue = 0.0f;
}
}
}
void ResetJump()
{
canJump = false;
JumpValue = 0;
}
void FixedUpdate()
{
if(KBCounter >= 0)
{
rb.velocity = new Vector2(moveInput * walkSpeed, JumpValue);
}
else
{
if(KnockFromRight == true)
{
rb.velocity = new Vector2(-KBForce, KBForce);
}
if(KnockFromRight == false)
{
rb.velocity = new Vector2(KBForce, KBForce);
}
KBCounter -= Time.deltaTime;
}
}
}
I want to get the player knockback after colliding with the wall.
Also I’m doing this for the college project.
New contributor
raindroops is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.