而不是增加對象的collider大小(你在評論中討論過),那麼如何以相反的方式來處理?檢查周圍的觸感,爲碰撞的區域,而不是隻單點,使用Physics2D.CircleCast
:
private void Update() {
//User input (touches) will select cubes
if(Input.touchCount > 0) {
Touch touch = Input.GetTouch(0);
}
Touch[] touches = Input.touches;
foreach(var touchInput in touches) {
float radius = 1.0f; // Change as needed based on testing
RaycastHit2D hit = Physics2D.CircleCast(Camera.main.ScreenToWorldPoint((Input.GetTouch(0).position)), radius, Vector2.zero);
if (hit.collider != null) {
selectedCube = hit.collider.gameObject;
selectedCube.GetComponent<SpriteRenderer>().color = Color32.Lerp(defaultColor, darkerColor, 1);
}
}
}
請注意,這不會是巨大的,如果你已經有了噸互相平齊可選對象。 ..但是,再次,在這種情況下增加對撞機的大小也無濟於事。 (我只是說增加對象大小,沒辦法提高用戶的準確性,或者允許多選,並使用Physics2D.CircleCastAll
)。
希望這會有所幫助!如果您有任何問題,請告訴我。
編輯:爲了獲得更好的精度,由於Physics2D.CircleCast
返回的「第一」的結果可以任意選擇,你可以改用Physics2D.CircleCastAll
獲得觸摸半徑內的所有對象,只能選擇一個最接近的原來的觸摸點:
private void Update() {
//User input (touches) will select cubes
if(Input.touchCount > 0) {
Touch touch = Input.GetTouch(0);
}
Touch[] touches = Input.touches;
foreach(var touchInput in touches) {
float radius = 1.0f; // Change as needed based on testing
Vector2 worldTouchPoint = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
RaycastHit2D[] allHits = Physics2D.CircleCastAll(worldTouchPoint, radius, Vector2.zero);
// Find closest collider that was hit
float closestDist = Mathf.Infinity;
GameObject closestObject = null;
foreach (RaycastHit2D hit in allHits){
// Record the object if it's the first one we check,
// or is closer to the touch point than the previous
if (closestObject == null ||
Vector2.Distance(closestObject.transform.position, worldTouchPoint) < closestDist){
closestObject = hit.collider.gameObject;
closestDist = Vector2.Distance(closestObject.transform.position, worldTouchPoint);
}
}
// Finally, select the object we chose based on the criteria
if (closestObject != null) {
selectedCube = closestObject;
selectedCube.GetComponent<SpriteRenderer>().color = Color32.Lerp(defaultColor, darkerColor, 1);
}
}
}
嗯,我不知道有多少GameObject是在場景中的一次,但增加對撞機的大小呢? – AmRzA
@AmRzA如果我增加對撞機的大小,這個對象上面的對象會漂浮在空中 – Milen
以及在協程內部使用一段時間(真)的情況如何? – AmRzA