This site requires JavaScript, please enable it in your browser!
Greenfoot back
Duck12
Duck12 wrote ...

2020/11/24

Creating solid object horizontally, vertically, diagonally

Duck12 Duck12

2020/11/24

#
I'm quite new in the programming world and I came across a problem I couldn't solve myself. I wanted to create a 2 player tank game where they have to fight each other. I also wanted to have some blocks the players can't pass through, but i don't l know how to add them. Here is my code for Player1: public class Player1 extends Player { public Player1() { setImage("Blue.png"); getImage().scale(40,40); } public void act() { moveAround(); isTouchingBlock(); } private void moveAround() { if(Greenfoot.isKeyDown("w")) { move(2); } if(Greenfoot.isKeyDown("a")) { setRotation(getRotation()-2); } if(Greenfoot.isKeyDown("s")) { move(-2); } if(Greenfoot.isKeyDown("d")) { setRotation(getRotation()+2); } } public void isTouchingBlock() { if(isTouching(Stein.class)) { setLocation(getX(), getY()); } } } Stein.class is my block that shouldn't be passed. There is nothing in that code yet. I'd appreciate every help. Thanks!
danpost danpost

2020/11/24

#
Collision is an integral part of moving and both should be dealt with together -- move; if collision, move back To move back, the direction moved needs to be known. Thus, moving and collision are inseparable. Moreover, collisions can occur while turning also and the same logic applies with them.
Duck12 Duck12

2020/11/24

#
So what can I do with my code? Shall I change it? I still don't know what you mean.
Duck12 Duck12

2020/11/24

#
well i solved the problem a litlle with this code: if(isTouching(class.Stein)) { move(-2); } but still acting weirdly.
danpost danpost

2020/11/24

#
Duck12 wrote...
well i solved the problem a litlle with this code: if(isTouching(class.Stein)) { move(-2); } but still acting weirdly.
Your moving could be +2 (from "w") or -2 (from "s"). Moving back must take that into account. It needs to "know" which way you moved to begin with.
Duck12 Duck12

2020/11/24

#
That solved my problem thanks Danpost!
You need to login to post a reply.