- Home /
Question by
JoshomeJosh · Aug 08, 2018 at 11:15 PM ·
c#2dphysicsphysics2d
Help with 2D physics script
public float minGroundNormalY = .65f;
public float gravityModifier = 1f;
protected bool grounded;
protected Vector2 groundNormal;
protected Vector2 targetVelocity;
protected Vector2 velocity;
protected Rigidbody2D rb2d;
protected ContactFilter2D contactFilter;
protected RaycastHit2D[] hitBuffer = new RaycastHit2D[16];
protected List<RaycastHit2D> hitBufferList = new List<RaycastHit2D> (16);
protected const float minMoveDistance = 0.001f;
protected const float shellRadius = 0.01f;
void OnEnable () {
rb2d = GetComponent<Rigidbody2D> ();
}
void Start () {
contactFilter.useTriggers = false;
contactFilter.SetLayerMask (Physics2D.GetLayerCollisionMask (gameObject.layer));
contactFilter.useLayerMask = true;
}
void Update () {
targetVelocity = Vector2.zero;
ComputeVelocity ();
}
protected virtual void ComputeVelocity () {
}
void FixedUpdate () {
velocity += gravityModifier * Physics2D.gravity * Time.deltaTime;
velocity.x = targetVelocity.x;
grounded = false;
Vector2 deltaPosition = velocity * Time.deltaTime;
Vector2 moveAlongGround = new Vector2 (groundNormal.y, -groundNormal.x);
Vector2 move = moveAlongGround * deltaPosition.x;
Movement (move, false);
move = Vector2.up * deltaPosition.y;
Movement (move, true);
}
void Movement (Vector2 move, bool yMovement) {
float distance = move.magnitude;
if (distance > minMoveDistance) {
int count = rb2d.Cast (move, contactFilter, hitBuffer, distance + shellRadius);
hitBufferList.Clear ();
for (int i = 0; i < count; i++) {
hitBufferList.Add (hitBuffer[i]);
}
for (int i = 0; i < hitBufferList.Count; i++) {
Vector2 currentNormal = hitBufferList[i].normal;
if (currentNormal.y > minGroundNormalY) {
grounded = true;
if (yMovement) {
groundNormal = currentNormal;
currentNormal.x = 0;
}
}
float projection = Vector2.Dot (velocity, currentNormal);
if (projection < 0) {
velocity = velocity - projection * currentNormal;
}
float modifiedDistance = hitBufferList[i].distance - shellRadius;
distance = modifiedDistance < distance ? modifiedDistance : distance;
}
}
rb2d.position = rb2d.position + move.normalized * distance;
}
This is a code I made by following this tutorial series https://unity3d.com/learn/tutorials/topics/2d-game-creation/intro-and-session-goals?playlist=17093
I ran into a problem while testing with slopes: when I hit an upward slope while moving upward the player sort of glides upward without touching the slope and then continues to jump higher even though I haven't touched the Jump twice. Also while in this 'gliding state' I cannot jump. A similar thing can be achieved with hitting the bottom of a downward slope while going down.
I have no idea how to tackle this problem.
Comment
Answer by JoshomeJosh · Aug 09, 2018 at 04:31 PM
EDIT: I move the player by changing the target velocity in a computeVelocity method in another script