我正在开发一个带有触摸控制的移动游戏。我可以很容易地选择一个不动的游戏对象,它会做出反应,但是当它移动的时候很难选择它,因为它是很小的(例如,它是基于物理的)。是否有一种方法可以增加游戏对象的触点半径,这样就可以更容易地按下它,还是有其他的解决方案?
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) {
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint((Input.GetTouch(0).position)), Vector2.zero);
if (hit.collider != null) {
selectedCube = hit.collider.gameObject;
selectedCube.GetComponent<SpriteRenderer>().color = Color32.Lerp(defaultColor, darkerColor, 1);
}
}
}
发布于 2015-12-14 14:23:12
与其增加对象的对撞机大小(您在评论中已经讨论过),不如以相反的方式来处理呢?使用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);
}
}
}
请注意,如果在每个other...but上有大量可选择的对象,那么这也不是什么好事,在这种情况下,增加对撞机的大小也于事无补。(我想说的是,只要增加物体的大小就行了。否则无法提高用户的准确性。或允许多选择,并使用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);
}
}
}
https://stackoverflow.com/questions/34277051
复制