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;
 
 
(RequireComponent(typeof(Camera)))
public class CameraEventMasker : MonoBehaviour
{
    (SerializeField)
    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

hybrid.h

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

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

source.cpp

#include"hybrid/hybrid.h"

int main()
{
   setWindowSize(1500, 600);

   makeSequenceWall();//push back 5 Wall constructor

   Player p(300, 300,30,30,0.5,0,1,0);
   //------------
   slWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "HYBRID", false);
   while (!slShouldClose())
   {
               //----------
       p.move();
       p.render();//render the player

       
       for (int i = 0; i != 5; i++)//check the collision
       {
           wallSeq.at(i).reactTo(&p);
       }

       
       for (itr = wallSeq.begin(); itr != wallSeq.end();itr++)//render the wall
       {
           itr->render();
       }
       
       slRender();
   
   }
   slClose();
   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

Question:

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

Reference:

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
{
    (ExecuteAlways)
    (SelectionBase)
    (RequireComponent(typeof(Rigidbody)))
    public partial class ShipController : MonoBehaviour
    {
        (Header("References"))
        (SerializeField)
        private Rigidbody Body;

        (SerializeField)
        private TrackController Controller;

        (Header("Handling"))
        public float TorqueSpeed = 1.0f;

        public float RotationSpeed = 1.0f;

        public float RotationMaxDistance = 2.0f;

        private void Start()
        {
            ResetShip();
        }

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

            ThrustValue = Mathf.Clamp01(ThrustValue);

            ThrustForce = ThrustCurve.Evaluate(ThrustValue) * ThrustMaxSpeed;

            if (Input.GetKeyDown(KeyCode.Escape))
                ResetShip();

            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, Color.green);

                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;
                Body.AddForce(h);
            }

            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);
            }
            else
                // align to world up
            {
                rot = Quaternion.LookRotation(bodyTrans.forward);
            }

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

            Body.MoveRotation(slerp);

            #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));

            #endregion

            // prevent lateral drift
            // https://www.youtube.com/watch?v=qsfIXopyYHY
            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)
                return;

            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        = Vector3.zero;
            Body.angularVelocity = Vector3.zero;

            ThrustValue = 0.0f; // stop thrusting
        }
    }

    public partial class ShipController
    {
        public enum ShipHoverState
        {
            Aerial,
            Ground
        }

        public enum ShipThrustInput
        {
            None,
            Accelerating,
            Decelerating
        }

        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(Vector2.one * scale, Vector2.zero);
            Builder.Clear();
            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 ? Color.red : Color.green)}");
            Builder.AppendLine($"Velocity: {GetShipVelocity().z:F}");
            var text = Builder.ToString().Trim('n', 'r');
            GUILayout.Box(text, Styles.Box);
        }

        private void OnDrawGizmos()
        {
            Gizmos.color = Color.red;
            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(GUI.skin.box) { alignment = TextAnchor.UpperLeft };
        }
    }

    public partial class ShipController
    {
        #region Hovering

        (Header("Hovering"))
        public float HoverHeight = 0.3f;

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

        (Min(1.0f))
        public float HoverSpring = 250.0f;

        (Min(0.01f))
        public float HoverQFactor = 2.0f;

        (Min(0.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;

        #endregion

        #region Thrust

        (Header("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;

        #endregion

        #region Camera

        (Header("Camera"))
        public Camera Camera;

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

        public float CameraSmoothTime = 0.125f;

        public Vector3 CameraVelocity;

        #endregion
    }
}

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 {

    (BurstCompile)
    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() {
        base.OnCreate();
        buildPhysicsWorldSystem = World.GetExistingSystem<BuildPhysicsWorld>();
        stepPhysicsWorldSystem = World.GetExistingSystem<StepPhysicsWorld>();
        commandBufferSystem = World.GetExistingSystem<EndSimulationEntityCommandBufferSystem>();
    }

    protected override JobHandle OnUpdate(JobHandle inputDeps) {    
        JobHandle jobHandle = new CollisionJob().Schedule(
            stepPhysicsWorldSystem.Simulation, 
            ref buildPhysicsWorldSystem.PhysicsWorld, 
            inputDeps);    
        commandBufferSystem.AddJobHandleForProducer(jobHandle);    
        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) https://oraqia.wordpress.com/2014/07/05/tricks-for-2d-grid-based-character-collision-that-can-work-in-3d-too/ I’m currently using this type of collision test https://pastebin.com/UJ1hzCcv 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 ExtraProxies.com - 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 ProxiesLive.com Proxies-free.com New Proxy Lists Every Day Proxies123.com Proxyti.com Buy Quality Private Proxies