I’m doing some tests trying to avoid the use of raycasts. I’m trying just to let a box fall (kinematic body), and make it stand on another big box (floor). You can think it as a player colliding with floor. I achieved success using raycast for this but I wanted to try doing it with own unity collision system avoiding any player sttutering or sinking.
The code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
Vector2 _velocity = Vector2.zero;
public Vector2 _acceleration = new Vector2(0, -10);
Rigidbody2D _rb;
void Awake()
{
_rb = GetComponent<Rigidbody2D>();
}
// Use this for initialization
// Update is called once per frame
void FixedUpdate ()
{
Debug.Log("Moved");
_velocity += _acceleration * Time.deltaTime;
_rb.position=_rb.position + _velocity * Time.deltaTime;
}
void OnTriggerEnter2D(Collider2D col)
{
Debug.Log("trigger Enter");
Vector3 pos = _rb.position;
float maxY=col.GetComponent<Collider2D>().bounds.max.y;
Vector3 newPos = new Vector3(0, maxY,0);
_rb.position=newPos;
_velocity.y = 0;
}
}
Really simple code. The problem is:
-
If I use OnTriggerStay instead of OnTriggerEnter it works correctly but this is too cpu intensive.
-
If I use OnTriggerEnter, it seems that when I move the box over the floor they are still sharing one edge (at y=0) and though, they are still colliding colliding and falling box (player) starts to sink next frame because no more OnTriggerEnter will be called.
-
If I use OnTriggerEnter with for example a delta of 0.1f, it stutters (you have to really get close to notice it because I use 1 pixel == 1 unity pixel but it happens).
So, Is there any possibility to accomplish total balance of the player on the floor without using OnTriggerStay?
Note: Player has its pivot at the bottom.
Note: The floor top is set at 0.
Thanks in advance.