I am making a basic Breakout game and using the following code to detect if the collision between the Capsule Collider 2d and circle collider 2d has happened on the top:
bool FindIfTopCol(Collision2D other)
{
print("collider.y " + collidersize.y / 2);
ContactPoint2D[] contacts = other.contacts;
if (contacts[0].point.y - transform.position.y > collidersize.y / 2)
{
print("top " + (contacts[0].point.y - transform.position.y));
return true;
}
else
{
print("not top " + (contacts[0].point.y - transform.position.y));
return false;
}
}
For the most part the detection was working fine but after running the game a while and especially after the circle collider gets into a non top collision, the method seems to return all the collisions as non top collision.
To figure out the issue i placed print statements and this is the result:
collidery 0.2610874
top 0.2885695
collidery 0.2610874
not top 0.2552783 First actual non top collision
collidery 0.2610874
not top 0.2542975 It's a top collision, but shows as not top
collidery 0.2610874
not top 0.2558844 It's top collision, but shows as not top
And the rest of the collisions for the session is also wrong like this, until i restart the game.
I am not sure whats going wrong here.
And also if there is a better way to detect collision side, please let me know.
I'm not really sure what's happening here but I would use OnCollisionEnter2D() event to detect collisions. Then compare the contact point with the collider center to figure out what surface it hit. Here's an example from kacyesp.
Vector3 contactPoint = collision.contacts[0].point;
Vector3 center = collider.bounds.center;
bool right = contactPoint.x > center.x;
bool top = contactPoint.y > center.y;
Related
I have a simple waypoint system. It uses a transform of arrays that act as the bucket what holds the waypoint values.
I use this waypoint system to move a camera throughout a scene by moving towards one point to another. The scene is not big - so everything is close to each other.
The camera moves from one position to another by button click/press. This works fine.
void Start()
{
//Sets the Camera to the first point
Camera = GameObject.Find("Main Camera");
Camera.transform.position = patrolPoints[0].position
currentPoint = 0;
}
//Fixed Update seems to work better for LookAt
void FixedUpdate()
{
//Looks at initial Target
Camera.transform.LookAt(TargetPoints[0]);
if (click == true)
{
Camera.transform.position = Vector3.MoveTowards(Camera.transform.position, patrolPoints[currentPoint].position, moveSpeed * Time.deltaTime);
//Camera.transform.rotation = Quaternion.Slerp(Camera.transform.rotation, patrolPoints[currentPoint].transform.rotation, Time.deltaTime);
Camera.transform.LookAt(TargetPoints[currentPoint]);
}
}
public void onNextClick()
{
if (currentPoint >= patrolPoints.Length)
{
currentPoint = 0;
}
if (Camera.transform.position == patrolPoints[currentPoint].position)
{
currentPoint++;
click = true;
}
}
I am having difficulty with one aspect of the transform that I haven't talked about yet. That is the rotation.
I have used lookAt for setting up the target of the first look at point and that works. However when it runs to the next target in the look at array - the change is sudden.
I have tried an Slerp in the shot as well - and this works when the waypoint has been placed in the appropriate rotation value - and the value Slerps from one position to the next. However, the timing isn't quite aligning up yet. Some position transitions get there quicker - meaning the rotation is trying to get caught up / while others are lagging behind.
I have tried getting the distance between the current waypoint and the next waypoint and treating that as an overall percentage in the update relative to the current position of the camera - I believe this could help work out how far the rotation should be orientated given the position update.
However, I am somewhat lost on it. Many examples suggest looking at iTween - and I wouldn't imagine this would work - however, I want to get into the math a bit.
Can anyone put me in the right direction?
Looks like the Lerp for Position and a Slerp for Rotation done the trick.
MoveTowards wasn't playing ball with a Slerp on rotation - so I believe the timings weren't aligning.
if (click == true)
{
Camera.transform.position = Vector3.MoveTowards(Camera.transform.position, patrolPoints[currentPoint].position, moveSpeed * Time.deltaTime);
Camera.transform.rotation = Quaternion.Lerp(Camera.transform.rotation, patrolPoints[currentPoint].rotation, moveSpeed * Time.deltaTime);
I've been led to believe the lerp values work like a percentage of such - so the same input value works for it.
Finally I used a range on the distance between current position and update on the click - this helped speed up the button click.
if (Vector3.Distance(Camera.transform.position, patrolPoints[currentPoint].position) < PositionThreshold)
{
currentPoint++;
click = true;
}
Thank you for your time.
I'm developing a platformer in Unity using the 2D engine. I have my player character which has a BoxCollider2D and a RigidBody, and a number of 'walls' which have BoxColliders.
Now, I copied the script for moving the player from another project and made some changes. The part which has to do with movement is as follows:
public void FixedUpdate()
{
physVel = Vector2.zero;
// move left
if(Input.GetKey(KeyCode.LeftArrow))
{
physVel.x = -runVel;
}
// move right
if(Input.GetKey(KeyCode.RightArrow))
{
physVel.x = runVel;
}
// jump
if(Input.GetKey(KeyCode.UpArrow))
{
if(jumps < maxJumps)
{
jumps += 1;
if(jumps == 1)
{
_rigidbody.velocity = new Vector2(physVel.x, jumpVel);
}
}
}
//Apply gravity
_rigidbody.AddForce(-Vector3.up * fallVel);
// actually move the player
_rigidbody.velocity = new Vector2(physVel.x, _rigidbody.velocity.y);
}
Now this works perfectly fine.
The problem arises if the player jumps into a wall. If I keep the direction button mashed 'towards' the wall after having jumped, he is suspended in mid-air. As in the collision appears to be reducing movement on both axis to zero. If I release the direction, he falls normally. Collisions on the other axis works fine. I can hit my head or walk without issue.
Am I missing something obvious?
EDIT: try adding a material with 0 friction to both player and walls and see what happens, if it stops it is a friction error.
I am having a big struggle implementing a collision detect on a list of bricks.
I have a game which randomly drops bricks that are supposed to stack up at the bottom of the screen. I managed to make them stop at the bottom of the screen but they don't stack.
I have this in my update function:
if (r.Next(0, 50) == 8)
{
_bricks.Add(new NormalBrick(this, new Vector2(r.Next(0, 700), 100)));
}
foreach(Brick b in _bricks)
{
b.move(GraphicsDevice.Viewport);
}
My move() function has the following code:
public void move(Viewport viewport)
{
if (_position.Y == (viewport.Height - _texture.Height ))
{
_position = new Vector2(_position.X, _position.Y);
}
else
{
_position = new Vector2(_position.X, _position.Y + _speed);
}
}
How can I make sure that the bricks don't all stop at the bottom of the screen, instead the brick has to check if there is a brick beneath it?
I have checked other questions on here but I couldn't find my answer and I have tried several things to get it fixed. Any help would be appreciated.
I would create Rectangles for each of your Bricks (unless you have already done so). Then in the Update() method, use something like brick.Rectangle.Intersects(anotherBrick) after movement. If true, then position the current brick above the intersecting bottom brick.
Make sure to move the brick's rectangle each time the brick moves.
I hope this helps. Let me know if you require any further assistance.
Before you point out that there are other answers to this question, i have looked at if not all, most of the other answers to this question or a similar question and i haven't found the solution i require.
Basically all i want to be able to do is when the circle/ball collides with a rectangle, i want to determine which side of the rectangle this collision has occured at. I want to find this out so that i can enforce a bit more realistic physics, e.g. if the ball hits the top of the rectangle, inverse it's Y velocity only... instead of both.
I have tried comparing the X and Y positions of the ball and the rectangle and even the location of both of their bounding boxes... testing even if the bottom of the ball's box has intersected with the rectangles top... using 'if ball.boundingBox.Bottom >= rectangle.boundingBox.Top'.
I have attached a picture to this to show what i am trying to achieve... just in case it's a bit confusing, as it's not detailed... the red what look like v's is the path if the ball comes in from one side, i want the movement upon impact to travel in the opposite way but this depends on the side of the rectangle as to what component of the ball's velocity i will have to change...
FYI i have also looked at vector normalisation... i haven't used it before so forgive me if this could be solved using this...
Thanks v.much for reading
EDIT as i am in a rush, i have used an different image instead... this still shows the behaviour i am trying to achieve, as the physics shown on the diagram is how i want the ball to behave when it collides with the other sides...
LINK TO IMAGE: http://codeincomplete.com/posts/2011/6/12/collision_detection_in_breakout/bounce2.v283.png
This code might be more comprehensive than you need and can be refactored to suit your needs but it is a complete answer and is flexible to use with moving bounding rectangles along with moving circles.
here is a graphic to give a visual aid to what the code is doing.
the red circle is intersecting with the black rectangle. visualize two imaginary lines going through opposite corners. If you know which side of each of the 2 lines the circle is on, you can deduce the collided edge.
first declare class scope private members
Rectangle CollisionBoxRect;
Rectangle circleRect;
Dictionary<string, Vector2> corners;
In your update after you've moved the circle and set its location and the potential intersected box's location it does a basic check to see if the circle's bounding rect is involved with the block's bounding rect. If so, it then alters the ball's velocity with the appropriate collision normal depending on which side of the rect the circle collided with.
if (CollisionBoxRect.Intersects(circleRect))
{
ballVelocity = Vector2.Reflect(ballVelocity, GetCollisionNormal(CollisionBoxRect));
}
The following methods support getting the proper side (the normal actually). Some of these methods can be done once in the initialize phase if they never change (like the get corners method);
private Vector2 GetCollisionNormal(Rectangle boxBeingIntersected)
{
getCorners(boxBeingIntersected);
bool isAboveAC = isOnUpperSideOfLine(corners["bottomRight"], corners["topLeft"], getBallCenter());
bool isAboveDB = isOnUpperSideOfLine( corners["topRight"], corners["bottomLeft"], getBallCenter());
if (isAboveAC)
{
if (isAboveDB)
{
//top edge has intersected
return -Vector2.UnitY;
}
else
{
//right edge intersected
return Vector2.UnitX;
}
}
else
{
if (isAboveDB)
{
//left edge has intersected
return -Vector2.UnitX;
}
else
{
//bottom edge intersected
return Vector2.UnitY;
}
}
}
public bool isOnUpperSideOfLine(Vector2 corner1, Vector2 oppositeCorner, Vector2 ballCenter)
{
return ((oppositeCorner.X - corner1.X) * (ballCenter.Y - corner1.Y) - (oppositeCorner.Y - corner1.Y) * (ballCenter.X - corner1.X)) > 0;
}
private Vector2 getBallCenter()
{
return new Vector2(circleRect.Location.X + circleRect.Width / 2, circleRect.Location.Y + circleRect.Height / 2);
}
private void getCorners(Rectangle boxToGetFrom)
{
corners.Clear();
Vector2 tl = new Vector2(boxToGetFrom.X, boxToGetFrom.Y);
Vector2 tr = new Vector2(boxToGetFrom.X + boxToGetFrom.Width, boxToGetFrom.Y);
Vector2 br = new Vector2(boxToGetFrom.X + boxToGetFrom.Width, boxToGetFrom.Y + boxToGetFrom.Height);
Vector2 bl = new Vector2(boxToGetFrom.X, boxToGetFrom.Y + boxToGetFrom.Height);
corners.Add("topLeft", tl);
corners.Add("topRight", tr);
corners.Add("bottomRight", br);
corners.Add("bottomLeft", bl);
}
Okay, so, I am making a small tile-based digging game, now I want to do collision. How would I go about doing this correctly? I know how to check if the player collides with a tile, but I don't know how to actually make the player stop when it hits a wall.
This is the game, I got 20x20 tiles here.
This is the code I'm using atm:
foreach (Tile tiles in allTiles)
{
if (ply.rect.Intersects(tiles.rect))
{
if (tiles.ID != -1 && tiles.ID != 1)
{
if (ply.X > tiles.X)
{
Console.WriteLine("Right part.");
ply.X = tiles.pos.X + 30;
}
if (ply.X <= tiles.X)
{
Console.WriteLine("Left part.");
ply.X = tiles.pos.X - 30;
}
if (ply.Y > tiles.Y)
{
Console.WriteLine("Bottom part.");
ply.Y = tiles.pos.Y + 30;
}
if (ply.Y <= tiles.Y)
{
Console.WriteLine("Upper part.");
ply.Y = tiles.pos.Y - 30;
}
}
}
}
What type of collision detection are you using?
If your using Rectangles and the '.intersects' method you can always declare a bool to make sure your character is touching the floor. If he isn't you apply a Gravity Vector to make it fall to the next Tile with a different Rectangle so when he hits it he's going to stop falling.
If you want to block him from side to side just test to see which side of the rectangle he is touching and block him from moving on the 'X' axis.
E.g if he is going right and intersects with the left part of a rectangle, block is 'GoingRight' movement.
if(myCharacterRectangle.Intersects(tileRectangle)
{
if(myCharacterPosition.X > (tilePosition.X)
{
//You know the character hits the Right part of the tile.
}
if(mycharacterPosition.X <= tilePosition.X)
{
//You know the character hits the Left Part of the tile.
}
}
And same goes for the Position.Y if you want to test the Top or Bottom.
If you want to use Pixel by Pixel collision detection using Matrices I know a good tutorial here.
The detection will return a 'Vector2(-1,-1)' if there is no collision.
If there is a one the method will return the coordinates of the collisions which makes it even easier to determine what part of the tile your character is touching.
Hope this helps. Good Luck with your game.