I am working on a mini 2D game (Unity), in which there are objects that fall from the sky, at some point I need my player to stand on them as they keep falling to the ground at a constant speed, and thus they can’t be a RigidBody.
Reference: watch the video included at the end; I was spamming jump throughout the entire video
The issue is that my player keeps bouncing on them as they fall, never being grounded.
Note: both the player and the object have a physics material with 0 bounciness, and note that I still want my player to have gravity and everything a RigidBody has.
I couldn’t find a solution on Unity Discussions, I’m hoping that maybe I could somehow find a solution here.
Thank you in advance!
Here are the scripts I attached to the player and to the object:
To my player:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class PlayerScript : MonoBehaviour
{
[SerializeField] Rigidbody2D rb;
[SerializeField] float maxVel = 15;
[SerializeField] float walk;
[SerializeField] float jump;
bool isGrounded = false;
bool isAlive = true;
float horInput = 0;
public LogicScript logic;
// Start is called before the first frame update
void Start()
{
if (rb == null) {
rb = gameObject.GetComponent<Rigidbody2D>();
}
logic = GameObject.FindGameObjectWithTag("Logic").GetComponent<LogicScript>();
}
// Update is called once per frame
void Update()
{
if (isAlive) { move(); }
}
void move()
{
horInput = Input.GetAxisRaw("Horizontal");
if (horInput != 0)
{
LimitedAddForce(horInput *= walk);
}
if (isGrounded)
{
if (Input.GetKeyDown(KeyCode.Space) )
rb.AddForce(new Vector2(0f, jump), ForceMode2D.Force);
}
}
void LimitedAddForce( float force)
{
float currentVel = rb.velocity.x;
if (currentVel + force <= maxVel && currentVel + force >= -maxVel) rb.AddForce(new Vector2(force, 0f), ForceMode2D.Force);
}
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.tag == "FloatingGround")
{
isGrounded = true;
}
else if(other.gameObject.tag == "DeathGround")
{
isAlive = false;
logic.gameOver();
Debug.Log("GAMEEEEEE OVERRRRRR!!!");
}
}
void OnCollisionExit2D(Collision2D other)
{
if (other.gameObject.tag == "FloatingGround")
{
isGrounded = false;
}
}
}
To my Object:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GroundMoveBehaviour : MonoBehaviour
{
[SerializeField] public float dropVel;
[SerializeField] public float deadZone;
// Update is called once per frame
void Update()
{
transform.position -= new Vector3(0f, dropVel * Time.deltaTime, 0f);
if(transform.position.y < deadZone)
{
Destroy(gameObject);
}
}
}
Here is a video explaining my problem, if you zoom in a little, you can see the player bouncing small bounces on the floating grounds.
NOTE: I was spamming jump throughout the entire video.
