Hello everyone,
I have a project in which when you click on an object you select it. When selected, the object follows the mouse cursor. Now I want to have the selected object jump on top of any other objects that I point my mouse on. Here is my piece of code that controls the mouse movement and object collision detection.
public bool isSelected;
public List<Collider> currentlyCollidingWith = new List<Collider>();
public GameObject lastCollidedObject;
void OnCollisionEnter(Collision col){
currentlyCollidingWith.Add(col.collider);
lastCollidedObject=col.gameObject;
}
void OnCollisionExit(Collision col){
currentlyCollidingWith.Remove(col.collider);
}
void OnMouseDown(){
isSelected=!isSelected;
}
void FixedUpdate(){
if(isSelected)
{
Vector3 distanceToCam = Camera.main.WorldToScreenPoint(transform.position);
Vector3 mousePos = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x,Input.mousePosition.y,distanceToCam.z));
if(currentlyCollidingWith.Count>0)
{
transform.position=new Vector3(mousePos.x,lastCollidedObject.collider.bounds.max.y+gameObject.collider.bounds.extents.y,mousePos.z);
}
else
{
transform.position=new Vector3(mousePos.x,gameObject.collider.bounds.extents.y,mousePos.z);
}
if(Input.GetKeyUp(KeyCode.Mouse1))
{
transform.RotateAround(new Vector3(transform.position.x,transform.position.y,transform.position.z),new Vector3(0,1,0),45.0f);
}
}
}
Also you can see my problem on this video as well:
The problem occurs only when an object’s collider touches the edge of another collider. On such occasions, the collider returns a collision on one frame but no collision on the next frame which causes the object to change positions every frame.
Any help is appreciated. Thank you.