I’m trying to rotate an object, only if the rotated position is collision free. The object is made up of several child objects, each of which have their own collider.
The way I’ve gone about doing this is rotating the object, then checking if the object is in a collision. If it is, the object is rotated back to its original position. However, it seems my collision check is always returning true, so the block is always rotated back. Any ideas? I have a feeling that the children are colliding with each other, which makes the collision check always return true.
I’d also like to note that the collision check works in another part of my code, where I’m checking if a new position is collision-free (without rotation) but doesn’t seem to work here.
Rotation
// block rotation
if (Input.GetKeyDown(KeyCode.Q))
{
this.transform.Rotate(Vector3(0, 0, 90));
// if rotating puts piece in collision
if (Collide(this.transform.position.x, this.transform.position.y))
{
// rotate back
this.transform.Rotate(Vector3(0, 0, -90));
}
}
else if (Input.GetKeyDown(KeyCode.E))
{
this.transform.Rotate(Vector3(0, 0, -90));
// if rotating puts piece in collision
if (Collide(this.transform.position.x, this.transform.position.y))
{
// rotate back
this.transform.Rotate(Vector3(0, 0, 90));
}
}
Collision Check
// moves peice to specified position and check children for collisions
function Collide(x:Number, y:Number)
{
// save position
var oldX:Number = this.transform.position.x;
var oldY:Number = this.transform.position.y;
// move to new position
this.transform.position.x = x;
this.transform.position.y = y;
// make sure none of children collide
var count:int = this.transform.GetChildCount();
for (var i:int = 0; i < count; i++)
{
var block:Block = this.transform.GetChild(i).GetComponent("Block") as Block;
if (block.Collide(block.transform.position.x, block.transform.position.y))
{
// move back to original pos
this.transform.position.x = oldX;
this.transform.position.y = oldY;
return true;
}
}
// move back to original pos
this.transform.position.x = oldX;
this.transform.position.y = oldY;
return false;
}
Block Collision Check
// checks for collisions at the specified position
function Collide(x:Number, y:Number)
{
return Physics.CheckSphere(new Vector3(x, y, this.transform.position.z), 0.48);
}