Monogame Nez碰撞检测

时间:2017-11-22 23:07:05

标签: monogame

我正在用monogame和nez制作一个平台游戏我使用平铺地图编辑器创建了一个地图,我在地图上有一个尖峰,如果玩家碰撞,他们就会失去生命。我在钉子周围设置了一个盒子对撞机,玩家有一个盒子对撞机但是如果玩家到达钉子周围的盒子对撞机,它就会通过并且不会发生碰撞。我在nez中使用了碰撞检查方法,例如if(playercollider.collidesWith(spikecollider, out collisionresult),然后添加了一个调试,以查看是否发生了任何碰撞,但它没有显示任何内容。我将不胜感激。

这是我的代码:

class Scene1 : Scene
{
    TiledMap tiledMap;

    public override void initialize()
    {
        addRenderer(new DefaultRenderer());
        //setDesignResolution(800, 480, Scene.SceneResolutionPolicy.ShowAllPixelPerfect);
        Screen.setSize(800 * 2, 480 * 2);


        tiledMap = content.Load<TiledMap>("scene_01");
        var objectLayer = tiledMap.getObjectGroup("entities");
        var playerSpawn = objectLayer.objectWithName("Player Spawn");
        var spikesPos = objectLayer.objectWithName("spike");


        var tiledEntity = createEntity("tiled map");
        tiledEntity.addComponent(new TiledMapComponent(tiledMap, "collisions"));

        var deadly = tiledMap.getLayer("deadly");

        var spikes = createEntity("spikes");
        spikes.setPosition(spikesPos.x, spikesPos.y);
        var spikeCollider = spikes.addComponent(new BoxCollider(2, 4, 110, 24));
        //spikes.addComponent(new TriggerListener());
        //spikes.addComponent(new ProjectileMover());


        // setup our camera bounds with a 1 tile border around the edges (for the outside collision tiles)
        tiledEntity.addComponent(new CameraBounds(new Vector2(-tiledMap.width * 6, -tiledMap.height ), new Vector2(tiledMap.width * (tiledMap.tileWidth + 6), tiledMap.tileHeight * (tiledMap.height + 2.4f) )));

        var player = createEntity("player");
        player.setPosition(playerSpawn.x, playerSpawn.y);
        player.addComponent(new PlayerController());
        player.addComponent(new TiledMapMover(tiledMap.getLayer<TiledTileLayer>("collisions")));
        player.addComponent(new PlayerDamageDetector());
        var playerCollider = player.addComponent(new BoxCollider(-18,6, 32, 32));


        CollisionResult result;
        var playerhealth = player.getComponent<PlayerController>().health;
        if (playerCollider.collidesWith(spikeCollider, out result))
        {
            playerhealth--;
            Debug.log("Collision: {0}", result);
        }


        // add a component to have the Camera follow the player
        camera.entity.addComponent(new FollowCamera(player));


    }
}

1 个答案:

答案 0 :(得分:0)

我找到了解决这个问题的方法。我刚刚在播放器控制器中创建了一个构造函数并添加了碰撞器参数,然后在播放器控制器更新中检查碰撞,然后当我将playercontroller添加为scene1类中的组件时,我传入了尖峰碰撞器。

这是代码:

Collider other;
CollisionResult result;

public PlayerController(Collider collider)
{
    this.other = collider;
}

然后在播放器控制器的更新方法中添加了这个

if (boxCollider.collidesWith(other, out result))
            Debug.log("Collision : {0} Results {1}", other, result);

然后在scene1类中我将spikecollider作为参数传递

player.addComponent(new PlayerController(spikeCollider));

现在我能够发现碰撞。