- Home /
Giving gravity to a game object and have it collide with the ground below it without using Rigidbodies
The idea is that I want to apply gravity to the Player using the transform.Translate function and when a raycast that shoots from the bottom of the Player's bounding box hits the ground the gravity's value will change to the distance between where the raycast hits the ground and the origin of the raycast.
However I'm having a bit of trouble with getting it to work properly. The Player seems to fall through the ground before it stops rather than resting plumb with the ground. Here is the code that I have written for it:
public class Player : MonoBehaviour
{
private BoxCollider2D _col2D;
private Vector2 botRight;
public LayerMask _collisionMask;
private float rayLength;
public float gravity = -0.1f;
public Vector3 velocity;
// Start is called before the first frame update
void Start()
{
_col2D = GetComponent<BoxCollider2D>();
}
// Update is called once per frame
void Update()
{
velocity.y += gravity * Time.deltaTime;
botRight = new Vector2(_col2D.bounds.max.x,_col2D.bounds.min.y);
RaycastHit2D hit = Physics2D.Raycast(botRight,Vector2.down,rayLength,_collisionMask);
Debug.DrawRay(botRight,Vector2.down * rayLength,Color.red);
if(hit){
rayLength = hit.distance;
velocity.y = - hit.distance;
Debug.Log("Hit.distance is: " + hit.distance);
}
transform.Translate(velocity);
}
}
Here's a video of what occurs when I run the project: https://www.youtube.com/watch?v=6KEQ3FnFDww
Could someone help me with trying to get the Player to fall on top of the ground properly? Thanks
Your answer
![](https://koobas.hobune.stream/wayback/20220613032714im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Raycast Does not Detect Collider 2 Answers
Flipping object with Box Collider while on an angled collider 0 Answers
why Raycast2D doesn't work properly? 0 Answers
Issue with Raycasts in Unity 2D 2 Answers
Unity Raycast2D ignored instantiated Prefab object 0 Answers