title: html/ javascript shop

text:
# Question
Title: html/ javascript shop
Im new to drop down menus. How can I make a working shop in html/javascript. I have this so far http://prntscr.com/o15oj7 . I want help with the selling of a material part. i know i should use if statements but im not sure how to format the function . I want if bronze is selected for how much you can sell it for to be displayed. then if u press sell button you gain that much gold then lose 1 bronze.

```
var goldcoins = 0;
var goldcoins = 0;
var Bronzeprice = 10;
var Silverprice = 20;
var GoldPrice = 50;
var DiamondPrice = 100;
var ShrimpPrice = 10;
var BassPrice = 20;
var SalmonPrice = 50;
var SharkPrice = 100;

function sellItem(){
    var mylist=document.getElementById("myList");document.getElementById("favorite").value=mylist.options[mylist.selectedIndex].text;}

```

Html code:

```
   </style>
                   <font size="+2"><b>Shop</b>
                       <br />
                      <font size="+0"> Auto Miner <button
onclick="buyMiner()"
    id="MinerCostBtn" >Buy</button>
                    <br />
                  <font size="+0"> Auto Fisher <button onclick="buyFisher()" id="FisherCostBtn" >Buy</button>
                <br />
                <br />
                <form>
                Sell:
                <select id"SellBox" >
                    <option> Bronze </option>
                    <option> Silver </option>
                    <option> Gold </option>
                    <option> Diamond </option>
                    <option> Shrimp </option>
                    <option> Bass </option>
                    <option> Salmon </option>
                    <option> Shark </option>
                    </select>
                    For: <span id="currentPrice">0</span>  <button onclick="SellItem()" id="SellBtn" >Sell</button>

                  </form>
                  <br />
                  Gold Coins: <span id="goldcoins">0</span>
                  <br />
                  Buy skillpoint 100,000 gold <button onclick="buySkillPoint()" id="SkillPointBtn" >Buy</button>
                  <br />
                  Buy diamond 10,000 gold <button onclick="buyDiamond()" id="diamonddBtn" >Buy</button>
                  <br />
                  Buy shark 10,000 gold <button onclick="buyShark()" id="sharkkBtn" >Buy</button>
                  <br />
                  <br />
                  <br />

```

I expect when bronze is selected (etc) for how much you will gain from it to be displayed then when button is pressed for you to lose 1 bronze and gain that amount of gold. While the drop down menu is on that item. I have the variables on a diffrent javascript . i do that all those drop down button items . I just need to know how to format the funtion so if they are selected in the drop down menu that item will sell.

# Answer
> 1 votes
To add onto @Xesenix's answer you probably want to make this generate it's own list, without you having to update the drop-down list each time. You do this by creating the drop-down through javascript.

```
let goldCoins = 0;
let selectedPrice = 0;

const itemPrices = {
  bronze: 10,
  silver: 20,
  gold: 50,
  diamond: 100,
  shrimp: 10,
  bass: 20,
  salmon: 50,
  shark: 100,
  // I added this value
  Chicken: 9000
};

// We'll simply get a ref to the select element (or you can create it from here as well if you like)
let itemSelector = document.getElementById('item');

// Now create the option elements
for (let item in itemPrices) {
  // Quickly checking that this is a property that you created
  if (itemPrices.hasOwnProperty(item)) {
    // Create the element
    let option = document.createElement('option');

    // Set the value
    option.setAttribute('value', item);

    // Capitalize the first letter of the item name
    const itemName = uppercaseFirstLetter(item);

    // And add the inner text
    option.innerHTML = itemName;

    // Now add the element to the itemSelector element
    itemSelector.appendChild(option);
  }
}

// To make sure that the first item's price shows on screen
updateSelection();

function uppercaseFirstLetter(str) {
  // Got this code from here: https://paulund.co.uk/how-to-capitalize-the-first-letter-of-a-string-in-javascript
  return str.charAt(0).toUpperCase() + str.slice(1);
}

const chosenItemDropdown = document.getElementById('item');

function updateSelection() {
  selectedPrice = itemPrices[itemSelector.value]
  updateDisplay(selectedPrice);
}

function sellItem() {
  // Add the sell code stuff here
  goldCoins += selectedPrice;
  document.getElementById('gold').innerText = goldCoins;
}

function updateDisplay(value) {
  document.getElementById('price').innerText = value;
}
```

```
Earned: <span id="gold">0</span> Price: <span id="price">0</span>
<select id="item" onchange="updateSelection()">
  <!-- JS will place option elements here -->
</select>
<button onClick="sellItem()">Sell</button>
```

So now, all you need to do is add a new item to `itemPrices` and voilà, you have an auto-updating list. Just add a new item to the list and run the snippet!

# Answer
> 1 votes
To read current selected value from select drop down you need to modify is as follow:

```
Earned: <span id="gold">0</span>
Price: <span id="price">0</span>
<select id="item" onchange="updateSelection()">
  <option value="bronze">Bronze</option>
  <option value="silver">Silver</option>
  <option value="gold">Gold</option>
  <option value="diamond">Diamond</option>
  <option value="shrimp">Shrimp</option>
  <option value="bass">Bass</option>
  <option value="salmon">Salmon</option>
  <option value="shark">Shark</option>
</select>
<button onClick="sellItem()"></button>

```

And in javascript you can do something like this:

```
let goldCoins = 0;
let selectedPrice = 0;

const itemPrices = {
  bronze: 10,
  silver: 20,
  gold: 50,
  diamond: 100,
  shrimp: 10,
  bass: 20,
  salmon: 50,
  shark: 100,
}

const chosenItemDropdown = document.getElementById('item');

function updateSelection() {
  selectedPrice = itemPrices[chosenItemDropdown.value] || 0;
  udateDisplay();
}

function sellItem() {
  goldCoins += selectedPrice; // or do whatever else you want with it
  udateDisplay();
}

function udateDisplay() {
  document.getElementById('gold').innerHTML = goldCoins;
  document.getElementById('price').innerHTML = selectedPrice;
}

```

---
Tags: javascript, html
---


# Question
Title: Exchanging data between custom-built hardware and games
I have a built my own steering wheel and motion platform that I would like to connect to popular car racing games (e.g. iRacing, Dirt Rally). I need to read data such as the car's acceleration (to send to the motion platform) from these games and send information such as steering wheel's angle to the game. I have written an SDK in C++ to communicate with my steering will and motion platform. Now I need to interface different games with to that SDK.

I searched quite a bit but could not find much information about how this is generally done. Do game developers provide some sort of extension which allows third party hardware developers to communicate with their game?

Any guidance from the community is much appreciated.

Kam

# Answer
> 2 votes
An option, on Windows, as far as I have been able to find, is to implement a Force Feedback Device Driver. You need to implement a register to the system a dll with a COM object that implements `IDirectInputEffectDriver`, and writ the CLSID in:

`HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\MediaProperties\PrivateProperties\Joystick\OEM`

Then you would configure Force Feedback with your device in the game.

See Force Feedback Device Driver Interface.

---

*I find the documentation lacking, and I didn't find any code examples.*

# Answer
> 0 votes
> send information such as steering wheel's angle to the game

That's the easy part. Just create a device driver for your platform which reports it as a standard game controller and represents its various input functions as axis and buttons. Any game with controller support will then allow the player to bind those to various game functions.

> read data such as the car's acceleration (to send to the motion platform)

That's the difficult part. The game might not expose that information in a way which is easy to read. What you could try (ordered from easiest to hardest):

* As the answer by Theraot suggests, see if the game sends Force Feedback data to your game controller driver which is sufficient for your purpose.
* Contact the developers of the game and ask them if they would like to collaborate with you to add support for your platform to their game.
* Read the memory of the game executable. Find out the locations in memory where it stores the relevant data and extract it at runtime. Depending on how the game is programmed, this might be a quite frustrating process. And if you eventually find a solution, that solution can easily break with every patch or even on different language versions of the game.
* Hack the game executable. Reverse-engineer it and create a patch/mod which adds support for the platform to the game. If it's an online game with good anti-cheat protection or Digital Restrictions Management, then this might also get in your way.

---
Tags: game-loop, platformer, joystick, motion-control
---


title: Unity3d crash on Launching on Ubuntu

text:
# Question
Title: Unity3d crash on Launching on Ubuntu
I have a problem that bugged me for quite some time now
I'm trying to Install Ubity3d on Ubuntu
I Followed some instructions that i've found after some research I downloaded and installed UnityHub and the latest release (UnitySetup-2019.1.0f2) that i found on Unity on Linux: Release Notes and Known Issues
and i moved the installed unity file from **Home** to **opt** folder and made it run on command *unity3d* and here is what i did exactly

```
sudo mv Unity-2019.1.0f2 /opt/Unity3D
sudo ln -s /opt/Unity3D/Editor/Unity /usr/bin/unity3d

```

and the problem is that every time i open Unity editor (via both the command line and UnityHub) the unity Launcher appears for moments to proccess and then crashes and the editor doesn't open and the error changes everytime i try to open the program here are 3 forms of errors that appeared to me, here is the first

```
Gtk-Message: GtkDialog mapped without a transient parent. This is discouraged.
Gtk-Message: GtkDialog mapped without a transient parent. This is discouraged.
Gtk-Message: GtkDialog mapped without a transient parent. This is discouraged.
Gtk-Message: GtkDialog mapped without a transient parent. This is discouraged.
[Unity Package Manager (Upm)]
Parent process [5258] was terminated
Segmentation fault (core dumped)

```

and the second

```
Gtk-Message: GtkDialog mapped without a transient parent. This is discouraged.
Gtk-Message: GtkDialog mapped without a transient parent. This is discouraged.
(unity-editor:6651): Gtk-CRITICAL **: gtk_file_chooser_widget_set_current_name: assertion 'priv->action ==
GTK_FILE_CHOOSER_ACTION_SAVE || priv->action ==
GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER' failed
Gtk-Message: GtkDialog mapped without a transient parent. This is discouraged.
[Unity Package Manager (Upm)]
Parent process [6651] was terminated
Segmentation fault (core dumped)

```

