Hello, for my game I want the player to be able to switch between a melee weapon or ranged weapon. To do this they can press "T" for melee or "Y" for ranged. (The below code is in my class called "Player" which is the actor the player controls):
^This code is suppose to access a method called newWeapon() in my MyWorld class which is a child of my World class, and it is suppose to run that method in order to replace the weapon on the player currently (code for method (in MyWorld class)is below):
the variable 'p' just stores a reference to the player object.
The problem I am having is that pressing either 'T' or 'Y' does not change the weapons. The weapon that I already have equipped remains and never leaves. I had set it as so in my MyWorld constructor:
So, the method does work as the melee weapon is on the player upon running the game, but it does not work for changing weapons again.
Also, am I right in thinking the best way to switch object out is to destroy the original then set that variable which was holding the object to a new object? I'm thinking the problem might lay there.
Any help would be appreciated thank you.
1 2 3 4 5 6 7 8 9 | if (Greenfoot.getKey()== "T" ) { world.newWeapon( new Melee()); } if (Greenfoot.getKey()== "Y" ) { world.newWeapon( new RangedWeapon()); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public void newWeapon(Weapon w) { weapon = w; addWeaponToGame(weapon); } public void addWeaponToGame(Weapon w) { //checks is weapon exists already, if it does then it will destroy it if (weapon != null ) removeObject(weapon); //sets weapon variable to the new weapon weapon =w; addObject(weapon, p.getX(), p.getY()); } |
1 | addWeaponToGame( new Melee()); |