collision detection – Pygame advanced blitting options

I need advanced blitting options in my game as the latter is a 2D game that has trees’ sprites along with the player’s sprite.

So I want that every tree sprite gets blitted at a specific position relatively with the player’s coordinates.

These are the possible cases :

cases

I have an idea in mind which is to check for the player’s coordinates and depending on them, blit the tree’s sprite underneath it or above it (respecting the layers system). However, I think that this won’t work or will make the tree’s sprite flicker in case there is more than one player (or another object that can pass beside the tree). So what is a good solution for that ?

The reason why I want to solve this problem is adding some depth and reality into the game though it’s a 2D one.

collision detection – Best practice for detecting enemy death in 3D platformer

I’m building a 3D platformer, and I’m having issues figuring out how I should determine whether the player has effectively jumped on an enemy to kill them.

My current approach uses “hurtboxes” above the enemies like so:

hitbox picture

And if the player has a negative velocity and isn’t grounded while they collide with that hurtbox, it will kill the enemy. This works pretty well, but isn’t ideal because the hurtbox being too big makes killing them easy, but making it too small results in unexpected failure to kill the enemy, which would be frustrating to a player.

Is this typically how 3D platformers deal with this issue, or are there better ways?

Thank you!

binary – Can possiblity of hash collision be “zero” when we hash same file in different formats?

Let’s say I have a file A, which is any normal file (pdf, jpeg, mp3 etc.)

Now I get the binary dump of file, say another file B{A}.

And the hexdump of file say, file H{A}.

Now I hash all the three files with any 256 bit HASH (SHA256, BLAKE256 etc.)

I want to know that :

1. What is the possiblity of hash collision in this case (Considering if somehow I find a collison in case of file A, I still can generate the hex and binary dump of that file to see if hashes of B{A} and H{A} matches or not).

2. Will it still be 1/256* 256* 256? Or

3. Will there be 0 collision ? (Considering collision between exactly same size of files)

java – How can i fix my enemy movement, and collision?

I recently started a project with some friends, Its a simple java game and im having issue getting the Collision and enemy movement working properly.

Using this:

if(tempObject.getId() == ID.Block) {
            if (getBoundsBig().intersects(tempObject.getBounds())) {
                velX = -velX;
                velY = -velY;
            }
            else {
                velX = (jenny.nextInt(4 - -4) + -4);
                velY = (jenny.nextInt(4 - -4) + -4);
            }
        }

I can get basic enemy movement, however the collision doesn’t seem to work. Enemies often change velocity really fast but the enemies end up phasing through walls. I thought just setting the velocity to the negative counterpart would be enough. Its not.

In - Game footage of enemy phasing

As seen in the gif above the enemy still decides to run right through a wall. Any ideas on how i could fix this?

c# – Rectangle collision not working!

I’m making a simple game in C# and i’m having some problems with rectangle collisions.
What i’m doing is checking if two rectangles intersects, checking the side of collision and then moving the rectangles away from each other.

What is working:

  • The rectangle intersection check is working.
  • The left and right rectangle side collisions is working.

What is not working:

  • When i move a rectangle to the top or bottom side of another the first rectangle jumps to the other side.
  • The first problem works correctly if the first rectangle is alligned perfectly to the top or bottom side.

Here is a snippet of the code that i currently have, i hope someone can help me find the problems.

public RectangleF Bounds { get { return new RectangleF(position.x, position.y, scale.width, scale.height); } }

public void CheckCollisions(Transform first, Transform second)
{
    if(first.Bounds.IntersectsWith(second.Bounds) == false) return;

    bool touching_left =
    first.Bounds.Right > second.Bounds.Left &&
    first.Bounds.Left < second.Bounds.Left &&
    first.Bounds.Bottom > second.Bounds.Top &&
    first.Bounds.Top < second.Bounds.Bottom;

    bool touching_right =
    first.Bounds.Left < second.Bounds.Right &&
    first.Bounds.Right > second.Bounds.Right &&
    first.Bounds.Bottom > second.Bounds.Top &&
    first.Bounds.Top < second.Bounds.Bottom;

    bool touching_top =
    first.Bounds.Bottom > second.Bounds.Top &&
    first.Bounds.Top < second.Bounds.Top &&
    first.Bounds.Right > second.Bounds.Left &&
    first.Bounds.Left < second.Bounds.Right;

    bool touching_bottom =
    first.Bounds.Top < second.Bounds.Bottom &&
    first.Bounds.Bottom > second.Bounds.Bottom &&
    first.Bounds.Right > second.Bounds.Left &&
    first.Bounds.Left < second.Bounds.Right;

    if (touching_left)
    {
        float x = second.Bounds.Left - first.Bounds.Width;
        float y = first.Bounds.Y;

        first.SetPosition(new PointF(x, y));
        Debug.WriteLine("Touching LEFT");
    }

    else if (touching_right)
    {
        float x = second.Bounds.Right;
        float y = first.Bounds.Y;

        first.SetPosition(new PointF(x, y));
        Debug.WriteLine("Touching RIGHT");
    }

    else if (touching_top)
    {
        float x = first.Bounds.X;
        float y = second.Bounds.Top - first.Bounds.Height;

        first.SetPosition(new PointF(x, y));
        Debug.WriteLine("Touching TOP");
    }

    else if (touching_bottom)
    {
        float x = first.Bounds.X;
        float y = second.Bounds.Bottom;
        
        first.SetPosition(new PointF(x, y));
        Debug.WriteLine("Touching BOTTOM");
    }
}

