# Unity [java] 2D collision response

This topic is 4672 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I'm having a problem identical to the one in this thread. I have to move the player to the edge of the object it collided with, but I don't know how to find out which side it collided with, since the player can be moving in different x and y velocities at the same time. I'm using rectangles as bounding boxes and checking for collisions with the intersects() method. I've gotten it so that it works fine if you collide diagonally on the left or right side of an object, but I don't know how to correct the collision response for the top and bottom sides. Here's what I've come up with so far:
    private void updatePlayer(long elapsedTime)
{
float dx = player.getVelocityX();
if (player.getBounds().intersects(player2.getBounds())) {
if (dx > 0) {
player.setX(player2.getX() - player.getWidth());
}
else if (dx < 0) {
player.setX(player2.getX() + player2.getWidth());
}
}
player.updateBounds();
float dy = player.getVelocityY();
if (player.getBounds().intersects(player2.getBounds())) {
if (dy > 0) {
player.setY(player2.getY() - player.getHeight());
}
else if (dy < 0) {
player.setY(player2.getY() + player2.getHeight());
}
}
}


Thanks [Edited by - nataku92 on August 27, 2005 2:43:34 PM]

##### Share on other sites
Well in order to collide it has to collide in both axis so there will always be 2 sides that are colliding(I am assuming you are using rectangles). So the question is which axis should you move the box in. I think in order to move an object out of another you should move in the axis that has the smallest distance between colliding sides. I wasn't sure if that made sense so I drew you a picture .

This should work and look pretty good in most cases, but is likely to be defective if the rectangles are very small or move very fast. Those errors could be fixed by moving the objects back when they collide and then moving back into the collision in smaller increments. Something like this:
If (boxa.collides(boxb)) {   boxa.position-= boxa.velocity   boxb.position-= boxb.velocity    boxa.velocity*=0.1   boxn.velocity*=0.1   for(int k=0;k<10;k++){      boxa.position+= boxa.velocity      boxb.position+= boxb.velocity       If (boxa.collides(boxb)) {         fix collision errors in position         break loop      }   }   boxa.velocity*=10   boxn.velocity*=10}

##### Share on other sites
Thanks for the help Alrecenk. Works fine most of the time, even without moving the player by increments and checking for collisions. However, I found 2 situations in which this method wouldn't work:

1. If the player collides on the y-axis but just hits the edge of the object, creating an intersection box with the width less than the height. (Same on the x-axis).

2. If the intersection box has the same width and height. Then it wouldn't be possible to find if the player collided on the x-axis, y-axis, or directly on the corner.

Oh, and I might switch to using the area class to more accurately describe the player, so I need a different method to handle collisions.

Thanks

[Edited by - nataku92 on August 28, 2005 1:09:39 AM]

##### Share on other sites
this is what I've been doing

