0

I'm working on a very basic tower defense game using Javascript in the Code.org online software. What I'm looking for is to click on a tower, it follows the cursor, and then releases when you click a spot on the map. I don't understand why my code isn't working, however. I appreciate the help! I know I'm a beginner and this is probably a very obvious question but it would mean a lot if someone could help me. Thanks!

EDIT: I haven't dealt with the last part yet. All that's included in this program segment is clicking on a tower, and having it follow your mouse cursor.

var mouseYPosition;
var towerIsSelected = false;

function moveTower() {
  onEvent("screen1", "mousemove", function() {
    setPosition("towerOne", mouseXPosition, mouseYPosition);
})}

onEvent("screen1", "mousemove", function(event){
  mouseXPosition = event.x;
  mouseYPosition = event.y;
});

onEvent ("towerOne", "click", function() {
  towerIsSelected = true;
  return towerIsSelected;
});

if (towerIsSelected) {
  moveTower();
}
samgolik
  • 1
  • 1
  • There are various topics about drag and drop here on StackOverflow, like (but not limited to) [Simple drag and drop code](https://stackoverflow.com/questions/18425089/simple-drag-and-drop-code). So should first do some more research, check those questions and answers, and if you still can get it working, you need to explain why those answers didn't help to solve you problem. – t.niese Mar 08 '20 at 18:45
  • Why do you expect that `moveTower` would be called after a `click` happens on `towerOne`? Why do you add another `mousemove` on `screen1` in `moveTower`? – t.niese Mar 08 '20 at 18:48
  • @t.niese I couldn't find a StackOverflow post that I understood and was trying to achieve the same purpose as me. Anyhow, I changed the if statement to inside the "mousemove" onEvent function and that worked. Thank you so much for your help! – samgolik Mar 08 '20 at 18:58
  • But if you keep the `onEvent("screen1", "mousemove", function() {` in your `moveTower` then you register that even over an over again. So you must do that, you only have to have the `setPosition("towerOne", mouseXPosition, mouseYPosition);` in you `moveTower` – t.niese Mar 08 '20 at 19:02
  • @t.niese You're right, just fixed that. Thanks again! – samgolik Mar 08 '20 at 19:19

0 Answers0