the third is

```
Gtk-Message: GtkDialog mapped without a transient parent. This is discouraged.
[0616/110743:ERROR:browser_main_loop.cc(161)] Running without the SUID sandbox! See
https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment for more information on developing with the sandbox on.
[0616/110744:ERROR:browser_main_loop.cc(207)] Gtk:
gtk_window_present_with_time: assertion 'GTK_IS_WINDOW (window)' failed
ATTENTION: default value of option force_s3tc_enable overridden by environment.
USER@USER:~$ [Unity Package Manager (Upm)]
Parent process [7583] was terminated

```

and stuck on that....
well i know that there's something wrong with GTK but i have no experiace with it and i didn't find anything useful on this matter on google

> OS: Ubuntu 16.04 LTC

# Answer
"Running without SUID sandbox" -- I've had this too. You need to make sure you have full permissions (777) of the Unity folder and its subfolders and files contained within them.
> 1 votes

---
Tags: unity, linux
---


title: What to use instead of UNet?

text:
# Question
Title: What to use instead of UNet?
If you look at this Link you'll see UNet is deprecated and will be removed in the future.

I'm developing a mobile multiplayer game, i've red official advise about it but they say "You can publish it with 2018.4 (LTS)" and I can't use 2018.4 version because in my project i use LWRP which is not in the 2018.X versions.

I've found the alpha version of the new system right here

My questions are:

1- Should i use the alpha version of the new system? And can i publish my game with it?