public void CollisionDetection(IMoveableObject o){   while(o.dx < 0 && (!isEmpty(o.left + o.dx, o.top) || !isEmpty(o.left + dx, o.bottom)){      o.dx++;   }   while(o.dx > 0 && (!isEmpty(o.right + o.dx, o.top) || !isEmpty(o.right + dx, o.bottom)){      o.dx--;   }   while(o.dy < 0 && (!isEmpty(o.left, o.top + o.dy) || !isEmpty(o.right, o.top + o.dy)){      o.dy++;   }   while(o.dy > 0 && (!isEmpty(o.left, o.bottom + o.dy) || !isEmpty(o.right, o.bottom + o.dy)){      o.dy--;   }}/*** returns true if the specified point on this object is empty. This example is for a tile map*/public bool isEmpty(int x, int y){   int tx = x / tileWidth;   int ty = y / tileHeight;   return (map[y][x] == WALKABLE); //obviously this isn't the exact test, it just conveys the meaning}

##### Share on other sites
The easiest way I find to do 2D collisions in Java is to add 4 additional rectangles. First check that whatever the player controls is in someway intersecting the other object. If it is then it needs to check to see which part of the player is colliding with the other object. In otherwords there is a rectangle for the top, the left side, the right side, and the bottom of the player. Find which one of those is intersecting the object and then make the additional adjustments you need to. I am working on a game where you rotate the level around the player, and all the collisions seem to work this way perfectly.

##### Share on other sites
Thanks for the ideas. I'll try them out as soon as I can. I still need a method for collision detection with the area class though.

Thanks

##### Share on other sites
In my opinion, you should use the center of the object and its velocity to form a vector. The lenght of that vector depends on its velocity. Use that vector as a line to check for intersection with 4 edges of the other object. You need to make the vector from one rectangly object only and check with other objects (rectangle). If collision happened, send a message to the other object.

Of course there's more to do to make it a perfect 2D collision detection. If you like my idea, respond and I'll post the rest, hope it helps :)

##### Share on other sites
Skeleton_V@T, thanks for the reply. I'd like to see how to implement your method

Thanks

• ### Similar Content

• Hello Guys!
Please share your experience, where is it better to find sales manager  specialists for indie team of 6 + people(remotely)?
Maybe someone has a good experience of cooperation with finding projects through sale managers(USA and Canada)?
Thank you
Best Regards
Alex Vovk
Co-Founder of Sixteen Squares
Alexander_Vovk@outlook.com

• Been a bit quiet recently, but we've been busy bug fixing and tweaking things... Now we have lots more 'Particle effects' in the game, specifically here the Flamethrower and Enemy attacks!

• Hi and thanks for reading, I have an issue with this reactive crosshair script, everything works fine until I start changing the offset. Give the script a go and you will see what I mean, when I do SetOffset(0f); it doesnt always set back to the origional state, if anyone can spot a fix I'd be super appreciative!
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ReactiveCrosshair : MonoBehaviour { [SerializeField] GameObject c_limb_prefab; private float center_offset = 0f; private float current_offset = 0f; private float max_offset = .5f; private int number_of_limbs = 4; private float limb_length = .05f; private float limb_width = .005f; private List<GameObject> c_limbs = new List<GameObject>(); public void SetupCrosshair(){ for (int i = 0; i < number_of_limbs; i++) { GameObject line_go = (GameObject)Instantiate (c_limb_prefab); line_go.transform.SetParent (this.transform); Vector3 limb_pos = new Vector3 (0f,0f,0f); //line_go.transform.position = limb_pos; line_go.transform.localPosition = limb_pos; LineRenderer line = line_go.GetComponent<LineRenderer>(); line.startWidth = limb_width; line.positionCount = 2; line.SetPosition (0, line_go.transform.localPosition + new Vector3(center_offset, 0f, 0f)); line.SetPosition (1, line_go.transform.localPosition + new Vector3(center_offset + limb_length, 0f, 0f)); line.useWorldSpace = false; c_limbs.Add(line_go.gameObject); } if (c_limbs != null) { OrientLimbs (); SetOffset (0f); } } public void OrientLimbs(){ for (int i = 0; i < c_limbs.Count; i++) { float rotation_step = 360f / (float)c_limbs.Count; c_limbs [i].transform.RotateAround (c_limbs[i].transform.position, c_limbs[i].transform.forward, 90f + (rotation_step * (float)i)); } } public void SetOffset(float _current_spread){ float offset = Mathf.Lerp (0f, max_offset, _current_spread); for (int i = 0; i < number_of_limbs; i++) { if (offset > current_offset) { Vector3 pos = c_limbs [i].transform.position + (c_limbs [i].transform.TransformDirection (Vector3.right) * offset); c_limbs [i].transform.position = pos; } if (offset < current_offset) { Vector3 pos = c_limbs [i].transform.position - (c_limbs [i].transform.TransformDirection (Vector3.right) * offset); c_limbs [i].transform.position = pos; } } Debug.Log ("SetOffset() offset: " + offset.ToString () + " _current_spread: " + _current_spread.ToString() + " localPos: " + c_limbs[1].transform.localPosition); current_offset = offset; } }

• So, as the title says i am trying to figure out a good way sync all that information with other players in Unity. My problem is that i can't come up with a good solution since i am used to creating classes for everything e.g. attachments are its own class and then the weapon would save a reference to that attachment. But since you can't send custom classes over [Command] & [ClientRPC] i am a little stuck. A solution for this would be giving each attachment for a slot a unique ID and then passing the ID to other player but i feel like that is very error prone if other ppl add a new attachment or the IDs get mixed up.
Is there a "standard" way that this is usually done that i am missing?
I am fairly new to programming so any help is appreciated!

• I'm looking for any team / people that need a programmer for their project. I'm looking to expand my portfolio which you can see Here. I'm more experienced with Unity but I can spend the time to learn new Engines if that's your preference. I have worked on Unreal Engine 4 before but I might take some time to re-learn it, if the project requires it. Feel free to DM here or use the contact info on my website.

• I'm working on a system for my game that will allow the player to stack pick ups in a queue. As one pick up expires, the next automatically activates. I'm having an issue though where if I pick up the first one, it activates fine, but if i pick up a second directly after it, it overrides the first one, activates the second one, and then once it has run it's course, everything goes back to normal gameplay, no first pick up. I'm not sure why this is happening. Hopefully someone can spot what I'm doing wrong in my code.
Here is the code for the pick up manager:
// Update is called once per frame void Update () { if (pickUpQueue.Count != 0 && !pickUpActive) { pickUpActive = true; pickUpQueue[0].ActivatePickUp(); } DeactivatePickUp(); } void DeactivatePickUp () { if (pickUpQueue.Count != 0 && pickUpActive) { Destroy (pickUpQueue [0]); pickUpQueue.RemoveAt (0); pickUpActive = false; } } And here is the PickUp:
public override void ActivatePickUp () { ball.GetComponent<Ball>().Speed = 2.0f; //increase ball speed... ball.GetComponent<Ball>().StartCoroutine(timer); //...set time that power up is active }
There is also a Base Pick Up:
public void OnCollisionEnter2D (Collision2D collision) { Vector2 tweak = new Vector2 (Random.Range(0f, 0.2f),Random.Range(0f, 0.2f)); this.gameObject.GetComponent<Rigidbody2D>().velocity += tweak; //if the pickup makes contact with the paddle or ball.... if (collision.gameObject.tag == "Paddle" || collision.gameObject.tag == "Ball") { GameObject.FindObjectOfType<GameManager>().GetComponent<PickUpManager>().pickUpQueue.Add(this); Destroy(gameObject); //...and finally destroy power up object } } As a side note, I am trying to find a solution to this that will work for all of my pickups. Some pickups are ammo based, some are timed.
• By D34DPOOL
Edit Your Profile D34DPOOL 0 Threads 0 Updates 0 Messages Network Mod DB GameFront Sign Out Add jobEdit jobDeleteC# Programmer for a Unity FPS at Anywhere   Programmers located Anywhere.
Posted by D34DPOOL on May 20th, 2018
Hello, my name is Mason, and I've been working on a Quake style arena shooter about destroying boxes on and off for about a year now. I have a proof of concept with all of the basic features, but as an artist with little programming skill I've reached the end of my abilities as a programmer haha. I need someone to help fix bugs, optomize code, and to implent new features into the game. As a programmer you will have creative freedom to suggest new features and modes to add into the game if you choose to, I'm usually very open to suggestions :).
What is required:
Skill using C#
Experience with Unity
Experience using UNET (since it is a multiplayer game), or the effort and ability to learn it
Compensation:
Since the game currently has no funding, we can split whatever revenue the game makes in the future. However if you would perfer I can create 2D and/or 3D assets for whatever you need in return for your time and work.
It's a very open and chill enviornment, where you'll have relative creative freedom. I hope you are interested in joining the team, and have a good day!

To apply email me at mangemason@yahoo.com

• Is there a way to automatically change the start position of an animation? I have a bunch of animations set up on 3D models in unity. The issue is that I need to move the 3D models, however when I do so the animation start positions are not updated and I have to do it manually.

Changing the transform of key frames is time consuming with the amount of animations I have, so I was wondering if there was a way to do it automatically?
• By MoreLion
hey all! We are looking for members for our Unity horror game!
Here’s the story:
After a deadly virus plunges the world into chaos killing 85% of the human population there are now what they call “zones” these zones are watched very closely by the surviving government, people are checked every day for the virus, even if you touch the spit or any human waste or fluids of the victim who is infected, you will die. But one day, people in the west zone start to go missing, 1 woman goes outside the walls to uncover the mystery, is there more to the virus than meets the eye?, That is where your story starts.
This game is not a long development game, I have loads other game ideas,
I will also allow you to have a bit of creative freedom if you wish to add or share a idea!
And no, it’s not a zombie game lol I feel like zombie games are too generic, in this game you will encounter terrifying beasts!
There is some concept art one of our concept artists have made
If interested email liondude12@gmail.com

• GOVERNOR is a modernized version of the highly popular series of “Caesar” games. Our small team has already developed maps, written specifications, acquired music and performed the historical research needed to create a good base for the programming part of the project.

Our ultimate goal is to create a world class multi-level strategic city building game, but to start with we would like to create some of the simpler modules to demonstrate proof of concept and graphical elegance.

We would like programmers and graphical artists to come onboard to (initially) create:

A module where Province wide infrastructure can be built on an interactive 3D map of one of the ancient Roman Provinces.
A module where city infrastructure can be built on a real 3D interactive landscape.
For both parts, geographically and historically accurate base maps will be prepared by our team cartographer. Graphics development will be using Blender. The game engine will be Unity.

More information, and examples of the work carried out so far can be found at http://playgovernor.com/ (most of the interesting content is under the Encyclopedia tab).

This project represents a good opportunity for upcoming programmers and 3D modeling artists to develop something for their portfolios in a relatively short time span, working closely with one of Canada’s leading cartographers. There is also the possibility of being involved in this project to the point of a finished game and commercial success! Above all, this is a fun project to work on.

Best regards,

Steve Chapman (Canadian Map Makers)

• 11
• 19
• 12
• 34
• 9
• ### Forum Statistics

• Total Topics
631398
• Total Posts
2999838
×