我创建了一个简单的拖动脚本。这将是我游戏的主要输入,以及我将如何控制玩家。脚本如下所示:
public void OnMouseDown() {
offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint (new Vector3 (Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
if (gameController.GetCurrentState () != GameStates.INGAME){
gameController.StartGame();
}
}
public void OnMouseDrag() {
if (gameController.GetCurrentState () == GameStates.INGAME) {
Vector3 curScreenPoint = new Vector3 (Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
Vector3 curPosition = Camera.main.ScreenToWorldPoint (curScreenPoint) + offset;
transform.position = curPosition;
}
}
此脚本已附加到我的播放器。附在我的播放器上的还有RigidBody 2D和Circle Collider 2D。我已经创建了一些墙壁,在游戏开始时,我使用mainCam.ScreenToWorldPoint将其重新定位在摄像机外部。这完成了:
var mainCam : Camera;
var topWall : BoxCollider2D;
var bottomWall : BoxCollider2D;
var leftWall : BoxCollider2D;
var rightWall : BoxCollider2D;
//Reference the players
function Start () {
//Move each wall to its edge location:
topWall.size = new Vector2 (mainCam.ScreenToWorldPoint (new Vector3 (Screen.width * 2f, 0f, 0f)).x, 1f);
topWall.center = new Vector2 (0f, mainCam.ScreenToWorldPoint (new Vector3 ( 0f, Screen.height, 0f)).y + 0.5f);
bottomWall.size = new Vector2 (mainCam.ScreenToWorldPoint (new Vector3 (Screen.width * 2, 0f, 0f)).x, 1f);
bottomWall.center = new Vector2 (0f, mainCam.ScreenToWorldPoint (new Vector3( 0f, 0f, 0f)).y - 0.5f);
leftWall.size = new Vector2(1f, mainCam.ScreenToWorldPoint(new Vector3(0f, Screen.height*2f, 0f)).y);;
leftWall.center = new Vector2(mainCam.ScreenToWorldPoint(new Vector3(0f, 0f, 0f)).x - 0.5f, 0f);
rightWall.size = new Vector2(1f, mainCam.ScreenToWorldPoint(new Vector3(0f, Screen.height*2f, 0f)).y);
rightWall.center = new Vector2(mainCam.ScreenToWorldPoint(new Vector3(Screen.width, 0f, 0f)).x + 0.5f, 0f);
}
与玩家一样,这面墙也附有RigidBody 2D和Box Collider 2D。我的问题是我无法发现任何类型的碰撞。甚至当我把球拖到墙上时也是如此。我打算用这个脚本检测是否在拖动时触摸了墙壁。通过这样做,我将能够调用我的游戏状态" GameOver"并结束游戏。
任何关于为什么的想法,我都无法检测到这种碰撞?我确信墙壁处于正确位置,球确实碰到了墙壁。
答案 0 :(得分:1)
您是否只是在询问如何检测碰撞?确保所有对象(墙和播放器对象)都有Collider2D组件。在这些碰撞者上,将 IsTrigger 设置为 true 。然后在你的播放器控制器中:
void OnTriggerEnter2D(Collider2D other) {
// check if "other" is a wall
if (other.transform.GetComponent<Wall>())
this.gameState = GameStates.GAMEOVER;
}
请注意,至少有一个可碰撞的GameObject需要一个RigidBody2D。只需在所有东西上放置一个RigidBody2D,就不要使用重力。
答案 1 :(得分:0)
你没有写过如何制作screenPoint,所以这里只是如此
public void OnMouseDown() {
screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);