design – What is a manageable way to handle physics collisions for many types in C#?

I have a function that takes two objects and uses a switch on the enum types of the objects.

The problem I have is this is getting painful to manage as I add more and more primitive types and i need two case statements for each variation.

My switch is setup like this:

switch (obj1.Type, obj2.Type){
    case (GeometryType.Polygon, GeometryType.Polygon):
       return GetIntersectingPoints(obj1 as Polygon, obj2 as Polygon, contactPoints);
   case (GeometryType.Polygon, GeometryType.Circle):
      return GetIntersectingPoints(obj1 as Polygon, obj2 as Circle, contactPoints);
   case (GeometryType.Polygon, GeometryType.Arc):
      return GetIntersectingPoints(obj1 as Polygon, obj2 as Arc, contactPoints);
   case (GeometryType.Polygon, GeometryType.Line2D):
      return GetIntersectingPoints(obj1 as Polygon, obj2 as LineSegment, contactPoints);
   case (GeometryType.Polygon, GeometryType.BiArc):
      return GetIntersectingPoints(obj1 as Polygon, obj2 as BiArc, contactPoints);

    //same as second case but the other way around
   case (GeometryType.Circle, GeometryType.Polygon):
     return GetIntersectingPoints(obj2 as Polygon, obj1 as Circle, contactPoints);
    // and so on

Since the objects provided could either be A and B or B and A every time i add a new primitive type this switch becomes painfully longer and longer and its just a huge hassle to deal with.

Is there a smarter design pattern to do this that requires less management? How do people usually handle this situation in physics collision design ?

cryptography – What are the different ways of finding collisions in SHA?

I have been researching SHA and its applications. While many SHA algorithms exist they can be categorized into three groups SHA, SHA-1, SHA-2, and SHA-3. SHA through SHA-2 is based on the Merkle–Damgård construction which I presume has a certain approach to finding collisions, like length extension attacks. However, SHA-3 is based on a different structure, based on Keccak. This makes it invulnerable to length extension attacks because of the capacity variable.

SHA-1 for example has been cracked by Google and the CWI Institute, where two visually different PDFs had the same hash.

So this leaves me wondering what the different attack strategies are for SHA-1, SHA-2, and SHA-3.

labeling – Improving label collisions for Tree/Graph?

Historically, MMA has never handled label collisions well, but recently they added some improvements here via things like Callout. I want to fix ImageSize but still see as much as possible (by tooltipping a minimally set of vertices).

Here’s two examples of the problem:

enter image description here

enter image description here

Unfortunately, Callout doesn’t work in Graphics but it does on ListPlot type functions… any ideas?

unity – How to trigger OnMouseX events on Kinematic Rigidbody2D object with a different collider than one used for collisions?

I have a use-case where I have an object with a Collider2D and a Kinematic RigidBody2D in order to do Kinematic movement.

However, I also want to be able to select/hover that object with a OnMouseDown/OnMouseEnter/etc, using a larger collider than I would use for the kinematic movement.

My current attempt at a solution is to have Physics-related scripts/rigidbody2d/collider2d as the top level game object, and to have a child object, with a larger collider2D which will respond to OnMouseX events.

enter image description here

enter image description here enter image description here

In order to ignore OnMouseX events on the parent, I’m putting it into its own user_ignore_raycasts layer (I need it as its own layer for the layer collision matrix). I’m also putting the child in its own user_use_raycasts layer.

I’m passing that into a script that sets MainCamera’s event mask:
enter image description here

using UnityEngine;
public class CameraEventMasker : MonoBehaviour
    private LayerMask cameraEventMask;
    // Start is called before the first frame update
    void Awake()
        GetComponent<Camera>().eventMask = cameraEventMask;

What I notice is that OnMouseX events on the child will work IF the RigidBody2D on the parent is deleted…however, if the RigidBody2D is there, I won’t receive any events. Anyone know why this is the case, and if there are other workarounds or solutions?

c++ – Problems with collisions (using vector of instances)

I wrote a for loop to check every instance of the class Wall, only the the last instance in the vector properly works


 void reactTo(Player* other)
     if (react)
         if ((other->back<front && other->front > front) && (other->y > foot && other->y < head))
             other->goAhead(0) = false;
             other->goAhead(0) = true;

             if ((other->front >= back) && other->back < back && other->y > foot && other->y < head)
                 other->goAhead(1) = false;
                 other->goAhead(1) = true;
     if (other->foot <= head && other->head >= head && other->x > back && other->x < front)
         other->goAhead(2) = false;
         other->goAhead(2) = true;
         if ((other->head >= foot) && other->foot < foot && foot && other->x > back && other->x < front)
             other->goAhead(3) = false;
             other->goAhead(3) = true;
     if (other->front > back && other->back <= front && other->head < head && other->foot > foot)
         R = 0;
         R = 1;



int main()
   setWindowSize(1500, 600);

   makeSequenceWall();//push back 5 Wall constructor

   Player p(300, 300,30,30,0.5,0,1,0);
   while (!slShouldClose())
       p.render();//render the player

       for (int i = 0; i != 5; i++)//check the collision

       for (itr = wallSeq.begin(); itr != wallSeq.end();itr++)//render the wall
   return 0;


unity – How to mimic Wipeout wall collisions?

This is how are wall collisions in the original game:

enter image description here

Right now I can pass through walls if I insist a bit:

enter image description here

Also, I can slip through hover point, and when pushed back, ship makes a jump:

enter image description here

For wall collision, I’ve tried to give a clamped impulse force using wall normal but it isn’t right at all:

enter image description here


How can I mimic the wall collision like in the original game?

So basically, the ship:

  • cannot quit the track
  • gets stopped by the wall, obviously
  • its velocity is reduced somewhat but player can recover quickly


You can see how are a few collisions in the original game at about 32:00 in this longplay:

The track has a mesh collider that is exactly the shape of the track.

The ship has a Rigidbody with a mass/drag of 1 and angular drag of 5 and hovering point at front uses the formula in Wikipedia of a damped harmonic oscillator.

In short, I have done hovering but kept a rigid body, Unity handles the gravity, drag and collisions for the time being, i.e. everything else.

Here’s the code I am using:

using System;
using System.Text;
using UnityEngine;
using Wipeout.Components;
using Wipeout.Extensions;
using Wipeout.Formats;

namespace Scenes
    public partial class ShipController : MonoBehaviour
        private Rigidbody Body;

        private TrackController Controller;

        public float TorqueSpeed = 1.0f;

        public float RotationSpeed = 1.0f;

        public float RotationMaxDistance = 2.0f;

        private void Start()

        private void Update()
            if (Input.GetKey(ThrustInputPush))
                ThrustValue += ThrustAccelerateRate;
                ThrustInput =  ShipThrustInput.Accelerating;
                if (Input.GetKey(ThrustInputPull))
                    ThrustValue -= ThrustDecelerateRate * ThrustValueStopFactor;
                    ThrustInput =  ShipThrustInput.Decelerating;
                    ThrustValue -= ThrustDecelerateRate;
                    ThrustInput =  ShipThrustInput.None;

            ThrustValue = Mathf.Clamp01(ThrustValue);

            ThrustForce = ThrustCurve.Evaluate(ThrustValue) * ThrustMaxSpeed;

            if (Input.GetKeyDown(KeyCode.Escape))

            if (Input.GetKeyDown(KeyCode.Keypad0))
                Time.timeScale = 0.0f;

            if (Input.GetKeyDown(KeyCode.Keypad1))
                Time.timeScale = 1.0f;

            if (Input.GetKeyDown(KeyCode.KeypadDivide))
                Time.timeScale /= 2.0f;

            if (Input.GetKeyDown(KeyCode.KeypadMultiply))
                Time.timeScale *= 2.0f;

        private void FixedUpdate()
            Body.centerOfMass = HoverCenterOfMass;

            var bodyTrans = Body.transform;
            var bodyPoint = bodyTrans.TransformPoint(HoverPoint);

            var ray     = new Ray(bodyPoint, bodyTrans.TransformDirection(Vector3.down));
            var raycast = Physics.Raycast(ray, out var hit);
            var hover   = raycast && hit.distance <= HoverHeight;

            if (hover)
                Debug.DrawLine(ray.origin, hit.point,;

                var k = HoverSpring;
                var x = Mathf.Pow((HoverHeight - hit.distance) / HoverHeight, 2);
                var c = Springs.QFactorToDamping(HoverQFactor, HoverSpring, Body.mass);
                var v = bodyTrans.InverseTransformDirection(Body.GetPointVelocity(bodyPoint)).y;
                var f = k * x - c * v;
                var g = Mathf.Sign(f) * Mathf.Min(Mathf.Abs(f), HoverMaximumForce);
                var h = bodyTrans.TransformDirection(Vector3.up) * g;

            HoverState = hover ? ShipHoverState.Ground : ShipHoverState.Aerial;

            Quaternion rot;

            if (TrackRaycast(bodyTrans, Vector3.down, out var raycastHit, out var face, RotationMaxDistance) && face.HasFlag(TrackFaceFlags.Floor))
                // align to face normal
                var nv = raycastHit.transform.TransformDirection(face.Normal);
                var tv = bodyTrans.forward;
                Vector3.OrthoNormalize(ref nv, ref tv);
                rot = Quaternion.LookRotation(tv, nv);
                // align to world up
                rot = Quaternion.LookRotation(bodyTrans.forward);

            var slerp = Quaternion.Slerp(Body.rotation, rot, Time.fixedDeltaTime * RotationSpeed);


            #region Movement

            var velocity = GetShipVelocity();

            if (Mathf.Abs(velocity.z) < ThrustMaxSpeed && ThrustInput != ShipThrustInput.None)
                var factor = HoverState == ShipHoverState.Aerial ? ThrustAerialFactor : 1.0f;
                var force  = Mathf.Min(ThrustMaxSpeed * factor, ThrustForce * factor);
                Body.AddRelativeForce(Vector3.forward * force);

            var torque = Input.GetAxis("Horizontal");

            Body.AddRelativeTorque(Vector3.up * (torque * TorqueSpeed));


            // prevent lateral drift
            var tx = bodyTrans.TransformDirection(Vector3.right);
            var rx = bodyTrans.InverseTransformDirection(Body.velocity).x;
            Body.AddForce(tx * (-Time.fixedDeltaTime * rx * HoverSideDriftForce));

        private void LateUpdate()
            var cam = Camera;
            if (cam == null)

            var ct = cam.transform;

            ct.position = Vector3.SmoothDamp(ct.position, Body.transform.TransformPoint(CameraPosition), ref CameraVelocity, CameraSmoothTime);
            ct.rotation = Quaternion.LookRotation(Body.transform.forward);

        private bool TrackRaycast(Transform source, Vector3 direction, out RaycastHit hit, out TrackFace face, float maxDistance)
            face = default;

            if (!Physics.Raycast(source.position, direction, out hit, maxDistance))
                return false;

            if (hit.transform != Controller.transform)
                return false;

            face = Controller.Track.Faces(hit.triangleIndex / 2);

            return true;

        private void ResetShip()
            var tf = Controller.Track.Faces(49);
            var tt = Controller.transform;

            var position = tt.TransformPoint(tf.Position) + tt.TransformDirection(tf.Normal) * 5.0f;

            Body.transform.position = position;

            var forward = tt.TransformDirection((tf.Section.Next.Position - tf.Section.Position).normalized);
            var upwards = tt.TransformDirection(tf.Normal);

            Body.transform.rotation = Quaternion.LookRotation(forward, upwards);

            Body.velocity        =;
            Body.angularVelocity =;

            ThrustValue = 0.0f; // stop thrusting

    public partial class ShipController
        public enum ShipHoverState

        public enum ShipThrustInput

        private readonly StringBuilder Builder = new StringBuilder();

        private void Reset()
            Body = GetComponent<Rigidbody>();

            Body.drag                   = 1.0f;
            Body.angularDrag            = 5.0f;
            Body.interpolation          = RigidbodyInterpolation.Extrapolate;
            Body.collisionDetectionMode = CollisionDetectionMode.Continuous;
            Body.constraints            = RigidbodyConstraints.None;

            Controller = FindObjectOfType<TrackController>();

            Camera = FindObjectOfType<Camera>();

        private void OnGUI()
            var scale = Screen.dpi / 96.0f;
            GUIUtility.ScaleAroundPivot( * scale,;
            Builder.AppendLine($"Time: {TimeSpan.FromSeconds(Application.isPlaying ? Time.time : default):g}");
            Builder.AppendLine($"Time scale: {Time.timeScale}");
            Builder.AppendLine($"Hover state: {HoverState.ToString(color: HoverState == ShipHoverState.Aerial ? :}");
            Builder.AppendLine($"Velocity: {GetShipVelocity().z:F}");
            var text = Builder.ToString().Trim('n', 'r');
            GUILayout.Box(text, Styles.Box);

        private void OnDrawGizmos()
            Gizmos.color =;
            Gizmos.DrawSphere(transform.TransformPoint(HoverPoint), 0.05f);

            Gizmos.DrawSphere(transform.TransformPoint(HoverCenterOfMass), 0.05f);

        public Vector3 GetShipVelocity()
            return Body.transform.InverseTransformDirection(Body.velocity);

        private static class Styles
            public static GUIStyle Box { get; } = new GUIStyle( { alignment = TextAnchor.UpperLeft };

    public partial class ShipController
        #region Hovering

        public float HoverHeight = 0.3f;

        public Vector3 HoverCenterOfMass = new Vector3(0.0f, -0.5f, 0.0f);

        public float HoverSpring = 250.0f;

        public float HoverQFactor = 2.0f;

        public float HoverMaximumForce = 250.0f;

        public float HoverSideDriftForce = 100.0f;

        public Vector3 HoverPoint = new Vector3(0.0f, -0.25f, 0.75f); // at ship nose tip

        public ShipHoverState HoverState;


        #region Thrust

        (Tooltip("Thrust acceleration curve."))
        public AnimationCurve ThrustCurve = new AnimationCurve(new Keyframe(0.0f, 0.0f, 2.0f, 2.0f), new Keyframe(1.0f, 1.0f, 0.0f, 0.0f));

        (Tooltip("Actual thrust force."))
        public float ThrustForce;

        (Tooltip("Maximum thrust speed."))
        public float ThrustMaxSpeed = 25.0f;

        (Tooltip("State of thrust input."))
        public ShipThrustInput ThrustInput;

        (Tooltip("The key for accelerating."))
        public KeyCode ThrustInputPush = KeyCode.UpArrow;

        (Tooltip("The key for decelerating."))
        public KeyCode ThrustInputPull = KeyCode.DownArrow;

        (Tooltip("How strong thrust can be on air."))
        public float ThrustAerialFactor = 0.125f;

        (Tooltip("Actual thrust value."))
        public float ThrustValue;

        public float ThrustAccelerateRate = 0.005f;

        public float ThrustDecelerateRate = 0.0025f;

        (Tooltip("How strong thrust value changes while braking."))
        public float ThrustValueStopFactor = 32.0f;


        #region Camera

        public Camera Camera;

        public Vector3 CameraPosition = new Vector3(0.0f, 1.5f, -5.0f);

        public float CameraSmoothTime = 0.125f;

        public Vector3 CameraVelocity;


The Q factor I used of 2 is equal to a damping of 7.9 for a spring of 250.

And here are the actual properties:

enter image description here

platformer – Pygame Platform & Player collisions

I am trying to create a platform game where a player jumps between platforms horizontally (using a projectile curve). Currently, I have a class that blits platforms and a background, as well as the player. However, I cannot get it to detect when a platform and the player collide. I have used actual images and then done self.rect = self.image.get_rect() for both the platform and the character. My question is have I done something wrong with my theory or have I just not coded it correctly.

rigidbody – Momentum-wise accurate player controls in Unity regarding collisions

rigidbody – Momentum-wise accurate player controls in Unity regarding collisions – Game Development Stack Exchange

entity component system – How to detect collisions in Unity ECS?

You can do this with a JobComponentSystem which schedules a job implementing ICollisionEventsJob*. You also need to set that job as a dependency for the EndSimulationEntityCommandBufferSystem using AddJobHandleForProducer. Here is an example script:

using Unity.Burst;
using Unity.Entities;
using Unity.Jobs;
using Unity.Physics;
using Unity.Physics.Systems;
using UnityEngine;

public class CollisionSystem : JobComponentSystem {

    private struct CollisionJob : ICollisionEventsJob {
        public void Execute(CollisionEvent collisionEvent) {
            Debug.Log($"Collision between entities { collisionEvent.EntityA.Index } and { collisionEvent.EntityB.Index }");

    private BuildPhysicsWorld buildPhysicsWorldSystem;
    private StepPhysicsWorld stepPhysicsWorldSystem;
    private EndSimulationEntityCommandBufferSystem commandBufferSystem;

    protected override void OnCreate() {
        buildPhysicsWorldSystem = World.GetExistingSystem<BuildPhysicsWorld>();
        stepPhysicsWorldSystem = World.GetExistingSystem<StepPhysicsWorld>();
        commandBufferSystem = World.GetExistingSystem<EndSimulationEntityCommandBufferSystem>();

    protected override JobHandle OnUpdate(JobHandle inputDeps) {    
        JobHandle jobHandle = new CollisionJob().Schedule(
            ref buildPhysicsWorldSystem.PhysicsWorld, 
        return jobHandle;    

Note that the physics system will usually generate multiple collision events on what appears to be just a single collision to the player. There is some debate about whether that’s a bug or a feature.

* Yes, I am aware how useless this documentation article is right now. Hopefully it will get more useful in future versions of the documentation.

c# – How to do topdown collisions properly?

I’m trying to achieve grid/tile based collisions like (A link to the past) here is an article showing it off (sliding off the corners and such) I’m currently using this type of collision test It’s based on deepnights implementation of tile collisions but modified a bit, you have your positionX/Y in the world, TileX/Y is the tile equivalent (my tiles are 16/16), and XRatio/YRatio which is how much into a tile are you so whenever you’re moving into a tile you can clip into it for a certain amount which is nice for making it seem like the player is above stuff and to have more control over it but I’m really looking for someone to show me how I’d go about implementing this kind of collision testing properly I’ve been having so many problems (Getting stuck in 1 pixel in the corners, Snapping on one side while the other u don’t, getting stuck in general/not being able to move when holding diagonals etc) If you could “Explain Like I’m 5” that’d be awesome I’d really like to learn this stuff properly

TL:DR – Trying to achieve Topdown collision detection like a link to the past/stardew (Slide off corners of tiles) and being bug free (Not getting stuck / snapping)

DreamProxies - Cheapest USA Elite Private Proxies 100 Cheapest USA Private Proxies Buy 200 Cheap USA Private Proxies 400 Best Private Proxies Cheap 1000 USA Private Proxies 2000 USA Private Proxies 5000 Cheap USA Private Proxies - Buy Cheap Private Proxies Buy 50 Private Proxies Buy 100 Private Proxies Buy 200 Private Proxies Buy 500 Private Proxies Buy 1000 Private Proxies Buy 2000 Private Proxies New Proxy Lists Every Day Buy Quality Private Proxies