Thanks in advance!

How to use setUserPointer/getUserPointer for collision detections with Ammo.js

I want to print names of colliding objects. I made a very simple example.

I created an object to keep a user data:

        const userData = { name: name };

I keep this object in a body using setUserPointer:

body.setUserPointer(userData);

I try to get this names using getUserPointer and print them. But I get "undefined" instead of names:

function detectCollison(): void
{
    const dispatcher = physicsWorld.getDispatcher();
    const numManifolds = dispatcher.getNumManifolds();

    for (let i = 0; i < numManifolds; i++)
    {
        const contactManifold = dispatcher.getManifoldByIndexInternal(i);
        const body0 = contactManifold.getBody0();
        const body1 = contactManifold.getBody1();

        const p0 = body0.getUserPointer();
        const p1 = body1.getUserPointer();

        console.log("first object: " + p0.name);
        console.log("second object: " + p1.name);
    }
}

This is a TypeScript version. I tried to keep names as a body property but it does not work too. It prints "undefined" instead of names:

        (this.body as any).name = name;

        physicsWorld.addRigidBody(this.body);
function detectCollison(): void
{
    const dispatcher = physicsWorld.getDispatcher();
    const numManifolds = dispatcher.getNumManifolds();

    for (let i = 0; i < numManifolds; i++)
    {
        const contactManifold = dispatcher.getManifoldByIndexInternal(i);
        const body0 = contactManifold.getBody0();
        const body1 = contactManifold.getBody1();

        console.log("first object: " + (body0 as any).name);
        console.log("second object: " + (body1 as any).name);
    }
}
```

mathematics – How to orient a rectangular object, so when a sphere ( ball ) collision happens to redirect it towards a point?

I have a rectangular object and a ball ( sphere ) in 3D and would like to orient the rectangular object in such way that when a collision with the ball and the object happens, to redirect the ball towards a certain point

Here’s an example of what I want to achieve

Example

In short: How to rotate the black rectangle in order to redirect the blue ball towards the yellow.

Thanks in advance

movement – Collision Resolution for Height Maps

GameDev StackExchange!

I’ve written height map collision detection into my game, but I’ve been struggling on how to get the resolution step to work well with player movement. (This is in 3D, by the way.)

The player is represented in the physics engine by a capsule, and the height map is essentially just a series of y-positions (heights) in a grid (2D array) representing (x,z) positions. When testing for a collision, I take all of the rectangular grid spaces that the player intersects with, then test the capsule for intersections against the two triangles that make up each grid space. (These triangle-capsule tests use the Separating Axis Theorem.) This approach allows the player to have multiple collision points, one with each triangle (e.g. one with a “ground” triangle below, keeping him from falling, and one with a “wall” triangle ahead, keeping him from walking farther forward).

However, this approach has issues. For example, if the player falls from a high place and lands on the boundary between two triangles, penetrating some distance into their faces, the direction of minimum penetration will be parallel to the ground rather than along the triangle normals. This causes the player to be pushed parallel to the ground and fall through the terrain instead of being caught.

If the player penetrates into the floor even a little bit, then he will fall through the floor.

I tried to solve this by constraining the triangles to force resolution to occur along the triangle’s normal. This solves the floor-fall problem, but introduces new problems. (There’s programming for you, huh?) For example, if the player jumps at a ledge but doesn’t make it, the triangle at the top of the ledge will still force the player upwards, causing them to be pulled up above the terrain.

The player jumps at a ledge and doesn't make it, but since the top of the ledge must force a resolution along the normal, the player is forced upwards.

Note that, since I’m using a heightmap, I don’t have any true walls and need a solution that works for slopes of any steepness. For example, the following case would also be problematic using the triangle normals as the sole basis of resolution:

The flattened resolution directions would generate similar problems.

At this point, I don’t know how to best take the raw collision resolution data and modify/filter it to work as I would like. How can I get these collisions to work in a sensible manner for player movement?

(It may or may not be useful to note that I currently also have a modifier on the capsule that “flattens” the resolution directions to be either parallel or orthogonal to the capsule’s local vertical direction, vertical being “from sphere to sphere.” This facilitates things like allowing the player to walk up a ramp at angle without forcing them to input a diagonal direction to compensate for being pushed to the side.)

unreal 4 – Make character fall straight down on a collision

I’m building a game where I need my character to fall straight down when an overlap (collision) event occurs while jumping.

Depending on the angle my character gets deflected, I want it to fall straight down after a collision.

I have hooked the OnComponentHit delegate.
enter image description here

I just need a solution.

Thank you!

enter image description here

collision detection – i don’t know why i get this Problem ( i’m totally new in Unity )

My game Object is look like this :

enter image description here

i am having all of my collision in the child object Enemy_Colliders but the problem here is when iam using my Player gameObject which have a function call “Attack” :

void Attack()
    {
        Animator.SetTrigger("Attack");

        hitEnemies = Physics2D.OverlapCircleAll(AttackPoint.position, AttackRange, enemyLayers);

        Debug.Log(hitEnemies);

        foreach (Collider2D enemy in hitEnemies)
        {
            Debug.Log("hit");
            enemy.GetComponent<EnemyBehave>().TakeDamage(AttackDamage);
        }
    }

it can still detect the collision but in console

enter image description here

, but i got this error :

enter image description here

can you guys help me to understand and how to fix this error, iam totally new in Unity.

my Enemy Script (TakeDamage function is call by Attack in Player Script):

public class EnemyBehave : MonoBehaviour
{

    public Transform rayCast;
    public LayerMask raycastMask;
    public float raycastLength;
    public float attackDistance;
    public float moveSpeed;
    public float timer; //cooldown between 2 attack;
    public float maxHealth;

    private RaycastHit2D hit;
    private GameObject target;
    private Animator animator;
    private float distance;
    private bool attackMode;
    private bool inRange;
    private bool cooling;
    private float intTimer;
    private float currentHealth;


    private void Awake()
    {
        intTimer = timer;
        animator = GetComponent<Animator>();
        currentHealth = maxHealth;
    }

    // Update is called once per frame
    void Update()
    {
        if (inRange)
        {
            hit = Physics2D.Raycast(rayCast.position, Vector2.left, raycastLength, raycastMask);
            raycastDebug();
        }

        if (hit.collider != null)
        {
            EnemyLogic();
        }

        else if (hit.collider == null)
        {
            inRange = false;
        }

        if (inRange == false)
        {
            animator.SetBool("canWalk", false);
            StopAttack();
        }


    }



    void EnemyLogic()
    {
        distance = Vector2.Distance(transform.position, target.transform.position);
        if (distance > attackDistance)
        {
            Move();
            StopAttack();
        }
        else if (attackDistance >= distance && cooling == false)
        {
            Attack();
        }

        if (cooling)
        {
            Cooldown();
            animator.SetBool("Attack", false);
        }

    }


    void Cooldown()
    {
        timer -= Time.deltaTime;
        if(timer <= 0 && cooling && attackMode)
        {
            cooling = false;
            timer = intTimer;
        }
    }

    void Move()
    {

        animator.SetBool("canWalk", true);
        if (!animator.GetCurrentAnimatorStateInfo(0).IsName("Attack"))
        {
            Vector2 targetPosition = new Vector2(target.transform.position.x, target.transform.position.y);
            transform.position = Vector2.MoveTowards(transform.position, targetPosition, moveSpeed * Time.deltaTime);
        }
    }

    void Attack()
    {
        timer = intTimer;
        attackMode = true;
        animator.SetBool("canWalk", false);
        animator.SetBool("Attack", true);
    }

    void StopAttack()
    {
        cooling = false;
        attackMode = false;
        animator.SetBool("Attack", false);
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "Player")
        {
            target = collision.gameObject;
            inRange = true;
        }
    }

    void raycastDebug()
    {
        if (distance > attackDistance)
        {
            Debug.DrawRay(rayCast.position, Vector2.left * raycastLength, Color.red);
        }
        else if (distance < attackDistance)
        {
            Debug.DrawRay(rayCast.position, Vector2.left * raycastLength, Color.green);
        }
    }

    public void TriggerCooling()
    {
        cooling = true;
        Debug.Log("cooling");
    }


    public void TakeDamage(int Damage)
    {
        currentHealth -= Damage;

        animator.SetTrigger("Hurt");

        if (currentHealth <= 0)
        {
            Die();
        }
    }

    public void Die()
    {
        Debug.Log("Die");
        animator.SetBool("Die", true);
        gameObject.transform.GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Static;
        GetComponent<Collider2D>().enabled = false;
        GetComponent<CircleCollider2D>().enabled = false;
        StartCoroutine(RemoveFromScreen());
        this.enabled = false;
    }


    IEnumerator RemoveFromScreen()
    {
        yield return new WaitForSeconds(4f);
        Destroy(gameObject);
    }


}