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

2015/1/6

Selecting A Class And Moving It: Can someone help me please

TheLlama TheLlama

2015/1/6

#
Hi, i've been making a game recently and i want to make it so the tank that i click on is selected and where-ever i click the mouse next it will move and also be deselected after i've clicked the mouse to move it. I dont want it too move too quickly either and i also want it to turn towards the mouse just before it moves. Can someone help me please? Thanks
danpost danpost

2015/1/6

#
Since the tank must be deselected at the time of the click to move it, the movement will have to be controlled by the tank itself; if deselecting was done after the tank has finished moving, I would say to code it in the world class. Either way, however, the selecting itself will need to be done in the world class using a field to hold any tank clicked on -- detect first click and save tank in field; detect second click, tell tank where to go and clear field (reset its value back to 'null'). The state of the field, whether it contains a tank object or has a 'null' value, can be used to determine which click is which. You will need a method in the class of the tank that the world can call so it can prepare its trek. Call it 'proceedToClick()'. Acquiring the MouseInfo object can be done inside this method (the world does not need a MouseInfo object on the second click; it only needs to know that a click event occurred while a tank object was stored in the field). For the first click, however, the world will need to get a MouseInfo object and determine if the click was indeed on a tank (use the 'instanceof' conditional operator) and then save that tank in the field, if so. Do what you can with what was given and if you encounter any specific problems, post the code and explain for help.
TheLlama TheLlama

2015/1/6

#
Thanks, but how would i keep the tank in the field?
danpost danpost

2015/1/6

#
TheLlama wrote...
Thanks, but how would i keep the tank in the field?
Declare the field outside the method. That is, instead of a variable that is local to a method -- like this:
public void act()
{
    // blah, blah, blah
            Tank tank; // variable declared locally (inside the method)
            tank = (Tank)mouse.getActor(); 
    // blah, blah, blah
}
You would do this:
private Tank tank; // world instance field; default value is 'null'

public void act()
{
    // blah, blah, blah
            tank = (Tank)mouse.getActor();
    // blah, blah, blah
}
By declaring the field outside the method, it is retained for as long as this object exists ('this object' being the current world object, since we are in your world class -- your class that extends World).
You need to login to post a reply.