2- Should i wait for the new system came out? (I can't wait for months)

3- Should i try to use other third party systems like Photon?

Or is there any way to publish my game with nice multiplayer system?

**Note:** I can't pay for multiplayer matchmaking system. Because of that i want to make Hosting multiplayer game.

# Answer
sure why not Photon2(PUN) is currently the number one platform used by professional studios and developers. As Unet being deprecated by Unity Photon is claiming to be the number one platform to create real-time multiplayer games. Recently Photon changed the implementation in Photon2 with better and optimized and well-structured code.

I think you should use the free version of Photon2(PUN), You can use it very easily and also it is Fast, reliable and scalable.

check these links:

https://www.photonengine.com/ https://www.youtube.com/watch?v=rF2JGhv3Pyo

and also you can learn how to use it with:

https://paladinstudios.com/2014/05/08/how-to-create-an-online-multiplayer-game-with-photon-unity-networking/ https://www.youtube.com/watch?v=evrth262vfs
> 0 votes

---
Tags: unity, multiplayer, unet
---


# Question
Title: Unexpected output from the merging of a quadtree, when that data is converted to Box2D fixtures
I've been staring at this code trying to troubleshoot this for the past 3 days, but I seem to have gone Code Blind. I KNOW the issue is stupidly simple, but I just can't crack the problem.

I'm using a bastardized quadtree to store the terrain for a map. Each node is either full of children, or stores an instance of a tile (position data is saved in the tile). tile stores its AABB (x,y,w,h), and block type (1 = ground, 0 = air/nothing). Later it will store objects and entities as well. Inserting (right now) does NOT cause merging - that is a separate function call.

The darn thing renders properly if drawn to a Pixmap. Which drives me absolutely crazy.

Expected Output (image generated to PixMap from data) :

Output WITHOUT merging (tile width/heigh is 8 pixels), totally as expected :

Output WITH merging (bizzare.) :

UPDATE : I set up a small test, with a 32x32 area, same 8pix base tile size. First image is a 4x4 quadtree grid at 8px size. Second image is 2x2 quadtree at 16px, Third image is 1x1 at 32px size. The red and blue marker is drawn from the physical world camera, is 16x16, drawn at -8,-8 (so the center is at 0,0. The brown is a ground texture - drawn into the phys world camera. For ALL of these images, the quadtree origin is at 0,0. WHAT IS MOVING THE ORIGIN FURTHER AND FURTHER APART?! NOTHING IN MY CODE IS DOING THIS!!?!

Code which I am fairly sure is the problem (from the tile class) PPM is a constant defined elsewhere (Pixels Per Meter), set to 8. This is all rendered through LibGDX :

```
    public void setPhys(World w) {
    if(this.block != 0) {
        this.bdef = new BodyDef();
        NovaLog.debug("bdef.position.set(" + (this.aabb.x / PPM) + ", " + (this.aabb.y / PPM) + ");");
        bdef.position.set(this.aabb.x / PPM,this.aabb.y / PPM);
        bdef.type = BodyType.StaticBody;
        this.body = w.createBody(bdef);

        PolygonShape shape = new PolygonShape();
        NovaLog.debug("shape.setAsBox("+((this.aabb.width / PPM)/2) + ", " +  ((this.aabb.height / PPM)/2) +");");
        shape.setAsBox((this.aabb.width / PPM)/2, (this.aabb.height / PPM)/2);
        this.fdef = new FixtureDef();
        this.fdef.shape = shape;
        this.fixture = this.body.createFixture(fdef);
        this.fixture.setUserData(this);
    }
}

```

And the merge code from the quadnode class (might be problems here, I don't even know any more).

```
protected boolean merge() {

    //Leaves are already merged!
    if(this.isLeaf()) {return true;}

    boolean canMerge = true;
    //If we have child nodes, try to merge them.
    if(c[0] != null) {if(!c[0].merge()) {NovaLog.debug("NW couldn't merge."); canMerge = false;}}
    if(c[1] != null) {if(!c[1].merge()) {NovaLog.debug("NE couldn't merge."); canMerge = false;}}
    if(c[3] != null) {if(!c[3].merge()) {NovaLog.debug("SW couldn't merge."); canMerge = false;}}
    if(c[2] != null) {if(!c[2].merge()) {NovaLog.debug("SE couldn't merge."); canMerge = false;}}

    //If nodes aren't leaf nodes, and we couldn't merge them, return false.
    if(canMerge == false) {NovaLog.debug("Couldn't merge children."); return false; }

    // we should be able to try to merge this node.
    if(c[0].data.equalTo(c[1].data) && c[3].data.equalTo(c[2].data) && c[0].data.equalTo(c[3].data)){
        //Data is identical, WE CAN MERGE.
        this.data.block = c[0].data.block;
        this.c[0] = null;
        this.c[1] = null;
        this.c[3] = null;
        this.c[2] = null;
        //this.setFixture();
        NovaLog.debug("Merge success -> " + this.toString());
        return true;
    } else {
        // Data is NOT identical, we cannot merge!
        NovaLog.debug("Data not identical - ");
        for(int x = 0; x < 4;x++) {NovaLog.debug("" + c[x].data.block);}return false;
    }
}

```

I really doubt there's an issue here, but just in case...

```
protected boolean subdivide() {
    NovaLog.info("SUBDIVIDING : " + this.data.aabb.toString());
    //we cannot split this node if it has items or entities in it.
    if(!this.data.items.isEmpty() || this.data.entity != null) {
        NovaLog.error("cannot subdivide! ERROR!");
        return false;
    }

    float w = (float) (data.aabb.width / 2d);

    if(c[0] == null) {

        AABB aabbNW = new AABB(new Vector2(data.aabb.x,data.aabb.y), w, w);
        c[0] = new QuadNode(aabbNW, this);
        NovaLog.debug("NW = " + aabbNW.toString());

    }
    if(c[1] == null) {
        Vector2 xyNE = new Vector2(data.aabb.x + w, data.aabb.y);
        AABB aabbNE = new AABB(xyNE, w, w);
        c[1] = new QuadNode(aabbNE, this);
        NovaLog.debug("NE = " + aabbNE.toString());

    }
    if(c[2] == null) {
        Vector2 xySW = new Vector2(data.aabb.x, data.aabb.y + w);
        AABB aabbSW = new AABB(xySW, w, w);
        c[2] = new QuadNode(aabbSW, this);
        NovaLog.debug("SW = " + aabbSW.toString());

    }
    if(c[3] == null) {
        Vector2 xySE = new Vector2(data.aabb.x + w, data.aabb.y + w);
        AABB aabbSE = new AABB(xySE, w, w);
        c[3] = new QuadNode(aabbSE, this);
        NovaLog.debug("SE = " + aabbSE.toString());

    }
    return true;
}

```

At this point, I'm a Westworld Host looking at something that could do harm to his psyche - "It doesn't look like anything to me." Please help - the bruise on my forehead from banging my head against the wall is growing larger.

# Answer
> 1 votes
Apparently, whatever local origin is set in the default Shape.setAsBox() IS WRONG, or at least wrong for the use I'm using it as.

There is a longer version of setAsBox that allows you to set the Center of the shape...and putting in the simple halfwidth of the node, in each part of the vector leads to...properly aligned boxes. Why this is required, when you set position in the body def, i have absolutely no idea.

Corrected line :

```
shape.setAsBox((float)((this.aabb.width / PPM)/2.0f), (float) ((this.aabb.height / PPM)/2.0f), new Vector2((float)(this.aabb.width/2.0f)/PPM,(float)(this.aabb.width/2.0f)/PPM), 0.0f );

```

Results :

---
Tags: java, libgdx, box2d, quadtree
---


# Question
Title: how do i clamp my camera's rotation on X and Y?
i'm using a script to make my camera rotate smoothly toward the mouse cursor on the screen. and the only thing i need is to somehow clamp it's rotation on X and Y. here :

```
 public float Xspeed = 2.0f;
 public float Yspeed = 2.0f;
 private float yaw = 0.0f;
 private float pitch = 0.0f;
 public float minimumX = -20f;
 public float maximumX = 20f;
 public float minimumY = -45f;
 public float maximumY = 45f;
 public float damping = 2.0f;
 void Start()
 {

 }

 // Update is called once per frame
 void Update()
 {
     ///////// looking
     yaw += Xspeed * Input.GetAxis("Mouse X");
     pitch -= Yspeed * Input.GetAxis("Mouse Y");

     var desiredRotQ = Quaternion.Euler(pitch, yaw, 0);
    transform.rotation = Quaternion.Lerp(transform.rotation, desiredRotQ,
    Time.deltaTime * damping);
 }

```

# Answer
I found a way to clamp it.

```
public float Xspeed = 2.0f;
public float Yspeed = 2.0f;
float currentHeadRotationX;
float currentHeadRotationY;
public float minimumX = -20f;
public float maximumX = 20f;
public float minimumY = -45f;
public float maximumY = 45f;
public float damping = 2.0f;

void Start()
{

}
void Update()
{
    Vector2 mouseInput = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));

    currentHeadRotationX = Mathf.Clamp(currentHeadRotationX - mouseInput.y * Xspeed, minimumY, maximumY);
    currentHeadRotationY = Mathf.Clamp(currentHeadRotationY + mouseInput.x  * Yspeed, minimumX, maximumX);

    var desiredRotQ = Quaternion.Euler(currentHeadRotationX, currentHeadRotationY, 0);
    transform.rotation = Quaternion.Lerp(transform.rotation, desiredRotQ, Time.deltaTime * damping);
}

```
> 0 votes

---
Tags: camera, rotate
---


# Question
Title: How to remove an element from the scene while keeping it in array?
I combined cube meshes to make a big one. I stored the info of every cube in an array within a list of chunk. Now i want to delete the cubes in the scene to only keep the combined result, but without deleting the elements in the array. After combining meshes, i want to be able do destroy cube from it. So i want to keep the info so when i click the mesh, i get the position of the cube that would be there and check if it matches wit ha cube from the array. If it does, i want to remove it from the array and regenerate the mesh without that deleted cube.

How would I do that ?

# Answer
If you want to keep the whole cube game object around after merging the meshes so you can restore them later, then it would be better to deactivate it with `gameObject.SetActive(false)` instead of destroying it. That way it stays in memory as it is and you can later reactivate it with `SetActive(false)`.

However, for your particular use-case, that might be overkill. You would keep a lot of data about the gameObject in memory which you don't need and end up wasting a lot of RAM. All you really need to store are the coordinates of the cube within the larger merged mesh. So it would be better to define a `struct` which holds only the data you need about a merged cube and create an array of those struct's which you store on a component of the merged mesh.
> 1 votes

---
Tags: unity, 3d-meshes, gameobject, scene
---


# Question
Title: TextMesh Pro conflict in Unity2019.1.5f1
I'm having an issue with Textmesh Pro in my project. I originally got it from the Asset store a few months ago. More recently, I deleted it and downloaded it from the Package Manager. However, now in my scripts I'm getting the following error when using TextMeshPro class in my scripts:

> The type 'TextMeshPro' in '/Users/unityj/Documents/unity vscode/VSCode/FirstGame/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Runtime/TextMeshPro.cs' conflicts with the imported type 'TextMeshPro' in 'Unity.TextMeshPro, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in '/Users/unityj/Documents/unity vscode/VSCode/FirstGame/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Runtime/TextMeshPro.cs'. (CS0436) \[Assembly-CSharp\]

Tried to uninstall the package via package manager, deleting the package folders, deleting everything that mentions 'TextMesh Pro' and 'TMPro', reimporting all, and reinstalling, but I still get the error. Once TextMesh Pro is uninstalled, the class can't be accessed.

Asset Serialisation mode is set to 'Force Text' and I've set .Net4.x in the Player Settings

Making a new project does not replicate the problem, so I know it's a problem specific to my project, but I don't know where to start. Any suggestions would be appreciated.

# Answer
I found a similar Stack Overflow question Compiler error after importing TextMesh Pro with the same error message as you. See this answer by Jasil:

> Which version of unity are you using. If it 2018.2 or above you don't need to download from asset store its already part of unity. you can check from window \> package manager

And see the comment there by Tricko:

> I experienced this when I tried to update my project using 2018.3. You just need to delete the TextMesh Pro files from the old version, and I believe you have to do some re-mapping in case you are already using TMP from the old version.

---

There are also recommended steps for upgrading to the Package Manager version of TextMesh Pro from the Asset Store version. See Is there an upgrade path from Asset Store to package manager for TextMesh Pro? (From what I recall I had a slightly different error message when upgrading but I thought I would link this just in case it helps.)
> 1 votes

---
Tags: unity, c#
---


# Question
Title: How to address players struggling with simple controls?
I have an HTML game I built with Phaser 3, and I can't decide what to do with the controls. I've changed them several times, and now I feel like I've hit a sweet spot between usability and fun. However, I still see people struggle.

The game involves a boy with a slingshot that can be pulled back and fired to knock the enemy's head off. There are two virtual buttons on both side of the screen that are tapped to turn the character. I'm considering having the character turn automatically, so that the slingshot is the only mechanic involved and the game can be picked up and played without instructions. However, I feel like this will destroy the whole point of being fast to turn and shoot the enemy.

Should a simple game like mine require instructions, or is usability more important?

# Answer
> 28 votes
Are your test player having trouble discovering the controls or using them?

If they have trouble discovering them, you can add a prompt that explains them. To make it unobtrusive for players that don't need it, you can have it appear if the player stays there doing nothing.

Which, brings me to the next thing: probably all your game needs is a practice/creative/free mode, where players feel free to experiment with the controls without any pressure. That will get them used to the controls in the case that the trouble is using them and not discovering them.

While a game can do well without instructions or tutorials, they could help you reach more people (because not everybody is keen on experimenting without an example or guidance).

*Usually I would say that you should let the player configure the controls. However, I recognize that that does not make sense for every game and input device. With that said, consider if you need sensitivity options.*

There is also an argument for allowing for a simpler control scheme which will allow players who struggle to beat the game (a kind of assist mode, you can let the player know that it is not the intended way to play, yet it can allow them to enjoy the game anyway if they are having trouble). And this can be implemented without a lose of depth if the full controls are required to get high-scores.

---

**Addendum**

If you are going for a tutorial, the player does not need to notice it. Examples such as NES Mario (which Philipp explains, you might also be interested in Super Mario 3D World's design philosophy) and Megaman X (which is f■■king genius) are great case studies. A more recent example is Portal, which is tutorial for the most part.

See How to Design a Good Game Tutorial.

---

On the other hand, if you are thinking about tweaking the difficulty, consider that "Hard" does not have to mean (although it often means):

* Punishing (you fail, you lose a lot of things)
* Tedious (it takes a lot of time to get things)
* Inaccessible (hard to understand or control)

Instead, "Hard" can mean challenging. That way, Hard can be fun. Separate challenging from difficult, and you can increase challenge by adding rewards that require more skill, without making completing the game harder.

*In fact, who says difficulty is a single dimension concept?*

Thus, if you are increasing accessibility, you are not necessarily making an "easy mode". The game can remain hard (challenging). I want you to consider the concept of an assist mode.

---

To be honest, it is a bit of a branding issue. You see, some games lie to you (have hidden mechanics) as a mean to tweak difficulty. Usually to make it less punishing, however sometimes to make the content last longer (more tedious).

Difficulty in games has lowered in some parts of the industry, and accessibility is blamed for it (even though it is not the only factor). Also, some people want challenge※ and some people want to relax※※... there is no perfect difficulty.

※: Some games keep you engaged the whole way, they often throw unexpected twists to the player, have your adrenaline rush, your heart pumping, and huge dopamine rewards. Yeah, too easy might not be good.

※※: Some games allow you to get in the zone, archive a semi-meditative state as your mind is freed while you body just does the motions - rhythm games are good at this, also crowd-combat fighting games (no, repetition does not have to ruin the game)... Other are fun because they act more like sandboxes, they are more toys than games, where the fun comes from finding creative and amusing ways to do things. Yeah, too hard does not help either of that.

*And then there are games that mock the player for picking an easy mode, failing or quitting.*

# Answer
> 23 votes
There are some games which pulled off the "silent tutorial" thing pretty well. The basic rules are:

* Introduce game elements one at a time
* Introduce them with as little distraction as possible
* Introduce them in a way that it is impossible or at least very difficult for the player to *not* do what they are supposed to do and discover the mechanic on their own.

A good example for a silent tutorial is the first level of the original Super Mario Bros for the NES. From the perspective of todays gamers, the game mechanics seems obvious. But remember the situation of their players back then. For most of their audience it wasn't just the first platformer they ever played but in fact the very first video game they saw at all. So they had to expect that their audience came to the game with absolutely zero knowledge. That meant a good tutorial was crucial. Did they open the game with a long text explaining to the player what to do? No, they just threw them from the title screen into the game:

1. The player starts at the left side of an empty screen. There is just one thing the player can do: press right to start walking. This teaches the player the very first rule of the game: "move right to progress".
2. Then the player encounters the first enemy walking right towards them. Most players actually run into the goomba and lose on their first run. This teaches the player the second rule of the game: "Do not run into any creatures you meet".
3. At the next try, the players will discover that they can jump. They will jump over the enemy. This teaches rule number 3: "Your primary method to solve problems in this game is by jumping over them".
4. Interestingly, the most convenient pattern to avoid that gooba makes the player jump into the first question mark block and receives a coin. So the player already learns another mechanic: "Jump against the question mark blocks from below and good things happen to you".
5. There are more question mark blocks for the player to apply that knowledge. They are grouped with the rock blocks which do not react at all to the player jumping against them. This teaches the player "There are different blocks in this game, and they react differently when you jump at them".
6. One of the question mark blocks releases a mushroom. The player does not yet know that the mushroom is good for them. It might just as well kill them like the goomba did. But it moves in a way that it is very difficult for the player to avoid it. Most players do touch it, and are surprised that it doesn't just leave them alive, it actually does something good: Their character grows. This teaches the player: "Not everything that moves hurts you. Mushrooms are good".

And the game teaches all that in just the first minute of gameplay without a single word of explanation.

There is a lot more the first level teaches the player in ways they don't even realize they are being taught, including the existence of secrets, common jumping patterns, koopa shells, fire flowers, stars and many more. Analyzing that whole level and figuring out why the designers placed things the way they did can be an enlightening experience in tutorial design.

I am looking forward to learning how to play your game.

# Answer
> 7 votes
Although I like the other answers, I think nobody mentioned the most important: It all depends on your target audience.

Do you target people who are gamers? They play games regularly and your game would be familiar to them? Then most likely you wouldn't need anything more than a simple screen hidden behind a button that explains the basics. (Just in case someone misses something)

Do you target a broader audience? Maybe children too that have no experience in games? Then yes, you'd need some sort tutorial, instructions, otherwise you risk the user getting overwhelmed and giving up.

Having said that, I'm a person that hates the tutorials that "grab the user by their hand" and ask them to click on buttons while everything else is disabled. I like when playing the game is the tutorial by itself, like the original Super Mario, where the stage itself was teaching you what is an enemy, what is a block, what happens when you interact with them, and learning how to jump. It's up to you how you want to approach it.

# Answer
> 1 votes
this can be a very general question and depends on game design. most of players hate hints and tutorials but most of the time its needed to add the pace of learning in the game. you have to find the best way to introduce your game to the player. sometimes a cheetsheet in loadings is enough some times you have to give the data step by step. think about your design

# Answer
> 0 votes
How much in-person user testing have you done? You can theorycraft all day long on why might be happening but there's nothing like seeing it for yourself what they are stumbling on. Then you can tweak as needed and repeat the user testing (with new players.)

Even you you use heat-mapping for remote testing, in-person you can see the player body language, where he is looking and often they will voice out loud what they are thinking. Most big cities have game development meetup and they are the perfect venue for that.

---
Tags: game-design, game-mechanics, control, tutorials, usability
---


# Question
Title: How can I find the opposite angle and position of the camera?
In this project I have a character and a camera that follows it.

**The camera has a position relative to the character that was defined as (x = 0, y = 0, z = 0) and also its rotation:**

**I found a value close to its position and opposite angulation, but not really the correct value:**

**By pressing the Q key, the camera shifts to the position and angulation that I have discovered. Releasing the Q key, the camera returns to its initial position:**

**IN GAME:**

As you can see, the inversion is not 100% correct.

**One of the ways I thought, is a way where I take this relative value from the camera (x = 0, y = 0, z = 0) and with that:**

*I put the character's mesh at the location (x = 0, y = 0, z = 0) at the level and so, as the camera will be (for example) x = -250, y = 0, z = 300, it's just I invert the value of x. The angulation is simpler to deduce, but it would be interesting for me to also derive its relative value (0, 0, 0).*

---

**EDIT 1** (*Attempt that I did and that almost worked out*)

**By clicking the down arrow to the left of the values, you can select whether you want the variable to be *Relative* or *World* (I did not know that):**

**Before it was all 0, it now has a value:**

**Taking the minus sign, I was able to figure out the opposite position:**

**New position:**

**It happens that at the time of changing the angulation from relative to absolute, a conversion is not made:**

**I can not get absolute value equivalent to relative. What happens is that the value 0, 0, 0 is also defined for the absolute rotation. In the image below the camera was exactly in the same position as the VR camera:**

**I discovered by trial and error the equivalent angulation between relative and absolute:**

**BLUEPRINT:**

The code works correctly, but I feel that again I did not get exactly the position and opposite angles.

**Here are some screenshots of the game:**

**Local X with NORMAL CAMERA:**

**Local X with OPPOSITE CAMERA:**

**Local Y with NORMAL CAMERA:**

**Local Y with OPPOSITE CAMERA:**

*Note that in the **opposite camera** you can see the end of the world (sky) from wherever you are, which is not the case with the **normal camera**. I noticed this, and so, I think once again I did something wrong.*

# Answer
To get the correct result, I had to make the **Spring Arm** simpler/understandable.

**Initial Spring Arm:**

**Modified Spring Arm:**

**I set the location and angulation of the normal camera:**

**I recommend setting all values of rotation to 0 after finding the inverse position of the camera:**

**I recommend furthermore only modify the values by the details tab. Do not use the E shortcut and set the rotation with the mouse (errors happened to me):**

**Then just find the reverse rotation in the necessary axes:**

* X axis, for the camera does not stand upside down.
* Y axis, in this case is the inverse angulation at 45º.

**Superimposed normal and inverse camera images:**

See that the character remains in the same place in the two images, so the location and angulation were defined correctly.
> 0 votes

---
Tags: camera, unreal-4, angles
---


title: Game area where I can not click?

text:
# Question
Title: Game area where I can not click?
I created a project based on the Top Down Example.

What is happening is that there is an area just above my character where I can not click.

**Image showing location where the mouse is and soon after, when I move it a little to the left it disappears:**

By the minimap you can see that the game recognizes as if the mouse was on top of the character, very close.

**I went to test to see if this happened in all Top Down Examples, but it does not happen:**

I've modified the position of the camera a bit in this project where I'm having problems (**image 1**). Is there a non-clickable area defined based on the camera, to prevent the player from clicking the location where the character is? And with the change of position the area is no longer equivalent to the position of the character?

**This area in red I can not click:**

**I have not changed anything that has to do with the mouse in the character's blueprint:**

What is going on?

---

**EDIT 1 (tests done based on some comments to clarify the question and to verify possible cause of the problem)**

**I pressed P to see if there was any area of the map where there could be no click:**

**See I can put my mouse right below the character, and even click:**

**From there up the mouse does not appear, and obviously I can not click:**

**Location where the mouse appears again and what I can click:**

These 3 images were captured in the character's home position without moving it. But the problem persists wherever the character is.

**Through the test I did below, I prove that the problem is directly related to the position the character is in:**

The green question marks the spot where my mouse is.

---

**EDIT 2 (I think I discovered the problem)**

I read DMGregory's comment again and went to look at the collider, it was small and it already existed before the problem happened.

**I started the game and paused. I came across this image:**

I created this sprite to appear on the minimap, I believe that may be the cause of the problem. How to make the mouse skip it? Without having to simply upload it?

# Answer
As I put in the second edition of the question, the mouse click was not working as it ended up being blocked by the sprite.

**I did not know what was happening because I selected the option where the owner did not see the sprite (the sprite is only useful for the minimap):**

Only thing I did was climb the sprite to the point where it is not seen by the camera that follows the character.
> 0 votes

---
Tags: unreal-4, blueprints
---


# Question
Title: WebGL Freeze for some minutes after loading asset bundle
I have to **Load/Unload models from a specific URL based on player position**. For this reason I am checking player position from model and then load/unload related piece of model in a `Update` event which runs on every frame.

Here is the update, that validating some checks before loading/unloading. I added this check for optimization purposes as the main loading/unloading loop is heavy:

```
 private void Update()
 {
     //If this feature is disable don't load/unload
     if (enableThisFeature == false) return;

     //if player is moving, dont load//unload
     if (Input.GetAxis("Horizontal") != 0 || Input.GetAxis("Vertical") != 0)
     {
         //do nothing when player is moving
         return;
     }

     DeactivateDistantTiles();
 }

```

After this I am checking player position and calling model load/unload:

```
private void DeactivateDistantTiles()
{
    playerPosition = transform.position;
    playerPosition = cameraController.currentActiveCam.transform.position; //transform.position;

    checkPlayerPositionChangeing = playerPosition.z != playerLastPos.z || playerPosition.x != playerLastPos.x;

    if (checkPlayerPositionChangeing)
    {
        ABLoadUnloadLoopCall();
    }

    playerLastPos = cameraController.currentActiveCam.transform.position;

}

Vector3 tilePosition;
float xDistance;
float zDistance;

public void ABLoadUnloadLoopCall()
{

    //old
    //foreach (SingleABLoader tile in tiles)
    //{
    //    Debug.Log("ABLoadUnloadLoopCall 123");
    //    Vector3 tilePosition = tile.gameObject.transform.position + (tileSize / 2f);

    //    float xDistance = Mathf.Abs(tilePosition.x - playerPosition.x);
    //    float zDistance = Mathf.Abs(tilePosition.z - playerPosition.z);

    //    if (xDistance + zDistance > maxDistance)
    //    {
    //        /*If you don't want to destroy the object on unload then use below line otherwise use DestroyBundleObject with true pararmeter */
    //        //tile.DestroyBundleObject();
    //        tile.DestroyBundleObject(true);
    //    }
    //    else
    //    {
    //        tile.StartDownloadingAB();
    //    }
    //}

    //new
    for(int i = 0; i < tiles.Length; i++)
    {
        tilePosition = tiles[i].gameObject.transform.position + (tileSize / 2f);

        xDistance = Mathf.Abs(tilePosition.x - playerPosition.x);
        zDistance = Mathf.Abs(tilePosition.z - playerPosition.z);

        if (xDistance + zDistance > maxDistance)
        {
           /*If you don't want to destroy the object on unload then use below line otherwise use DestroyBundleObject with true pararmeter */
           //tiles[i].DestroyBundleObject();
           tiles[i].DestroyBundleObject(true);
        }
        else
        {
            tiles[i].StartDownloadingAB();
        }
    }
}

```

I found that `ABLoadUnloadLoopCall` making GC allocation in KBs in every frame which is very high (i think this is a problem, maybe i am wrong). So is there any way available that my above code optimize and make less allocation. My initial research suggest to use `For` loop instead `foreach` therefore in `ABLoadUnloadLoopCall` I am using for loop instead `foreach` but **still my game lag/freeze for some minutes after loading the model/asset bundle.** The lag/jerky/freeze usually disappear after some minutes/seconds of asset bundle loading.

**Edit:** Some More Code Snippet Added. Here is the Bundle/Model loading Code. Whenever a asset bundle download is require it add the download in a queue which later process one by one.

```
public void StartDownloadingAB()
{
    if (BundleLoadStatus == BundleLoadStatusEnum.bundleNotLoadedYet)
    {
        BundleLoadStatus = BundleLoadStatusEnum.bundlesLoading;
        enqueTheABDownloading.EnqueABDownloading(this);
    }

}

//actual code the download the bundle.
public IEnumerator DownloadAB()
{

    if (isBundleLoading == true)
        yield return false;

    BundleLoadStatus = BundleLoadStatusEnum.bundlesLoading;
    isBundleLoading = true;

    www = UnityWebRequestAssetBundle.GetAssetBundle(finalABLoaderURL);
    yield return www.SendWebRequest();

    if (www.error != null)
    {
        Debug.LogError("assetBundleURL : " + finalABLoaderURL);
        Debug.LogError("www error : " + www.error);
        www.Dispose();
        www = null;
        yield break;
    }

    bundle = ((DownloadHandlerAssetBundle)www.downloadHandler).assetBundle;

    AssetBundleRequest bundlePrefabAsync = bundle.LoadAssetAsync(bundle.name, typeof(GameObject));
    yield return bundlePrefabAsync;

    // if we got something out
    if (bundlePrefabAsync != null)
    {
        //First Off the Origin Shifting
        environmentOriginSetter.EnvironmentOriginSetterFeatureActive(false);//TODO
        //assetBundleToLoadObj = (GameObject)Instantiate(bundlePrefab);

        //Then Instantiate the Bundel Object and make it child to environment parent object.
        assetBundleToLoadObj = Instantiate(bundlePrefabAsync.asset as GameObject);
        assetBundleToLoadObj.transform.parent = envParent.transform;
        //assetBundleToLoadObj.transform.parent.transform.position = this.transform.localPosition;//new

        //Then Enable the Origin Setter feature again
        environmentOriginSetter.EnvironmentOriginSetterFeatureActive(true);
    }

    www.Dispose();
    www = null;

    // try to cleanup memory
    //Resources.UnloadUnusedAssets();//TODO open if memory problem occur
    bundle.Unload(false);//TODO open if memory problem occur
    bundle = null;

    isBundleLoading = false;
    BundleLoadStatus = BundleLoadStatusEnum.bundlesHasLoaded;
}

```

For Unloading, I am destroying the object

```
public void DestroyBundleObject(bool isDestroy)
{
    //bundle was loaded completely, write a bool, if it is true then loaded completely
    //bundle is loading, isBundleLoading
    //bundle is not load yet,

    if (bundleObjectsDeleted == false && BundleLoadStatus == BundleLoadStatusEnum.bundlesHasLoaded)
    {
        bundleObjectsDeleted = true;
        if (assetBundleToLoadObj)
        {
            Destroy(assetBundleToLoadObj);
        }
        BundleLoadStatus = BundleLoadStatusEnum.bundleNotLoadedYet;
    }
}

```

Before loading the bundle/Model, I Enque the desired bundle in a list and download it one by one.

```
public void EnqueABDownloading(SingleABLoader abToDownload)
{
    if (!singleAbLoader.Contains(abToDownload))
    {
        Debug.Log("Enque " + abToDownload.gameObject.name);
        singleAbLoader.Enqueue(abToDownload);

        if (isDownloadStarted == false)
        {
            StartCoroutine(StartDownloading());
        }
    }
}

public IEnumerator StartDownloading()
{

    isDownloadStarted = true;
    Application.runInBackground = true;//enforce background loading.
    imgBlockClicks.SetActive(true);
    textLoading.SetActive(true);
    loadingSlider.gameObject.SetActive(true);

    while (singleAbLoader.Count > 0)
    {
        float sliderIncrementValue = 1f / singleAbLoader.Count;

        SingleABLoader singleAbLoaderCurrent = singleAbLoader.Dequeue();
        Debug.Log("Starting to call " + singleAbLoaderCurrent.gameObject.name);
        yield return singleAbLoaderCurrent.DownloadAB();
        Debug.Log("Finsihed to call " + singleAbLoaderCurrent.gameObject.name);
        //Debug.Log("Finished next loop");
        //singleAbLoaderCurrent.CallDownloadAB();
        //Debug.Log("download call for "+ singleAbLoaderCurrent.name);
        loadingSlider.value = sliderIncrementValue;
    }

    isDownloadStarted = false;

    textLoading.SetActive(false);
    imgBlockClicks.SetActive(false);

    //Application.runInBackground = false;
    loadingSlider.gameObject.SetActive(false);
    loadingSlider.value = 0;
}

```

I tried to profile on editor and found something like this:

**My recent test suggest that the error is occuring in FireFox and chrome while Edge is running fine.**

# Answer
The error was critical, no one able to answer this despite setting the bounty. Anyway the problem is resolve thanks to unity forum, thanks to JJ Johan. The Problem was **shader compilation**.

> If I used **GPU instancing** it would cause a very long freeze the first time a mesh was rendered with that shader, only in the web build (and only WebGL 2 since it isn't supported in WebGL 1)

**Note:** The issue was not encounter in MS Edge browser even with the gpu instance checked property in shader.
> 0 votes

---
Tags: unity, c#, webgl, assetbundle
---


# Question
Title: OpenGL C++ Drawing particles instanced performance
In my 2D Game Engine I'd like to reduce the amount of draw calls. I used to do a draw call for every particle, which yields worst performance.

I've tried instanced rendering in OpenGL but my performance didn't change ( and the particles were only drawn every few frames). Every particle emitter has a Vertex Buffer for the model matrix & color of every particle. The buffers memory is preallocated with the max amount of particles. During rendering all active particles are collected and the data send to the GPU via glBufferSubData.

My instanced rendering looks like this

```
set projection & view matrix as uniforms
for ( emitter : particleEmitters)
    glBindVertexArray(emitter.VAO)
    emitter.GetTexture().Bind()
    std::vector<glm::mat4> models; // collect all model matrices
    std::glm::vec4> colors;        // collect all colors

    for( activeParticle : emitter.activeParticles())
       models.push_back(activePartile.modelmatrix)
       colors.push_back(activeParticle.color)

    if(models.size() > 0)
      // fill model matrices buffer
      glBindBuffer(GL_ARRAY_BUFFER, emitter.modelVBO);
      glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(glm::mat4) * models.size(), &models[0]);

      // fill color buffer
      glBindBuffer(GL_ARRAY_BUFFER, emitter.ColorVBO);
      glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(glm::vec4) * colors.size(), &colors[0]);

      glDrawArraysInstanced(GL_TRIANGLES, 0, 6, models.size());

      // Unbind and other stuff...

```

And the initialization of the buffers

```
ParticleEmitter::ParticleEmitter()
{
    // Set up mesh and attribute properties
    GLuint VBO;
    GLfloat particle_quad[] = {
        // Pos      // Tex
        -0.5f, 0.5f, 0.0f, 1.0f,
        0.5f, -0.5f, 1.0f, 0.0f,
        -0.5f, -0.5f, 0.0f, 0.0f,

        -0.5f, 0.5f, 0.0f, 1.0f,
        0.5f, 0.5f, 1.0f, 1.0f,
        0.5f, -0.5f, 1.0f, 0.0f
    };
    glGenVertexArrays(1, &this->m_vao);
    glGenBuffers(1, &VBO);
    glBindVertexArray(this->m_vao);
    // Fill mesh buffer
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(particle_quad), particle_quad, GL_STATIC_DRAW);
    // Set mesh attributes
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)0);

    // setup model matrices buffer
    glGenBuffers(1, &modelVBO);
    glBindBuffer(GL_ARRAY_BUFFER, modelVBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(glm::mat4) * maxParticles, nullptr, GL_DYNAMIC_DRAW); // allocate space for max amount
    {
        GLuint location = 2;
        GLint components = 4;
        GLenum type = GL_FLOAT;
        GLboolean normalized = GL_FALSE;
        GLsizei datasize = sizeof(glm::vec4);
        char* pointer = 0;
        GLuint divisor = 1;

        for (int c = 0; c < 4; ++c)
        {
            glEnableVertexAttribArray(location + c); //location of each column
            glVertexAttribPointer(location + c, components, type, normalized, datasize, pointer + c * sizeof(glm::vec4)); //tell other data
            glVertexAttribDivisor(location + c, divisor); //is it instanced?
        }
    }

    // setup color buffer
    glGenBuffers(1, &ColorVBO);
    glBindBuffer(GL_ARRAY_BUFFER, ColorVBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec4) * maxParticles, nullptr, GL_DYNAMIC_DRAW); // allocate space for max amount
    {
        GLuint location = 1;
        GLint components = 4;
        GLenum type = GL_FLOAT;
        GLboolean normalized = GL_FALSE;
        GLsizei datasize = sizeof(GLfloat);
        char* pointer = 0;
        GLuint divisor = 1;
        glEnableVertexAttribArray(location); //location of each column
        glVertexAttribPointer(location, components, type, normalized, datasize, pointer); //tell other data
        glVertexAttribDivisor(location, divisor); //is it instanced?
    }

    glBindVertexArray(0);
}

```

Since the particles are drawn for only ~10 frames in a 60frame cycle (but correctly) , I assume my layout is somewhat wrong.

Why are the particles not drawn every frame?

@edit: After commenting out the whole section about glBufferSubData and glDrawArraysInstanced the performance didn't change. The performance killer is in fact the calculation of the model matrix on the CPU for every active particle

# Answer
Found my mistake at the initialization of the color buffer.

instead of

```
 GLsizei datasize = sizeof(GLfloat);

```

it should be

```
GLsizei datasize = sizeof(glm::vec4);

```
> 2 votes

---
Tags: opengl, 2d, particles, instancing, vertex-buffer
---


# Question
Title: How to make player land on platforms more than one in pygame
I'm trying to make multiple platforms (blocks) on screen on which player can jump and land on it. When I just keep only one block, player jumps on it and land easily. But when I create other platform and player jumps, it gets hit by the block and goes below on the map. But if I try to jump over other platform, it lands on the surface easily.

What I tried so far,

I forgot to add these lines,

```
        # Checking Collision of Platform and Hero
    self.obstacleHit_or_not(self.hero, self.platform, 460)
    self.obstacleHit_or_not(self.hero, self.platform1, 460)
    self.obstacleHit_or_not(self.hero, self.platform2, 460)

    # This function works for Blocks only
def obstacleHit_or_not(self, hero, platform, position):
    hit = pygame.sprite.collide_rect(hero, platform)

    if hit:
        #print("ITS HITTING")
        hero.y = position
        print("hero.y - ", hero.y)

    elif hero.y == position:
        #print("HITTING INSIDE OF 450")

        while True:
            hero.y += 5
            if hero.y >= 625:
                break

```

# Answer
First, instead of storing each platform as a member in class, do it like this:

```
self.platforms=[Platform(200, 550), Platform(600, 550), Platform(1000, 550)]

```

It's the list of all platforms in the game. By storing them in the list, you'll be able to easily add or remove them. Do the same for each object that's going to be more than one in the game (coins, enemies, etc).

Now, for the collision checking. Let's change the obstacleHit\_or\_not method to return True if any of the platform present in self.platforms is hit, False otherwise.

```
def obstacleHit_or_not(self, hero, platforms):
    for platform in platforms:
        hit = pygame.sprite.collide_rect(hero, platform)
        if hit:
            return True
    return False

```

Change other collision checking functions to look like this one. If you need the information about which platform has been hit, you can "return platform" if hit, "return None" if not.

Now, depending on what your collision function returns, you'll have to update the player's position/velocity accordingly.

Generally the game loop looks like this:

1. Get system events (keyboard, mouse, etc)
2. Get collision information for all moving objects
3. Update velocity of each moving object, according to collision information
4. Update the position of each moving object,
5. Draw the frame

Collision checking should do only that - check if the object is colliding. It's not its job to tell the player to stop phasing through the platform d;
> 1 votes

---
Tags: collision-detection, python, pygame
---


title: Synchronize points from UI and server

text:
# Question
Title: Synchronize points from UI and server
I am sorry in advance if it's not perfectly clear.

I would like to make a game with let's say the following map (in real it will be a 3D globe).

Now this map contain point, and each point is a place where user can build stuff.

The distance between point is very important, and also, the location of each one of them (not on water and equally distant to each others)

The problem I face, is I don't know how to sync the point with the server. explaining :

I want the point to be equally distant between each others, and only on lands. Generate them is easy from the game itself. but since the game will have a server that control what is build on each case by multiple player, I should generate them in the server. but I don't know how can I do this. since only the game itself know the map and where it can place the point.

Should I generate them in the game, than copy the amount I can fit and write it in the server like if i can fit 200points, I make the server generate 200 points with id from 0 to 200 and the UI will draw them in order ?

I need a little help to find the good direction to explore.

Thank you

# Answer
> 1 votes
# Client-side generation

It seems to be the easiest way for you, because

> Generate them is easy from the game itself.

It's usually synchronized by using the same **random seed generated by the server**. It reduces the load on your server, because it does not have to execute a (probably) expensive generation algorithm and transfer a (probably) large volume of data to clients.

You should generate a seed and send it to clients. On client side, reseed the RNG and generate the map. Because seeds are the same, maps will be the same too.

# Server-side generation

It will be useful if, for example, you don't want to reveal the entire map to players and their hacked clients. It's somewhat harder because

* The server may be written on another language, so you have to port your generation algorithm and make no bugs;
* You must optimize generation, transferring and storing maps. If you have an algorithm that takes 5 seconds on client machine, imagine what happens if 100 players decide to start a game. But if there are no such bottlenecks, there is no need to optimize.

---
Tags: architecture, client-server, server, synchronization
---


# Question
Title: Do I have to explain the mechanical superiority of the player-character within the fiction of the game?
For quite a while I wonder how to formulate this concept, which seems to be common, yet barely addressed within games. It is about the concept of **player controlled characters (PC)** being consistently superior to generic **non-player controlled characters (NPC)**. This also must not depend on the actual **player skill** (defined as what the player can actively do), and instead be inherent to the PC itself.

Now for RPGs it's usually something like destiny, magic, superior skill, backstory, better (enchanted) equipment, having a rare power.

But what if it's about space ships with equal size, type and equipment? How could I explain that a player can repeatedly and easily grind through 5-10 space ships which he himself is using without having much room for player skill due to weapons and thrusters working automatically? Effectively pushing a button to start attacking just as his opponents are doing. *Let's say it's the early phase of the game, just to keep this abstract. Also let's assume a standard, futuristic setting with no special lore-based elements like psi powers or crystals.*

**What guidelines or concepts exist which can be used to justify PC superiority in general? In a mathematical sense, do I have to explain -75% damage taken and +300% damage dealt as baseline for all PCs in a credible way? Or is that a silently accepted premise of games in general?**

# Answer
You might not have to.

When a player consistently wins against seemingly bad odds, they are far more likely to attribute it to their skills as a player than to having a mechanical advantage. You rarely have to justify generosity to the players. They will just handwave it and move on with the game. Quite a lot of games are doing this.

Often you design the gameplay and encounters the way you want them to be and then adjust the difficulty by tweaking the relative damage output of the PC and NPCs. If the game has to give a 12x mechanical advantage to the player to be winnable, so be it. And when you aren't sure whether your game is too easy or too hard, you just offer multiple presets to the player and call them difficulty setting.

On the other hand, if your game is very simulationist, very transparent regarding the math used to resolve combat and it seems implausible within the narrative of your game for the player to be so much better than their opponents, then it might still be too obvious for the player how much you are cheating in their favor. In that case consider another option: Just give the player easier challenges in the early phase of the game. Don't give them the worst ship in the game with the worst equipment. Give them the second worst ship with decent equipment and put the enemies in the starting area into the worst space clunkers possible.

I am looking forward to using my "superior skills" (*cough*) as a spaceship captain to win some awesome space battles in your game.
> 38 votes

# Answer
> What guidelines or concepts exist which can be used to justify PC superiority in general? In a mathematical sense, how can I explain -75% damage taken and +300% damage dealt as baseline for all PCs in a credible way? Do I have to do it at all or is that a silently accepted premise of games in general?

I mean some games do essentially just that with no given explanation. Take Dynasty Warriors for example the controlled character just does way more damage than the ai controlled allies. Despite potentially swapping characters with your AI friends in the next battle. People just accept it or attribute to 'skill' at this point.

If you really do want in universe explanation I recommend asking over at https://worldbuilding.stackexchange.com/. As they're much more suited to building out lore/explanations for you.

One option to keep in mind though is that you can tweak the way effects are granted to lend more plausibility to your explanations. For example you mention the player takes 1/4 damage, but they could instead just as easily avoid 3/4 of all attacks at them. This would shift from a ship based effect(sturdy hulls from a custom vessel, extra shields from a special generator) to a pilot based one(ace pilot best in the fleet). Temper the math with grazes(reduced damage hits) and smaller (say ~20%) damage reduction to get the same exact effect as -75% damage if desired.
> 15 votes

# Answer
**You don't have to**

Player superiority is so well established by the thousands of games that have gone before that it is highly unlikely to raise the slightest eyebrow. More broadly, the protagonist(s) in nearly all fiction are outpowered compared to those around them. It is simply accepted to be the case.

Drawing attention to it is likely to be more difficult to do well than simply ignoring the issue and carrying on. You could, depending on tone, also "hang a lampshade on it" and point out the absurdity before carrying on regardless.
> 6 votes

# Answer
> What guidelines or concepts exist which can be used to justify PC superiority in general? In a mathematical sense, do I have to explain -75% damage taken and +300% damage dealt as baseline for all PCs in a credible way? Or is that a silently accepted premise of games in general?

Generally in YOUR case : Easiest Concept would be that the players superiority in-game comes not from HARDWARE, but from Superior Software. Either that the PC is a gifted coder, whose targeting, engine power control/efficiency, and shield frequency rotation patterns, are superior to any similarly equipped ship OR the other route - Humans are humans...but enemies are AI/scouts/drones and completely unmanned. And that these older unmanned ships have somewhat outdated software, generally outclassed by any modern system.

Generally as in a generic "Why are heroes better than non-heroes" :

Plot convenience. The story MUST progress, and the hero MUST NOT die to the first goblin he/she comes across (IE S01E01 of Goblin Slayer). Nothing more. Is John Wick PHYSICALLY different from you and I, such that a bullet wound does not cause him to bleed out internally? No. If John Wick were not the hero of a story, he would die. And it would be a bad story.
> 5 votes

# Answer
## Explaining it

> Now for RPGs it's usually something like destiny, magic, superior skill, backstory, better (enchanted) equipment, having a rare power.

The common thread in the things you list is that the player has **something that others don't**. Whether it's destiny's favor or a rare skill, there is something that separates them from the general rabble they interact with.

> But what if it's about space ships with equal size, type and equipment? How could I explain that a player can repeatedly and easily grind through 5-10 space ships which he himself is using without having much room for player skill due to weapons and thrusters working automatically?

The answer is the same: find an explanation that justifies why the player is different from the others. For example:

* The player managed to get their hands on a prototype ship. The manufacturer was unable to bring it into production due to external factors but a handful of prototypes exist. (example: The Expanse TV show)
* Similarly, the player belongs to a civilization which has above average engineering skills. It's not impossible for this civilization to have died out if you want a reason for why the player is unique in their setting. (example: Superman is the almost-last of his superior kind)
* The player has an exceptional crew, the cream of the crop. They are able to eke out victories because their skills dramatically impact the efficiency of the ship. Expert pilots, expert engineers, expert marksmen, ... a well oiled ship runs better (example: Mass Effect. Shepard has access to Black Ops level equipment and recruits exceedingly skilled people to their cause)
* Destiny favors the player. If you allow for destiniy (or a deity) to favor an RPG player, the same allowance exists for a player in space. There's no reason to assume that fate/god is bound to a planetary surface. (example: any RPG where they player is "the chosen" - this is a very common trope)

---

## Not explaining it

However, I do agree with others that you're better off *not* explaining it and expect the player to assume that they are really skillful, as opposed to the game holding their hand.

Everyone wants to feel like the hero who is superior to their opponents. Don't take that magic away unless you absolutely have to.
> 5 votes

# Answer
i don't think you need to explain this at all.

When you win a life or death fight, its not the losers that get to tell the story, if the ships are equal than its a 50% chance you win each fight.

sure you could say the odds of winning a 50/50 battle 10 times in a row is unlikely. but that is why they are the main character, they are the one with the story to tell. no one needs an explanation because they are emotionally invested in this person winning, they won't question something that is possible.

You are more likely to win 20 50/50 fights in a row than win the lottery and we don't need additional lore for someone winning the lottery beyond that it happened.

The mechanics used to ensure the player has a slight advantage need not to be described to them or explained since theoretically they could do it without the advantage
> 2 votes

# Answer
Players receive many advantages that are generally *silently accepted* like you mentioned. Mainly the ability to repeat encounters and bring in outside knowledge. Given the same ship and even the same exact character, players still come out ahead due to this fourth-wall version of precognition.

Games like SUPERHOT and Hotline Miami are good examples of this. The player can win 20 coin flips in a row because they (in theory) went through all one million possibilities. Think of it like the Doctor Strange approach.
> 2 votes

# Answer
**Don't explain it**
Pretty much all games do this and it is more than accepted. If you will explain it it will probably lower the satisfaction. Just imagine your spaceship needs to shoot down enemies that look like ducks instead of bad-ass star cruisers (even though they have the same stats), would that be satisfying?

You could also take a look at Bloodborne for comparison as they have quite a unique take on this. A lot of NPCs can and will pretty much one-shot the PC. This makes for an insane high learning curve but proves all the more satisfying for the right kind of player.
> 2 votes

# Answer
In all these games the players are the "heroes" of a story

They are on a path in that story where everything is interesting, exciting and relevant.

It's rather like the way that people depicted in films never go to the toilet, spend hours doing laundry or fill in forms. If these things happen they just kind of occur outside of the story

It's the same with the players in a RPG

Given that this is the way that the "story of the characters" work, it is not surprising that if they have a fight it will have a heroic outcome. If they find a treasure it will be enormous. If they fall in love it will be with the most beautiful.

This is not a matter of luck - or as you are concerned with - the laws of reality in the world in which they live. It is simply the path of the hero to tread a way that is brighter and a better story than everyone else

See Joseph Campbell's The Hero with a Thousand Faces if you want to understand the relation between hero and their story
> 1 votes

# Answer
Is your question "how to make my player win without advantage"? If they have no physical advantage, equipment or anything, the only things I can think of that could help them are intelligence and luck.

Example: Your player shoots an enemy spaceship at a spot that makes it destroy 2 other ships. Or the player gets lucky and the enemy gets an asteroid in the face.
> 0 votes

# Answer
> In a mathematical sense, do I have to explain -75% damage taken and +300% damage dealt as baseline for all PCs in a credible way? Or is that a silently accepted premise of games in general?

You could achieve this naturally through rapid fire. You can shoot projectiles as fast as you want by clicking the fire button. If you're shooting 4x faster than them, then you will take exactly 75% less damage and do 300% additional damage, even though you are firing the same projectiles as they are, and your ship has the same durability.

This doesn't remove the contrivance entirely, since you still have to wonder why your opponents aren't shooting quickly as well. But at least it shifts the burden from the inexplicable magical superiority of your ship to an inexplicable incompetence of your opposing ships' pilots. Something that the sci-fi film industry seems to be perfectly happy with.

Or perhaps it's a hell of a lot easier to navigate the ship with a PC keyboard or Nintendo controller than from the cockpit.
> 0 votes

---
Tags: game-design
---


# Question
Title: How to implement a component-based model for menus in Unity?
I'm trying to create a "sims-like" context menu when an item / game object is clicked.

This comes as an add-on question from this question: How to design context menus based on whatever the object is?

Specifically:

> Each object of class Item would have a list of components like Equipable, Edible, Sellable, Drinkable, etc. An item can have one or none of each component (for example, a helmet made of chocolate would be both Equipable and Edible, and when it is not a plot-critical quest item also Sellable). The programming logic which is specific to the component is implemented in that component. When the user right-clicks on an item, the components of the item are iterated and context-menu entries are added for each component which exists. When the user selects one of these entries, the component which added that entry processes the option.
>
> You could represent this in your XML-file by having a sub-node for each component. Example:

```
 <item>
      <name>Chocolate Helmet</name>
      <sprite>helmet-chocolate.png</sprite>
      <description>Protects you from enemies and from starving</description>
      <edible>
          <taste>sweet</taste>
          <calories>2560</calories>
      </edible>
      <equipable>
          <slot>head</slot>
          <def>20</def>
      </equipable>
      <sellable>
          <value>120</value>
      </sellable>
   </item>

```

When I read this, it reminds me of an interface in programming. My question is, how do you implement this? Perhaps a better question is "is the answer still valid" but it does seem relevant to me.

What have I tried? Nothing at this point, because I'm not sure where to start. Given the example above, I'd guess that `Item` would have a list of... interfaces? that it could implement? This is why I am a bit confused.

I want to add, this isn't just a UI issue. I found a few radial menus in the store, my issue is how to populate the menu depending on what game object is clicked.

# Answer
> 1 votes
Yes, using interfaces is one way to do this.

You can use `GetComponents` (note the additional `s`) to get all components on a gameObject which implement the same interface or inherit from the same class. So you can create an interface which marks any MonoBehaviour which adds one or more context menu options to the gameObject it is on.

Let's call this interface `IContextOptionsProvider` and give it a method `IEnumerable<ContextOption> GetContextOptions()` (assuming `ContextOption` is a plain old C# class you created to represent a context option). Then, when you create a MonoBehaviour which is supposed to add one or more context menu options to the gameObject it is on, you have it implement that interface and implement that method to return the context options. This could look something like this:

```
public class Potion : MonoBehaviour, IContextOptionProvider
{
    public IEnumerable<ContextOption> GetContextOptions() {
        return new ContextMenuOption[] {
            this.Drink,
            this.Sniff,
            this.PourOut
        }
    }
    /* definition of Drink, Sniff and PourOut */
}

```

Now if you want to get all the context options of all the components of a GameObject which implement `IContextOptionsProvider`, you can do it like this:

```
    foreach(IContextOptionProvider provider in gameObject.GetComponents<IContextOptionProvider>()) {
        foreach(ContextOption contextOption in provider.GetContextOptions()) {
            // do what needs to be done with each contextOption
        }
    }

```

---
Tags: unity, menu
---


# Question
Title: how to change value of variable only once?
I am building simple platformer game in which the player hops on to platforms and the speed of platforms increase per time. This is an endless game and depends on the high score system.

But, the problem is whenever I change the speed of the platform it changes per frame and it increases like 0.1f, 0.2f, 0.3f, and so on. For eg:- my default speed of platforms is 0.1f and whenever the player collides with that platform, I want it to change to 0.2f but since, I did this in update function in unity, it changes 0.1f ,0.2f,0.3f constantly.

My code is:-

```
public class destroyTime : MonoBehaviour {
    public float startTime = 3f;
public MoveTheTiles movethetiles;
    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        foreach (Transform child in transform) {
            if (child.tag == "Player" ) {
                startTime -= Time.deltaTime;
movethetiles.move += 0.1f;`//Problem is here!`
                if (startTime <= 0) {
                    startTime = 3f;
                    child.transform.parent = null;
                    Destroy (gameObject);
                }
            }
        }
    }
}

```

# Answer
If I understand correctly, it seems that everytime you hit a platform you want the speed to increase by a fixed amount. In this case I would recommend using OnCollision Enter:

```
void OnCollisionEnter (Collision collision) {
    movethetiles.move+=0.1f
}

```
> 1 votes

# Answer
Essentially, you should do something like this...

1. Give every platform a unique ID of some kind
2. Give the player a property called something like "current\_platform\_id"
3. If player is on no platform, ID is null (or some other value that can't be a platform ID)
4. As soon as a player touches a platform...
    1. If player.current\_platform\_id is not null, do nothing
    2. Otherwise, set player.current\_platform\_id to ID of touched platform and increment platform speed by 0.1f.
    3. As soon as player jumps or moves off the platform, set player.current\_platform\_id to null.

Effectively, this lets the player object know it's already on a platform, and that it doesn't have to up the speed.

Another approach is for the platform to have a "player is touching" flag, and on player touch and touching==false, set this to true and increase platform speed. As soon as the player leaves the platform (on player jump for example), set platform.touching to false.

This is actually not unlike debouncing a switch in code. This post might give some insights, though switch debouncing often can utilize time checks to avoid jitter (fast on and off fluctuating) at the point of switch activation. https://stackoverflow.com/questions/48434575/switch-debouncing-logic-in-c
> 0 votes

---
Tags: unity, platformer
---


title: How does Unity's Collider.Bounds work?

text:
# Question
Title: How does Unity's Collider.Bounds work?
From waht I understand, Collider.Bounds are the sides or bounds of the collider of the GameObject (at least for a cube with a BoxCollider). But I got a result that I wasn't expecting when I tried moving a cube continuously downwards and drawing the bounds with lines. While moving frame by frame, the collider bounds seemed to be not bounding the cube (or at least that's what my test is showing, if my test is correct).

Here's 3 frames of screenshot:

What I did for this is create a new 3D project, add a Cube, then added a single script and then added this script to the Cube. The whole script is:

```
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{
    Vector3 velocity;

    // Start is called before the first frame update
    void Start()
    {
        velocity = Vector3.zero;
    }

    // Update is called once per frame
    void Update()
    {
        velocity.y += -0.5f;
        transform.Translate(velocity);

        Bounds bounds = GetComponent<Collider>().bounds;
        Debug.DrawLine(new Vector3(bounds.min.x, bounds.min.y, bounds.min.z), new Vector3(bounds.max.x, bounds.min.y, bounds.min.z), Color.red);
        Debug.DrawLine(new Vector3(bounds.max.x, bounds.min.y, bounds.min.z), new Vector3(bounds.max.x, bounds.max.y, bounds.min.z), Color.red);
        Debug.DrawLine(new Vector3(bounds.max.x, bounds.max.y, bounds.min.z), new Vector3(bounds.min.x, bounds.max.y, bounds.min.z), Color.red);
        Debug.DrawLine(new Vector3(bounds.min.x, bounds.max.y, bounds.min.z), new Vector3(bounds.min.x, bounds.min.y, bounds.min.z), Color.red);
        Debug.DrawLine(bounds.min, bounds.max, Color.red);
    }
}

```

Am I not understanding something or am I doing something wrong?

# Answer
As @DMGregory stated, I needed to notify the Physics system by using Physics.SyncTransforms() after every call to Transform.Translate() and the Collider lined up perfectly after that.
> 1 votes

---
Tags: unity
---


# Question
Title: GameObject keeps snapping to camera size on play
I'm in the process of making my GameObject move when I drag it across the screen using touch. But my current issue is when I press play to test the game, game object snaps to the size of my camera on the Y. The camera by default is set to a size of "5" but I have mine set to "5.194104". The GameObject will snap to this position on play. I cannot figure out why. Instead of the object staying at the -4.5f like I have in the Vector3, it jumps to the camera size.

Here is what I have:

```
using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class PaddlePosition : MonoBehaviour
{
     void Update()
     {
         OnFingerDrag();
     }

     private void OnFingerDrag()
     {
           Vector3 fingerPosition = new Vector3(Input.mousePosition.x, -4.5f, 0.0f);
           Vector3 objectPosition = Camera.main.ScreenToWorldPoint(fingerPosition);

           transform.position = objectPosition;
     }
}

```

# Answer
You want the -4.5f to be set to the object position, not the finger position. i.e. `objectPosition.y = -4.5f`.

The finger/mouse position is in screen space where `(0,0)` is the bottom-left corner of the screen and the right-top is `(pixelWidth,pixelHeight)`. A negative y value (-4.5f) will just result in the center of the object being clamped to 4.5 pixels off screen at the bottom of the screen.

Your code should look something like this:

```
private void OnFingerDrag()
{
    Vector3 objectPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    objectPosition.y = -4.5f;

    transform.position = objectPosition;
}

```
> 0 votes

---
Tags: unity, c#, camera, transformation
---


# Question
Title: Changing JavaScript Player Object based on keypress
I'm currently working on a basic JavaScript top-down shooter and I've run into a dilemma. I'm trying to implement a basic toggle weapon system however when I press the key it changes the weapon properly but when I press it again to toggle back it doesn't work. I don't think it's an issue with the rendering because the drawing function is able to detect the different weapons properly. I feel it's an issue with the actual toggle system code.

Here's the code for the player class

```
class Player{
    constructor(set){
        this.cx = set.x;
        this.cy = set.y;
        this.r = set.r;
        this.color = set.color;
        this.angle = 0;
        this.toAngle = this.angle;
        this.state = 1;
        this.up = false;
        this.down = false;
        this.right = false;
        this.left = false;

        this.bind();
    }
    bind(){
        const self = this;
        c.addEventListener('mousemove', (e) => {
            self.update(e.clientX, e.clientY);
        });
        window.addEventListener('keydown', (e) => {
            if(e.keyCode == 81){
                if(self.state = 1)
                    self.state = 0;
                if(self.state = 0)
                    self.state = 1;
            }

        });
        //toggle code:
        window.addEventListener('keyup', (e) => {
            if(e.keyCode == 81){
                if(self.state = 1)
                    self.state = 0;
                if(self.state = 0)
                    self.state = 1;
            }

        });
    }
    update(ex, ey){
        this.toAngle = Math.atan2(ey - this.cy, ex - this.cx);
    }
    canv(){
        if(this.angle !== this.toAngle){
            clear();
            ctx.save();

            ctx.translate(this.cx, this.cy);
            ctx.rotate(this.toAngle - this.angle);
            ctx.translate(-this.cx, -this.cy);

            drawPlayer(this.cx, this.cy, this.r, 0, 180, this.color, this.state);

            this.angle = this.toAngle;
        }
    }
}
//drawing code (above this one in the complete file)
function drawCircle(x, y, rad, startAngle, endAngle, color){
    ctx.fillStyle = color;
    ctx.beginPath();
    ctx.arc(x, y, rad, startAngle, endAngle);
    ctx.fill();

}
function drawPlayer(x, y, playerR, playerStartAng, playerEndAng, color, state){
    //left hand start
    if(state == 0){
        ctx.fillStyle = color;
        ctx.beginPath();
        ctx.arc(x - 15, y - 15, 10, 0, 180);
        ctx.fill();

        //border
        ctx.strokewidth = 10;
        ctx.strokeStyle = "brown";
        ctx.stroke();
        //end

        //right hand start
        ctx.beginPath();
        ctx.arc(x + 15, y - 15, 10, 0, 180);
        ctx.fill();

        //border
        ctx.strokewidth = 10;
        ctx.strokeStyle = "brown";
        ctx.stroke();
    }
    if(state == 1){
        //right hand start
        ctx.beginPath();
        ctx.arc(x + 7, y - 21, 10, 0, 180);
        ctx.fill();

        //border
        ctx.strokewidth = 10;
        ctx.strokeStyle = "brown";
        ctx.stroke();

        ctx.fillStyle = color;
        ctx.beginPath();
        ctx.arc(x - 7, y - 17, 10, 0, 180);
        ctx.fill();

        //border
        ctx.strokewidth = 10;
        ctx.strokeStyle = "brown";
        ctx.stroke();

        //gun start
        ctx.fillStyle = "black";
        ctx.beginPath();
        ctx.ellipse(x, y - 20, 3, 25, 0, 0, 2 * Math.PI);
        ctx.fill();

        //gun border
        ctx.strokewidth = 10;
        ctx.strokeStyle = "black";
        ctx.stroke();
        //end

    }

    //draw player
    drawCircle(x, y, playerR, playerStartAng, playerEndAng, color);
}

```

# Answer
> 1 votes
You are assigning (i.e. `num = 0`) instead of using a conditional (i.e. `if (someBool === true) {/* Do stuff */}`).

Your toggle code should look something like so:

```
// Easiest way to toggle any value used as a boolean
self.state = !self.state;

// Or if you still want this as an if statement
if (self.state) {
  self.state = 0;
} else {
  // We use an else statement since there can only be two possible values
  self.state = 1;
}
```

**UPDATE: Remove the `keydown` event.**

I just noticed that you have both a `keyup` and `keydown` event listener. Only the `keyup` event should be on since you want the player to press the key to toggle and then press the toggle key again

---
Tags: javascript, html-canvas
---


# Question
Title: Making a way to fight monsters in my clicker game
I want a working next and previous button for killing monsters http://prntscr.com/o375y7 http://prntscr.com/o37609 Im new to this concept so i don't know how to go about doing this.

html code(all i have so far)

```
 <button onclick="Fight()" id="Fightbtn" >Fight</button> Rat   Hp:<span
 id="CurrentEnemyHp">10</span>
                    <body>

 <style>
a {
  text-decoration: none;
  display: inline-block;
 padding: 8px 16px;
}

a:hover {
  background-color: #ddd;
  color: black;
 }

.previous {
  background-color: #f1f1f1;
  color: black;
 }

.next {
  background-color: #4CAF50;
  color: white;
}

.round {
  border-radius: 50%;
}
</style>

<a href="#" class="previous round">‹</a>
<a href="#" class="next round">›</a>

            </body>

        </html>

```

The "Rat" in the middle of the button stuff should be like "span id="currentenemy" span" just didnt know how to set up my switch statement or array to be able to switch between current enemy, hp and damage from clicking the next button. if someone can help me set it up id appreciate it. never used this concept before.

I expect after my program is running for the next button to be by itself disabled until you kill a rat 10 times then it becomes enabled then after you click it for the enemy to change and hp to change(damage to) then the previous arrow will become unhidden. But my actual output i can't get this to work.

# Answer
> 0 votes
OK, so to achieve this check the code below.

```
// Create an array of enemies
let enemies = [];
enemies.fill({
  hp: 100
});

// Store the current enemy target
let currentTarget = 0;

// Our Fight function
function Fight() {
  enemies[currentTarget].hp -= 10;
}

// Our next and previous button actions
function nextTarget() {
  if (currentTarget < enemies.length) {
    //
    currentTarget++;
  } else {
    // Loop back around
    currentTarget = 0;
  }
}

function prevTarget() {
  if (currentTarget >= 0) {
    //
    currentTarget--;
  } else {
    // Loop back around
    currentTarget = enemies.length - 1;
  }
}
```

---
Tags: javascript, html
---


title: Getting exact time of button/key input

text:
# Question
Title: Getting exact time of button/key input
Is there a way to get the time of an input event (a key or button press) to a higher degree of accuracy than the Update call, maybe by subscribing to input events and handling them immediately?

# Answer
Using `OnGUI()` and `Event.current` you can get the exact moment that a key is pressed. `OnGUI()` is one of the few things that is not tied to framerate like the update function is. This is why using `OnGUI()` will give you a much more accurate time than the update function.

You can then do something like this:

```
void OnGUI()
{
    if (Event.current.isKey)
    {
        Debug.Log("Key pressed at time " + Time.realtimeSinceStartup);
    }
}

```

which will put the time a key was pressed, released, and typed in console.

I'm using `Time.realtimeSinceStartup` here because this reports time based on the system timer unlike Time.time does.
> 1 votes

---
Tags: unity, input
---