Stop transform.position by collider
Hi all, Is there any way to stop an object from going further by a collider even if the script makes its position update every frame to increase? Like this:
transform.position = new Vector2(100, transform.position.y); How to stop it from going to 100 if there is a collider in between?
Answer by FlaSh-G · Jun 21, 2017 at 10:58 AM
Give your GameObject a Rigidbody and perform a SweepTest.
var rb = GetComponent<Rigidbody>();
var distance = 100f;
RaycastHit hit;
if (rb.SweepTest(direction, out hit, distance))
{
distance = hit.distance;
}
transform.Translate(direction * distance);
As you can see, you need to specify a direction rather than a target position, as your collision test is based on going a direction rather than arriving at a position ("if there is a collider inbetween").
If needed, you can calculate the direction by subtracting the current position from the targetPosition:
var direction = targetPosition - transform.position;
By the way, if your object does not have a collider but rather is a point, replace the SweepTest with a regular Raycast and don't add a Rigidbody.
Well I guess I can't do it without specifying a position because here is a script:
void FixedUpdate () { if (!is$$anonymous$$ovable) return; float pos = Input.mousePosition.x; if (pos > maxX) pos = maxX; if (pos < $$anonymous$$X) pos = $$anonymous$$X; transform.position = new Vector2 (pos, transform.position.y); }
This script is on the object which has to move. Right now I am using the maximum and $$anonymous$$imum X value as maxX and $$anonymous$$X respectively but I would like to use colliders to limit it because the values may change.
It seems like you didn't understand my answer.
If needed, you can calculate the direction by subtracting the current position from the targetPosition
The object has a Rigidbody2D which does not have SweepTest. Please help me I am in a fix.
In 2D, this might be quite a challenge. If you don't need to be 100% exact, you could use a CircleCast ins$$anonymous$$d.
Your answer
Follow this Question
Related Questions
Colliders not working 2 Answers
Moving an object to a random position between two objects 1 Answer
Bug - Able to pass through rigidbody/collider when using Lerp/SetPosition 0 Answers
OnTriggerEnter2D calculate wrong collision when Object is scalling 0 Answers
Can you get polygon collider 2d shape from a sprite? 2 Answers