Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Control mouse input to place game elements

Discussion in 'Scripting' started by bzkarcade, Feb 4, 2022.

  1. bzkarcade

    bzkarcade

    Joined:
    Oct 5, 2017
    Posts:
    21
    Hello, I currently have a prototype of a 2D Tower Defense game where a mechanic is to place towers on a piece of land, but each place is already predefined.

    The game is planned for PC, and the input will be done with Mouse + Keyboard.

    I have the problem when using the mouse to place the tower on the ground.

    Basically with a RayCast I check if an available terrain was clicked to place the tower.

    If the terrain was selected on the mouse click, it starts to process the logic of tower placement, if the terrain is already occupied, if the player has enough resources, unlocked tower etc.

    And it seems to be correct but, when adding sound effects, I noticed a problem, since the sound effect is invoked that there was an error when placing the tower.

    Seeing the debug, what happens is that the click lasts several frames and I have something similar to this in the log:

    Code (Log):
    1. spawn true
    2. spawn error
    3. spawn error
    4. spawn error
    5. spawn error
    6. spawn error
    Since the first condition to place a tower is that the terrain is available, something that does not happen in the second frame. (The tower is placed, but the error sound plays)

    The raycast check is done in a FixedUpdate() which is the root of the problem.

    Any suggestion to solve this. Thanks in advance
     
  2. Putcho

    Putcho

    Joined:
    Jun 1, 2013
    Posts:
    246
    we cant see the logic behind your input code
    i assuming you using Input.GetKey/Input.GetMouseButton, as long as you hold the mouse button the "place the tower" method will keep trigger till you release the button
     
  3. bzkarcade

    bzkarcade

    Joined:
    Oct 5, 2017
    Posts:
    21
    I have something like this:

    Code (CSharp):
    1. if (Input.GetMouseButtonDown(0))
    2.                 {
    3.                     rayHit = Physics2D.GetRayIntersection(Camera.main.ScreenPointToRay(Input.mousePosition), distanceRay, boardCellMask);
    4.                     if (rayHit)
    5.                     {
    6.                         rayHit.transform.gameObject.GetComponent<BoardCell>().Click();
    7.                     }
    8.                 }
     
  4. Putcho

    Putcho

    Joined:
    Jun 1, 2013
    Posts:
    246
    look ok to me, now debug every if/else logic inside BoardCell.Click() and BoardCell.Update() looking for some boolean that been set to true but never set back to false.