# Question
Title: How do I make sure everyone sees the same distance across different resolutions?
Hello game dev community. I have recently got into making games in a browser window, and me and a friend ran into a common problem. Let's say I have a game like diep.io, where users can control their tank and move across a large grid. Each player can only see a certain distance, even if they moved the window to a larger monitor, like from 1080p to a 4K monitor.

I've created a game in HTML5 canvas, but the problem is that it depends on the browser's `window.innerWidth` and `innerHeight` properties. I can tell that this is an issue, because if I drew a grid, one player on a 1080p monitor could only see `x` distance but a player on a 4K monitor with a larger width and height could see `x * 2` distance (or how much larger it actually is), meaning that the player on a 4K monitor has an advantage, by seeing players in a larger distance.

How exactly could I tackle this problem? My friend has the same issue, and I hope this answers it.

# Answer
To get the obvious limiting factors out of the way: since there are currently 3 very common aspect ratios out there (4:3/5:4, 16:9, 21:9) and you can also just scale the window any way you want, it's impossible to show the exact same area to everyone. You could either go for the limiting approach, where you choose one of the aspect ratios and make sure that every other is just a cropped version or you can make sure the area they see is equal by using the

$$width = \sqrt {\frac{area} {aspect}} $$

formula. It depends on your preferences.

To display the same area across different resolutions, first pic a resolution that's comfortable to you (e.g. the width of the game on your monitor, just query innerWidth), then simply do

```
let factor = innerWidth / myComfortableResolution;
context.scale(factor, factor);

```

at the start of your program and after every resetTransform and setTransform if you use them. This will scale the viewing area to be the exact same width in units on every resolution.

If you use the formula from the first paragraph, replace `myComfortableResolution` with the width you get from it.
> 1 votes

---
Tags: javascript, rendering, html-canvas, browser
---


# Question
Title: Defining a projectiles speed and angle before Instantiating
I have a 360 degrees shooter object and a projectile to shoot. My projectile has a Rigidbody2D with zero gravity scale. I want it to bounce off of colliders when it gets hit, but when I instantiate it from my shooter I have to write the velocity value in update so it keeps going against the colliders when shot. I figured that I should assign it a velocity in start function, but then it only goes in one direction. How do I fix this?

# Answer
If I understand your question correctly, then I believe you are creating a top-down shooter game similar to the classic Asteroids.

You will want to add a force to the `RigidBody2D` of your projectile instead of directly modifying its velocity. Below is a function I have use in one of my 2D games that applies force to a projectile at the provided angle and magnitude. This code is attached to my `Projectile` script. You feed it the angle in degrees at which you would like to launch the projectile (0 for right, 90 for up, 180 for left, 270 for down), and adjust magnitude to determine how fast the projectile is launched.

```
RigidBody2D rb2D = GetComponent<Rigidbody2D>();

/// <summary>
/// Launches the ball at the given angle and magnitude.
/// </summary>
/// <param name="angle"></param>
public void LaunchProjectile(float angle, float magnitude)
{
    float newAngle = angle * Mathf.Deg2Rad;
    Vector2 direction = new Vector2(Mathf.Cos(newAngle), Mathf.Sin(newAngle));
    rb2D.AddForce(direction * magnitude, ForceMode2D.Impulse);
}

```

If you want to ensure that your projectile will bounce off of the colliders it hits, then create a new `PhysicsMaterial2D` and give it a friction value of 0 and a bounciness value of 1. You can create a new material by right clicking in the project folder and selecting "Create \> Physics Material 2D". Once you've created a new one, drag it into the `Material` field of your `Collider2D` components in the inspector. For example, if you have a ball that you want to bounce off of a wall, then you'll want to add this material to the `Material` field of both the ball and the wall's `Collider2D` components.
> 1 votes

---
Tags: unity, c#, 2d
---


title: Why I keep getting null exception?

text:
# Question
Title: Why I keep getting null exception?
If it's needed I will add the completed script code of the Prefab Replace EditorWindow type.

I packed exported the project to a file and uploaded the packed file it's 31MB only. My unity pack

In EditorWindow script:

```
for (var i = selection.Count - 1; i >= 0; --i)
{
      var selected = selection[i];
      _components = selected.GetComponents(typeof(MonoBehaviour));

      foreach (var comp in _components)
      {
              _newObject.Init(comp);
      }
}

```
* `_newObject` is an instantiated prefab
* `_components` is a `Component[]` array

Using either `typeof(MonoBehaviour)` or `typeof(Component)` I will get the same null exception later.

When I'm using a break point to debug I see that in components there are 3 items. And they are not null.

Then I have a Extension class:

```
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEngine;

public static class Extension
{
    public static T AddComponent<T>(this GameObject go, T toAdd) where T : Component
    {
        return go.AddComponent<T>().GetCopyOf(toAdd);
    }

    public static void Init<T>(this GameObject go, T comp) where T : Component
    {
        go.AddComponent(comp);
    }

    public static T GetCopyOf<T>(this Component comp, T other) where T : Component
    {
        if (comp != null)
        {
            Type type = comp.GetType();
            if (type != other.GetType()) return null; // type mis-match

            const BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Default | BindingFlags.DeclaredOnly;

            var pinfos = type.GetProperties(flags);
            foreach (var pinfo in pinfos.Where(pinfo => pinfo.CanWrite))
            {
                try
                {
                    pinfo.SetValue(comp, pinfo.GetValue(other, null), null);
                }
                catch { } // In case of NotImplementedException being thrown. For some reason specifying that exception didn't seem to catch it, so I didn't catch anything specific.
            }

            var finfos = type.GetFields(flags);
            foreach (var finfo in finfos)
            {
                finfo.SetValue(comp, finfo.GetValue(other));
            }
        }

        return comp as T;
    }
}

```

When using a break point I can see that inside the Init method that go and comp are not null. Then it's moving to the top method AddComponent and also there both go and toAdd are not null.

But when it's getting to the method GetCopyOf then comp is null at the first line it's null:

```
if (comp != null)

```

Already on this line comp is null. I can't figure out why it's null only at this method.

NullReferenceException: Object reference not set to an instance of an object

The full stack message:

```
Extension.GetCopyOf[T] (UnityEngine.Component comp, T other) (at Assets/Scripts/Extension.cs:23)
Extension.AddComponent[T] (UnityEngine.GameObject go, T toAdd) (at Assets/Scripts/Extension.cs:12)
Extension.Init[T] (UnityEngine.GameObject go, T comp) (at Assets/Scripts/Extension.cs:17)
PrefabReplace.InstantiatePrefab (System.Collections.Generic.IReadOnlyList`1[T] selection) (at Assets/Editor/PrefabReplace.cs:222)
PrefabReplace.Replacing () (at Assets/Editor/PrefabReplace.cs:144)
PrefabReplace.OnGUI () (at Assets/Editor/PrefabReplace.cs:44)
System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) (at <d7ac571ca2d04b2f981d0d886fa067cf>:0)
Rethrow as TargetInvocationException: Exception has been thrown by the target of an invocation.
System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) (at <d7ac571ca2d04b2f981d0d886fa067cf>:0)
System.Reflection.MethodBase.Invoke (System.Object obj, System.Object[] parameters) (at <d7ac571ca2d04b2f981d0d886fa067cf>:0)
UnityEditor.HostView.Invoke (System.String methodName, System.Object obj) (at C:/buildslave/unity/build/Editor/Mono/HostView.cs:342)
UnityEditor.HostView.Invoke (System.String methodName) (at C:/buildslave/unity/build/Editor/Mono/HostView.cs:336)
UnityEditor.HostView.InvokeOnGUI (UnityEngine.Rect onGUIPosition, UnityEngine.Rect viewRect) (at C:/buildslave/unity/build/Editor/Mono/HostView.cs:310)
UnityEditor.DockArea.DrawView (UnityEngine.Rect viewRect, UnityEngine.Rect dockAreaRect, System.Boolean customBorder, System.Boolean floatingWindow, System.Boolean isBottomTab) (at C:/buildslave/unity/build/Editor/Mono/GUI/DockArea.cs:361)
UnityEditor.DockArea.OldOnGUI () (at C:/buildslave/unity/build/Editor/Mono/GUI/DockArea.cs:320)
UnityEngine.Experimental.UIElements.IMGUIContainer.DoOnGUI (UnityEngine.Event evt, UnityEngine.Matrix4x4 worldTransform, UnityEngine.Rect clippingRect, System.Boolean isComputingLayout) (at C:/buildslave/unity/build/Modules/UIElements/IMGUIContainer.cs:266)
UnityEngine.Experimental.UIElements.IMGUIContainer.HandleIMGUIEvent (UnityEngine.Event e, UnityEngine.Matrix4x4 worldTransform, UnityEngine.Rect clippingRect) (at C:/buildslave/unity/build/Modules/UIElements/IMGUIContainer.cs:438)
UnityEngine.Experimental.UIElements.IMGUIContainer.HandleIMGUIEvent (UnityEngine.Event e) (at C:/buildslave/unity/build/Modules/UIElements/IMGUIContainer.cs:421)
UnityEngine.Experimental.UIElements.IMGUIContainer.HandleEvent (UnityEngine.Experimental.UIElements.EventBase evt) (at C:/buildslave/unity/build/Modules/UIElements/IMGUIContainer.cs:401)
UnityEngine.Experimental.UIElements.EventDispatcher.ProcessEvent (UnityEngine.Experimental.UIElements.EventBase evt, UnityEngine.Experimental.UIElements.IPanel panel) (at C:/buildslave/unity/build/Modules/UIElements/EventDispatcher.cs:511)
UnityEngine.Experimental.UIElements.EventDispatcher.Dispatch (UnityEngine.Experimental.UIElements.EventBase evt, UnityEngine.Experimental.UIElements.IPanel panel, UnityEngine.Experimental.UIElements.DispatchMode dispatchMode) (at C:/buildslave/unity/build/Modules/UIElements/EventDispatcher.cs:307)
UnityEngine.Experimental.UIElements.BaseVisualElementPanel.SendEvent (UnityEngine.Experimental.UIElements.EventBase e, UnityEngine.Experimental.UIElements.DispatchMode dispatchMode) (at C:/buildslave/unity/build/Modules/UIElements/Panel.cs:176)
UnityEngine.Experimental.UIElements.UIElementsUtility.DoDispatch (UnityEngine.Experimental.UIElements.BaseVisualElementPanel panel) (at C:/buildslave/unity/build/Modules/UIElements/UIElementsUtility.cs:245)
UnityEngine.Experimental.UIElements.UIElementsUtility.ProcessEvent (System.Int32 instanceID, System.IntPtr nativeEventPtr) (at C:/buildslave/unity/build/Modules/UIElements/UIElementsUtility.cs:68)
UnityEngine.GUIUtility.ProcessEvent (System.Int32 instanceID, System.IntPtr nativeEventPtr) (at C:/buildslave/unity/build/Modules/IMGUI/GUIUtility.cs:179)

```

# Answer
> 2 votes
Extension methods can be called on null objects, this means that that the only way `comp` can be null inside `getCopyOf` is when `GameObject#AddComponent<T>()` returns null.

This could happen because 1.) said gameobject already has a component of type `T`, 2.) The Component is an abstract one and can't be instantiated or 3.) The type is `Component`

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


title: How to move a 2D boat in unity

text:
# Question
Title: How to move a 2D boat in unity
I am working on a *2D game* in which boat moves continuously but the direction of the boat is on users touch. Where the user moves its finger the boat moves in that direction. How would I achieve this? Can someone help me in building my logic?

# Answer
> 1 votes
First get the point where the touch is in world coordinates (the necessary methods are on the Camera, look for something along the lines of `Camera.screenToWorldPosition` and pick the most suitable one), then get the direction vector by dividing the position of the boat from this and normalizing it:

```
Vector2 direction = (touchWorldPosition - boatPosition).normalized;

```

You can get the angle from this using `Quaternion.LookRotation`:

```
Quaternion touchAngle = Quaternion.LookRotation(direction);

```

Now rotate the boat towards this angle using `Quaternion.RotateTowards`. The first argument should be the current rotation of the ship, the second is the touchAngle you just calculated and the third argument is the max angle you want the ship to rotate in a frame. The method returns a new quaternion, set the ship's rotation to that.

Now get the forward direction vector of the boat. If the boat looks up by default, then it's `transform.up`, if it looks to the right, then `transform.right`, etc. To move the ship forward just take this direction vector and either apply a force in the same direction to the ship or set the velocity to be this value depending on whether you want a dynamic or kinematic approach respectively.

---
Tags: unity
---


# Question
Title: Game Mechanics for character development in an RPG
I recently asked a question here on a different stack about how to write strong characters given the limitations of the RPG genre. After all, even in an RPG, which is somewhat story friendly, many gamers just want to get on with the *game*. I understand the impulse and have no desire to punish the players of my game for just wanting to play my game.

## The Goal:

I want to create a character driven ensemble cast jRPG/cRPG with strong characters that the player begins to know and love.

## The Problem:

I don't want to shove story or backstory or dialogue down peoples throats when they just want to fight battles and level up and complete quests. Especially when this can get very repetitive when a player is 'stuck'.

### Current Solutions:

* **Skippable Dialogue and cutscenes**: This feature will often be used by players and can cause problems of its own. Many people will skip the important parts. Then you need to make the important bits unskippable or keep a quest log to hold their hand.
* **Characters make predetermined choices**: This is the thing I can use the most. But I need to also allow the player to make some decisions too. Need might be a strong word; I want. I also don't want to define my characters by a string of choices they made throughout an adventure story.
* **Blank Canvas**: This is where the character is just a representation of what the player makes of them. Their dialogue, their actions, their appearance and personality are all given to them by the player, not the game designer. This doesn't work for me. I have multiple characters. Plus I don't feel strongly that I can develop a game that facilitates the player projecting themselves onto the character, and that is a different skill and style.

## The Question:

What are some game mechanics that can facilitate character development. My Writing question was how do I write within the above constraints. My question here is: **What other game mechanics are available to seamlessly integrate character development into my game?**

---

My question is not a dupe of How can I make my players interested in the game lore of my MMORPG?. While we have similar problems, I am working on a single player jRPG which allows for different approaches to story and character than an MMO. I am also not looking for *just* back-story to develop character. For instance, one of the answerers to my linked writing question mentioned a characters battle-cry as an opportunity to develop their personality, which is decidedly not story.

# Answer
> 4 votes
You basically want to achieve two things:

1.) You want to make the player experience the story. This is very easy to solve, don't let them skip story parts and you'll be certain they've seen it all.

2.) Don't make the player sit through unnecessary cutscenes if they don't want to. There's an easy solution to this too: make every cutscene skippable.

These two options may seem like they can't be in the same game at once, but pay attention to the wording. You don't have to have cutscenes necessarily to tell a story.

As an example, look at Oxenfree. It has a medium sized cast of characters and you can get to know them better even during regular gameplay through conversations they're having. The game even makes sure to be the least intrusive it can get with those lines. If the player character does something that stops the conversation (e.g. shouting something), the other players can semi-naturally continue their lines by adding small half-sentences before them ("anyways, ...", "so, what I was saying...", etc.).

Firewatch avoids cutscenes very well too, even though it is a story oriented game. The main character speaks to other people through a walkie-talkie.

This approach certainly has it's limitations though. For one, you can't avoid cutscenes if you need the player character to stand at a specific location. Same thing if you want to make the main character do things the game mechanics don't allow (e.g. custom animations), but I think it's a good starting point.

# Answer
> 1 votes
**Make Story Delivery Unobtrusive**

If you're creating a JRPG, chances are your story will be delivered through text. There are many techniques to make text less annoying. You should absolutely have an easy to find text speed option that allows the player to make text appear faster or even instantly - slow text crawls are painful and feel like a waste of time to fast readers. Write your dialogue snappy and compact - avoid drawn-out mandatory conversations where possible. Try to separate essential information and story progression from flavour and side stuff and make the essential compact and condensed. Then...

**Present Non-Essential Story as Offer, Not Obligation**

All the nice stuffing in terms of character and story that the player doesn't absolutely *have* to know (even though they should, because it makes the game better) should be shown as an offer they can accept or ignore.

For example, if an automatic conversation is triggered, because something important is happening, deliver the essential in a few lines, then present dialogue options that let the player ask further questions or end the conversation. Allow the player to initiate conversations with their teammates on their own terms instead of triggering it automatically, possibly subtly alert them if teammates have something to say - a single "Can we hurry up? This place brings up bad memories..." is quickly ignored, but also sets a mood and lets the player know that there may be a conversation to be had. If you have voice lines, Philipp made good points about them on the Writing.SE and this is one more possible use for them.

Put background information into dialogues with NPCs or items descriptions in the world that the player can seek out if they're interested. Side quests are also allowed to be more wordy, because the player can ignore them. Put breaking points into long swaths of text where the player can choose to continue listening or walk away from the conversation. If the few mandatory things all players will see are presented in an engaging way, players who may at all care will seek out more depth in their own. Small but tasty appetizers and a ticket to the buffet.

It's important for these things to be easily accessible as well. Show the player they can talk to teammates in the tutorial, but keep the conversation short. NPCs and books/items are enough of a genre convention that most players will expect and know how to deal with them. Besides flavour about the world and characters, consider making some of the extra information useful in game - not in a way that makes it mandatory in order to be successful, but hinting at secrets is fair game.

**It Is Possible to Allow Self-Expression Within the Constraints of a Character**

If you look at games like Deus Ex: Human Revolution or The Witcher series, the main character is clearly defined, but there are still dialogue options for them to express different feelings about stuff. Many of these may not even have consequences in the game beyond a different answer from the conversation partner. However, these small choices still allow the player to feel a closer connection to the character. For example, in Human Revolution Adam is asked how he feels about the extensive modifications done to his body without his consent. His answer doesn't really change anything, but this allows the player to consider what they would feel in his shoes and develop empathy.

Of course you can bolster such decisions with in-game consequences. You could, as is often the case in JRPGs, implement a relationship score for your party members that may influence their powers or unlock new conversations and/or something like Mass Effect's companion quests. You can give better rewards for quests if you treat people kindly, find secret solutions or understand people's needs and desires. You can reward playing a character the way you have written them by giving better rewards/relationship points/stronger powers when adhering to their given personality. But you don't have to. Even a small conversation choice with three options and three different answers to them and nothing else can help the player grow closer to the character, as long as the option is well placed and written, i.e. makes the player actually think about the characters.

**Intertwine Mechanics and Characters**

This is sort of the holy grail of video game design and there are lots of approaches to it.

In terms of a JRPG, you could for example develop the trope of personality reflecting skill sets (brash fire mage, gentle healer etc.) and have characters react to their abilities. A gentle character may feel uncomfortable having destructive abilities and relieved to learn supportive ones. There's a world of difference between a voice line of "I'm sorry I have to do this." and "Burn, baby, burn!"

A typical shounen protagonist would probably think conjuring a big firestorm is awesome as hell while a more subtle power is lame and boring. However, learning how to use such powers may also change their ways of thinking and influence their personality in turn. Not to mention that it makes perfect sense that to master a certain skill you have to actually understand it, which may require character growth on its own. Think of Avatar: The Last Airbender and the scenes in which Zuko attempts to learn to bend lightning, but his inner turmoil keeps him from achieving the necessary control. Later, Zuko grows as a character but loses his firebending powers, because they're fuelled by rage, and he goes out to learn a new, more stable style of controlling fire, that is based on understanding fire as source of life instead of destruction.

Character development that makes your characters more powerful and your playstyle more fun (always remember: numbers are boring, options are interesting) incentivises players to follow the story, who are otherwise more interested in gameplay. Just try not to present the story as a necessary evil or price to pay to get to the fun stuff.

---
Tags: game-design, game-mechanics, rpg, character-development
---


title: JavaFX - How do I create a health bar?

text:
# Question
Title: JavaFX - How do I create a health bar?
I tried searching online on how to implement health bar with Java FX in a 2D side-view Java fighting game but I can only find those that goes with 'awt' and 'Swing'.

The health bar I'm picturing are like the two health bars on Street Fighter games. This is a game where two tanks fight each other in side-view.

I have a `ViewManager.java` that goes as follows:

```
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.*;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundImage;
import javafx.scene.layout.BackgroundPosition;
import javafx.scene.layout.BackgroundRepeat;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.scene.paint.*;
import javafx.scene.canvas.*;

public class ViewManager {

    private static final int HEIGHT = 1000;
    private static final int WIDTH = 1920;
    private AnchorPane mainPane;
    private Scene mainScene;
    private Stage mainStage;

    private final static int GAME_BUTTON_START_X = 120;
    private final static int GAME_BUTTON_START_Y = 400;

    List<WarstrikeButton> gameButtons;

    public ViewManager()
    {
        //Initialize the game stage
        initializeStage();

        //Create background
        createBackground();

        //Draws the tank and bullet
        drawTank();
        drawBullet();

        //Initialize the game buttons
        gameButtons = new ArrayList<>();
        createButtons();

    }//end viewManager

    private void initializeStage() {
        mainPane = new AnchorPane();
        mainScene = new Scene(mainPane, WIDTH, HEIGHT);
        mainStage = new Stage();
        mainStage.setScene(mainScene);
    }

    public Stage getMainStage()
    {
        return mainStage;
    }

    private void addGameButton(WarstrikeButton button)
    {
        button.setLayoutX(GAME_BUTTON_START_X);
        button.setLayoutY(GAME_BUTTON_START_Y + gameButtons.size() * 100);
        gameButtons.add(button);
        mainPane.getChildren().add(button);
    }

    private void createButtons()
    {
        createMoveButton();
        createShootButton();

    }//end createButtons method

    private void createMoveButton()
    {
        WarstrikeButton moveButton = new WarstrikeButton("Move");
        addGameButton(moveButton);
    }

    private void createShootButton()
    {
        WarstrikeButton shootButton = new WarstrikeButton("Shoot");
        addGameButton(shootButton);
    }

    private void createBackground()
    {
        Image backgroundImage = new Image("src/com/warstrike/graphics/resources/2d-game-background-6.jpg", 1366, 1000, false, true);
        BackgroundImage background =  new BackgroundImage(backgroundImage, BackgroundRepeat.REPEAT, BackgroundRepeat.REPEAT, BackgroundPosition.DEFAULT, null);
        mainPane.setBackground(new Background(background));
    }//end createBackground function

//end class

    /*public void drawImageOnScreen(double x, double y, double rotation, String imagePath) throws FileNotFoundException
    {
        //Creating an image
          Image image1 = new Image(new FileInputStream(imagePath));

          //Setting the image view
          ImageView imageView = new ImageView(image1);

          //Setting the position of the image
          imageView.setX(x);
          imageView.setY(y);
          imageView.setRotate(rotation);

          //setting the fit height and width of the image view
          imageView.setFitHeight(x);
          imageView.setFitWidth(y);

          //Setting the preserve ratio of the image view
          imageView.setPreserveRatio(true);

        }//end drawImageOnScreen function */

    public void drawTank()
    {
        // Create the Canvas
          Canvas canvas = new Canvas(1920, 1080);

          // Get the graphics context of the canvas

          GraphicsContext gc = canvas.getGraphicsContext2D();

          // Load the Image (Tank 1)
          String imagePath = "src/com/warstrike/graphics/resources/tanks_tankNavy3.png";
          Image image = new Image(imagePath);

          // Draw the Image (150px is x position, 850px is y position, 134px is times 1.4 of the original width of 92px, 96px is times 1.4 of the original height of 69px
          gc.drawImage(image, 150, 840, 110, 82); //void drawImage(Image img, double x, double y, double w, double h)

          // Load the Image (Tank 2)
          String imagePath2 = "src/com/warstrike/graphics/resources/tanks_tankDesert3.png";
          Image image2 = new Image(imagePath2);

       // Draw the Image (Width parameter is given a negative value to flip the tank horizontally)
          gc.drawImage(image2, 1725, 840, -110, 82); //void drawImage(Image img, double x, double y, double w, double h)

          //Add the canvas to the mainPane
          mainPane.getChildren().add(canvas);
    }

    public void drawBullet()
    {
        // Create the Canvas
          Canvas canvas = new Canvas(1920, 1080);

          // Get the graphics context of the canvas
          GraphicsContext gc = canvas.getGraphicsContext2D();

          // Load the bullet image
          String imagePath = "src/com/warstrike/graphics/resources/tank_bullet3.png";
          Image image = new Image(imagePath);

          // Draw Image
          gc.drawImage(image, 265, 843, 37.5, 25); //void drawImage(Image img, double x, double y, double w, double h)

          mainPane.getChildren().add(canvas);
    }

}

```

To have a better idea, here's a picture:

Just incase you'd want to see my `Main.java`:

```
    import javafx.application.Application; //import JavaFX libraries
    import javafx.scene.Scene;
    import javafx.scene.layout.BorderPane;
    import javafx.scene.shape.Rectangle;
    import javafx.scene.Group;
    import javafx.scene.Parent;
    import javafx.stage.Stage;

    public class Main extends Application {
        @Override
        public void start(Stage primaryStage)
        {
            try
            {
                ViewManager manager = new ViewManager();
                primaryStage = manager.getMainStage();
                //primaryStage.setScene(manager.drawImageOnScreen(50, 50, 0, "src/com/warstrike/graphics/resources/tanks_tankGreen3.png"));
                primaryStage.show();
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }//end catch
        }//end start

        public static void main(String[] args)
        {
            launch(args);
        }//end main
    }//end class

```

**TL;DR:**

1) How do I create a health bar using JavaFX? (Obviously: the health bar will be extended to work e.g health bar shrinks when a bullet hits the tank)

2) May I know if my implementation is the correct way to do it? Or should I divide different draw components (e.g. drawTank(), drawBullet()) by classes and how exactly do I do it?

Sorry I'm completely new to game dev. Thank you for your help.

# Answer
> 3 votes
I couldn't find your approach of a health bar, but I would suggest a simple approach for the start, something like this:

1) Add a `Rectangle` to your scene for each tank and give them both the same size:

```
Rectangle healtbarTank1 = Rectangle(200.0, 50.0, Color.RED);
Rectangle healtbarTank2 = Rectangle(200.0, 50.0, Color.BLUE);

```

2) Create a `DoubleProperty` for each healthbar and create a binding with the healthbars `widthProperty()`:

```
DoubleProperty healthPercentage1 = SimpleDoubleProperty(1.0);
DoubleProperty healthPercentage2 = SimpleDoubleProperty(1.0);

DoubleBinding b1 = healthbarTank1.widthProperty().multiply(healthPercentage1);
DoubleBinding b2 = healthbarTank2.widthProperty().multiply(healthPercentage2);
healthbarTank1.widthProperty().bind(b1);
healthbarTank2.widthProperty().bind(b2);

```

Then you just have to set the percentage properties and the rectangles will change their size according to your bindings (width * percentage). Calculating the percentage of the health is up to you though. You can exchange the rectangles later for nearly any other `Node` JavaFX has to offer.

# Answer
> 1 votes
To create a health bar, you want to have a value representing the percentage of health you have. This value can be calculated as such:

```
float percentage = (currentHealth / maxHealth);

```

This will give you a value between 0.0 and 1.0. Next, you have the max width of the health bars on either side. You would presumably draw a container that the health bar goes in and then draw the health bar itself. You can draw the actual bar anywhere you want, but to calculate the width of the bar based on the player's current health:

```
float width = (percentage * maxWidth);

```

If you wanted to justify the health bar itself to the right of the container instead of the left, you could do something like:

```
float percentage = (currentHealth / maxHealth);
float width = (percentage * maxWidth);
float x = (originX + ((1.0f - percentage) * maxWidth));

```

And that would move the health bar over so that it is positioned on the right side of the health container. You can also use these percentage values to draw only a portion of an image if you want to use an image for the health bar instead.

It has been a while since I've used JavaFX specifically, so I can't really help you on the specifics of the drawing portion, but if you know how to draw basic shapes on the canvas, you should be able to figure the rest out on your own.

---
Tags: java, gui, javafx, fighting-game
---


# Question
Title: How to render a large tile-based 2D world efficiently (using JavaFX/ScalaFX or more generally)
I have a file `tileset.png` containing a dozen 32\*32 tiles. When my game starts, it generates the world randomly with the available tiles and the size of the world can be changed, so I cannot have a hard-coded world texture.

So I have an \\$n \times m\\$ matrix, each of its element being a Tile. For the moment a so-called Tile is an `ImageView`(in JavaFX), which basically is a portion of my tileset (note that I only load the tileset image once and then generate all my tiles using it).

Now the very basic method that I'm using is, I store a boolean for each tile saying whether it is currently displayed on the screen. I also keep track of the total scale, that is the total amount of pixels that have been dragged yet. From this, for each tile that is to be displayed on the screen, I compute its \\$(x,y)\\$ position given the total offset and I add it to the scenne. Also for each tile that was displayed at the previous "iteration" but is not anymore, I remove it from the scene.

It is however quite laggy, especially when a lot of tiles need to be displayed at the same time or when dragging the map a lot.

I am sure I can drastically improve the performances but I cannot find how. I guess that having a different object for each tile isn't very efficient, yet as said before, I cannot have the entire map as a single image as it is randomly generated. So.. I still need each tile to be an object somehow?

I also saw a few things about using meshes or UV-mapping but I didn't really understand how to make it work here. Also, it was help for Unity. If anyone knows how to implement this in JavaFX/ScalaFX I would be glad to know, but otherwise I think I could adapt a general method in this specific library.

# Answer
> 1 votes
You can draw your tiles with the `Canvas` node. You can still use your tile set for this method. You just have to call the `drawImage(image, sX, sY, sW, sH, dX, dY, dW, dH)` method from the `GraphicsContext` of the canvas node. The `s` parameters are for defining a view on your image (like an `ImageView`). The `d` parameters are for sizing and positiong the resulting image on the canvas.

---
Tags: performance, tiles, tilemap, javafx
---


# Question
Title: How do game devs optimize their games for new CPUs/architectures?
I've learned that DirectX helps devs to program games on a variety of hardware. However, that's the visual/graphics side of things.

How do game devs deal with new CPUs or CPU architectures? Is there another API for that? Do they use DirectX for this too? Or do they need to learn the ins and outs of the architecture and program accordingly?

Thanks.

# Answer
> 0 votes
Programmers, in general, are not required to know how each CPU architecture works to optimise a game. That's the reason we have languages that abstract these details away for us.

One method video game programmers use, to optimise games, is called "Profiling". What this does is, you run the game, and you see which parts of the game are more resource-intensive than others. The results that you see are not "one size fits all", as in, it's possible for one part of the program to be heavier in a specific platform with specific hardware, but be very light on another. But for the most part it gives you an idea of what you can prioritise.

The average programmer, does not need to know the "ins and outs" of every CPU out there, nor for any new CPU that's coming out. There are people out there who like to make games on assembly, I do not have a lot of experience in that area, but I image one would need to know how a CPU architecture works in order to support it. However that's not a requirement and I'd image people do it more because they enjoy it, than that they have to.

---
Tags: directx
---


# Question
Title: LibGDX - Drawing animation before specific tiled layer is drawn
I'm using TildedMap to separate map layer, drawSprites layer and objects layer.I'm trying to draw the map, then the player animations and then the objects on the map. This way I'll be able to have the player walk behind an object. This works for single sprites but not for animations. When I run the game, it doesn't draw the animation and if I render the animation continuously, the object layer is never reached. What can I do to get around this?

```
public class PlayerRenderManager {
.....

//Animation for when the player is moving up
public Animation<TextureRegion> playerUp() {
    TextureRegion[][] tmp = TextureRegion.split(textureUp, 32,32);
    TextureRegion[] walkUpFrames = new TextureRegion[4];
    sprite = new Sprite(textureUp);
    int index = 0;
        for (int j = 0; j < 4; j++) {
            walkUpFrames[index++] = tmp[0][j];
        }
        animation = new Animation<TextureRegion>(1f/30f,walkUpFrames);
        return animation;
}

```

Rendering class

```
public class MapRenderManager extends OrthogonalTiledMapRenderer {
......

private float stateTime;
public void render(Player player, ArrayList<Actor> actors, ArrayList<Projectiles> projectiles, PlayerRenderManager playerrender) {

    stateTime += Gdx.graphics.getDeltaTime();
    beginRender();
    int currentLayer = 0;
    for (MapLayer layer : map.getLayers()) {
        if (layer.isVisible()) {
            if (layer instanceof TiledMapTileLayer) {
                renderTileLayer((TiledMapTileLayer) layer);
                currentLayer++;

                // draw sprites if ground layer has been rendered and object layer is yet to be rendered
                if (currentLayer == drawSpritesAfterLayer) {

                    batch.draw(playerrender.playerDown().getKeyFrame(stateTime, true),0,0);

                } else {
                    for (MapObject object : layer.getObjects()) {
                        renderObject(object);
                    }
                    for (int i = 0; i < projectiles.size(); i++) {
                        projectiles.get(i).getProjSprite().draw(this.getBatch());
                    }
                }
            }
        }
    }
    endRender();
}

```

# Answer
I solved it on my own! I needed to stop rendering the map, then draw the animation before rendering the rest of the map again.

```
public void render(Player player, ArrayList<Actor> actors, ArrayList<Projectiles> projectiles, PlayerRenderManager playerrender) {

    beginRender();

    int currentLayer = 0;
    for (MapLayer layer : map.getLayers()) {
        if (layer.isVisible()) {
            if (layer instanceof TiledMapTileLayer) {
                renderTileLayer((TiledMapTileLayer) layer);
                currentLayer++;

                // draw sprites if ground layer has been rendered and object layer is yet to be rendered
                if (currentLayer == drawSpritesAfterLayer) {
                    //player.getSprite().draw(this.getBatch());
                    endRender();
                    playerrender.update(player, 0,0);
                    beginRender();

                }
                else {

                    for (MapObject object : layer.getObjects()) {
                        renderObject(object);
                    }
                    for (int i = 0; i < projectiles.size(); i++) {
                        projectiles.get(i).getProjSprite().draw(this.getBatch());
                    }
                }
            }
        }
    }

    endRender();

}

```

The endRender() and beginRender() in the middle is all that was needed to fix it!
> 0 votes

---
Tags: libgdx, animation
---


# Question
Title: A* heuristic for use with Goal Oriented Action Planner
Many of the high-level descriptions I've found for GOAP and similar planners suggest using A\* for their path-finding, but I'm struggling to implement it for my own planner. Specifically, I'm struggling with creating an *admissible* heuristic.

As a trite example, consider this set of nodes, expressed as a map of *srcCoord -\> dstCoord -\> cost* (cost is Euclidean distance with one exception):

```
{0, 0}:
  {-14, 0}: 14.0,
  {3, 3}: 4.242640687119285,
{-14, 0}:
  {10, 10}: 1.0, # exception here, call it a wormhole
{3, 3}:
  {6, 6}: 4.242640687119285,
{6, 6}:
  {9, 9}: 4.242640687119285,
{9, 9}:
  {10, 10}: 1.4142135623730951,

```

The shortest path from `{0,0}` to `{10,10}`, by 0.1421356237309501, is `{0,0} -> {-14,0} -> {10,10}`.

Euclidean distance is a reasonable heuristic without wormholes in the picture, but it's inadmissible here: It'd return `26` for `{-14,0}->{10,10}`, so it'll never expand the `{-14,0}` node and will end up incorrectly returning the path through `{3,3}`.

My planner has no connection to 2d-geometries, but it exhibits this "wormhole" behavior... an initial action doesn't appear to get us closer to our goal, but after expansion we see that it makes future actions less costly, or amplifies their effect in reaching the goal.

Here's a specific example I have in mind for amplifying the impact of future actions:

> If mid-fight a better weapon (let's assume it's better in *all* respects) appears on the ground than the one currently equipped (likely dropped by someone who died), and it won't take longer to pick it up + finish the enemy than to finish the enemy with the current weapon, then pick it up, equip it, and use it.

How can I avoid *overestimating* the remaining cost after picking up the weapon? It's tempting to say *"let's assume the best possible outcome will come to pass"*, but if there're any further options after picking up the item than equipping and using it then calculating the *best* outcome would require its own planning exercise, turning my A\* into a DFS.

Some plausible future actions that could lower our actual cost to lower the most obvious estimate:

* wield the weapon with two hands, in order to do more damage
* cast Haste on ourselves to double our attack speed
* use a weapon-specific technique, e.g. sweeping our opponent's feet / tripping them using the haft of a polearm

# Answer
Choosing a good heuristic is the hardest part of applying A\* in novel situations.

Fortunately, it can be fairly forgiving. The "null heuristic"

```
float HeuristicRemainingCost(Node node) {
    return 0.0f;
}

```

...still gives the correct least-cost path in the end. It just falls back on Dijkstra-like behaviour, searching all paths in order of cost aimlessly, rather than accelerated toward promising directions.

Any amount of improvement on this should - in at least some situations - help speed up our algorithm. For instance, for your wormhole example, we could use...

```
float HeuristicRemainingCost(Node node) {
    // The best wormhole-free path can't be shorter than a straight line trip.
    float beeline = EuclideanDistance(node, goal);

    // The best wormhole-using path can't be shorter than the path to the nearest entrance
    // plus the path from the goal to its nearest exit.
    float enterWormhole = EuclideanDistance(node, GetClosestWormholeEntrance(node));
    float exitWormhold = EuclideanDistance(goal, GetClosestWormholeExit(goal));

    // So, the best path with or without wormhole use can't be shorter than:
    return Min(beeline, enterWormhole + wormholeCost + exitWormhole);
}

```

Here we've applied what's called a "relaxation" - we've "relaxed" the problem of navigating wormholes with each entrance leading to just one specific exit, to the simpler problem where any entrance can connect to any exit. This relaxation makes our estimate simpler, without increasing the estimated length of the optimal path, so it's safe.

This will beeline to a wormhole - any wormhole - if it's closer than the goal - the correct move if the wormhole actually helps and the wrong move otherwise, but it's limited in how long it will pursue those wrong moves: once it's explored the cells near dud wormholes it will revert to normal Euclidean heuristic A\* behaviour in the spaces between.

You can see it's still a fairly naive estimate, but it doesn't have to be too clever - it only has to be better than `return 0` to be worth a try, and as long as it's admissible (never overestimates) it won't impact correctness.

It's tempting to try to get more accurate here. Say instead of taking the shortest distance from *any* wormhole exit to our goal, we take the closest wormhole entrance we found above and compute the distance of *its* particular exit from the goal. Unfortunately, that re-introduces the possibility to over-estimate the distance, making our heuristic inadmissible. It might be the case that this wormhole takes me 1000 lightyears away from my goal, right next to the entrance to another wormhole that takes me straight to the goal. So if I fixate on just the closest wormhole I found, I could disregard fruitful paths and get a sub-optimal result. If your goal is fixed, you can solve this by pre-computing path distances from all wormholes taking other wormholes into account, but otherwise the optimistic approach above is still decent.

The other saving grace here is that, for an AI trying to make decisions that pass as an intelligent player, it doesn't have to be perfect. Humans are pretty rubbish at forecasting future events. If a new weapon randomly dropped midway through the combat that radically altered the strategy of the fight, that would probably surprise a human player too! It would be OK if the human or AI's planning up to that point didn't take that remote possibility into account. As long as they re-plan when new information becomes available, and take actions that are rationally advantageous based on the observable current situation, then they'll appear to be an intelligent and formidable adversary.

(Conversely, if they take an action that looks disadvantageous, counting on a random future event to make it an advantage later, this might make the AI appear *less* intelligent in the short term, or like it's cheating by using knowledge of future rolls)

So, a good policy here is to try to be optimistic, but not precognitive. It's OK if unpredicted stuff happens down the line and forces us to re-plan, as long as we're making good decisions about the predictable stuff.

So, here's one way to do that: as a pre-processing step, stack all the abilities your character has available to it, to determine the most damage it can do in a turn.

This is a good place to apply relaxations to keep your math tractable: Haste takes one turn to cast and only applies for 3 turns, and you only have enough mana to cast it twice? Well, pretend it's always active for free - this never underestimates the advantage you get, so it never overestimates the time to kill, and it's dirt simple to calculate.

More nuanced heuristics can be more true-to-life, but profile with the crude ones first to see if your performance is adequate. There's a point of diminishing returns where making your heuristic better but more expensive to compute costs more in heuristic evaluations than it saves you in cutting down the search space.

With this crude `optimisticDamage` in hand, your heuristic could be something like this, assuming we always deal our best possible damage every turn and never have to pay any mana for it:

```
float HeuristicRemainingCost(Node node) {
    float idealTurnsToKill = Ceiling(node.opponentHealth / optimisticDamage);
    return costPerTurn * idealTurnsToKill + costPerMana * 0;
}

```

Even if it's not reliably doing that much damage in a turn, this is still a much better estimate than `return 0`, for just the expense of one division and a little pre-computation. When faced with the choice between moves A and B, and A does more damage than B for the same mana cost, or does the same damage for less mana, this heuristic is already enough for A\* to favour A over B and make faster progress toward promising directions, even if both moves are vastly weaker than the computed optimistic damage.
> 4 votes

---
Tags: algorithm, path-finding, planning
---


# Question
Title: Concept of "scene" in Godot, misunderstanding
Could anyone clarify a beginner's question in Godot?

As in this 3D video tutorial (https://www.youtube.com/watch?v=-D-IcbsdT04), the guy creates one scene for the floor, another scene for the wall, and so on.

But from the concept I have of "scene," everything that appears at the same time should be part of just ONE scene.

Why this technique of creating multiple scenes for objects that will all appear together in one (and real) scene?

# Answer
The term "scene" in the context of Godot is kind of a misnomer. What a "scene" actually is in Godot is a reusable object template you can instantiate multiple times. You can edit the instances to give custom properties to each of them or you can edit the scene itself to change the properties of all these objects together.

If you are coming from Unity, then you might find that they are conceptually very similar to what Unity calls "prefabs".

Those reusable objects can be nested in each other by adding a node to an existing scene which is also a scene. Many games use nested scenes a lot. Let's say you have a 3d adventure game where the player explores buildings in a 3d landscape. Among many other game features, the player can find books in these buildings and read them.

* You will have one game root scene with multiple "building" scenes as sub-nodes.
* Each "building" scene has multiple "room" scenes as sub-nodes.
* In those "room" scenes you have multiple "bookshelf" scenes as sub-nodes.
* In those "bookshelfs" scenes you have multiple "book" scenes as sub-nodes.

Change the material in the original "book" scene, and all the books in all the bookshelfs in all the rooms of all the buildings will be affected. Except, of course, for those where you are overriding the default material. Which you can do on any of these hierarchy levels.

For more information about scenes, see the Godot manual about scenes and nodes, about scene instancing and about nested scenes.

---

I still don't know why they call those "Scenes", though. I would guess that the thought process during development had to be something like this:

> **Developers:** I hereby present you the basic concept of the "Scene". It's a container for everything there is in your game right now.
>
> **Users:** You know what would be cool? If we could have more than one scene in our project. So the title screen and the character select screen and the game itself and the scoreboard can all be developed independently. What do you think?
>
> **Developers:** Great idea! Implemented!
>
> **Users:** You know what would be even cooler? If we could have more than one active scene at once in the game! That way I can show my scoreboard with my game in the background.
>
> **Developers:** Hmmm... How does that fit into my architecture of everything being nodes in one big tree? I got it: Scenes can now be nodes in other scenes! Implemented!
>
> **Users:** We just discovered something cool! You can abuse this system to create kind of mini-scenes which just include a single object in your game. We can put those into the main scene over and over again to duplicate objects. And then when we edit that mini-scene all the objects in the game change at the same time. Neat!
>
> **Developers:** You crazy fools! Scenes where never supposed to be used that way! This is madness... wait, actually this is a pretty clever way to use that feature. Keep doing that!
> 13 votes

---
Tags: scene, godot
---


# Question
Title: Should I move the world or move the player?
I'm about to start developing a sidescrolling game where the player's goal is to travel as far as he can in the horizontal axis before touching down. Note that I do not need to ever travel back on the horizontal axis.

I'm developing this with the AndEngine for Android which uses OpenGL and Box2d.

Before starting, I need to decide on something important: should I use the world around the player to simulate movement or actually move the player and follow him with the camera features of the game engine?

Both approaches seems to have different strengths and fallbacks, so I don't know which one is considered best. For example, what would make it easier to add power ups along the way and have a nice animated background?

Thanks!

# Answer
> 9 votes
Move the camera (attached to your player). I would imagine that your world has multiple objects such as enemies. If you went with moving the world, you would have to loop through all these objects to update their positions every time the world moved.

If you move the player, and attach the camera to the player then there is minimal resource usage. The game will get to its render phase, loop through everything once like it does every frame, and draw them at position - camera.position. Camera position would always equal your players position in this case.

# Answer
> 6 votes
I always move the camera and would recommend it - there are many reasons why I prefer this, but the most significant probably boils down to this:

1. If you move the camera and player, that's **only two entities** that need to be updated to scroll the screen.
2. If you move the entire world whenever the screen needs to scroll, that encompasses an unknown and **possibly large number of entities** that will have to be updated.

# Answer
> 4 votes
It's pretty trivial really, it doesn't really make a difference from the things you've described.

Either you move the background past the camera and the player, or you move the player and the camera with him. I suppose there's one less thing to do if you just move the background.

Although I suppose if you move the background you'll have to parent any pickups and enemies to that, which again, is trivial but it's something to think about.

Personally I would move the player because I just like things to be done in a more realistic way.

# Answer
> 1 votes
Other answers are good, but I'd like to add a few points of what's better, hoping to help someone who tries to make the same decision for a different project.

Moving the Player:

* It's simple, everything else is static(ish), so in simplistic terms, the only thing you need to do to move the player is `player.x += 5;` (pseudocode).
* It "Clicks better" for most people. When you play a game, you always think that the player moves, not the other way around. So it's easier to think of it as "The player should move, not the world", which in turn, may make it easier for someone to organise it in their heads.
* Easy to track where the player is (it's position is also its coordinates on the map)

Moving the World:

* If your game is big enough, you don't have to worry about overflow/underflow, by moving too far away from the center of the world, as the position of the player is always very close to `0`.
* Similar to above, if you mess with 3D calculations, you don't have to worry about inaccurate results with floating points, because everything you see on the screen should be quite close to `0`.
* If done correctly, you can make an "infinite" world.
* Have to track the player manually, the player's position will always be a small value, which signifies where the player is on the screen (kinda), to know if the player is on the top-left of the map or the bottom-right, you'd have to keep track of that in some way.

At the end of the day, it depends on the project. If someone is making an original Mario clone, moving the world could be complicated, while moving the player doesn't really create many problems. Wanting to make a huge open-world game though, it may be better to move the world instead.

---
Tags: 2d, android, java, side-scroller, andengine
---


# Question
Title: Integrating Bullet3 into a C++ project - Linking to libraries
I've been following the BulletQuickstart guide and I get as far as generating the vs2010 solution and converting to newer. I've also been following this very good answer from a few years ago and have included the src folder into my project.

The only thing that remains is to link the libraries after building the bullet solution but I'm not entirely sure which ones are the correct ones to use. I've tried:

* Linking against Bullet3Collision.lib, Bullet3Dynamics.lib and LinearMath.lib
* Linking against BulletCollision.lib, BulletDynamics.lib and LinearMath.lib
* Same as the above options, but with original filenames i.e. BulletCollision\_vs2010\_debug etc.

In every instance I get the usual errors when not linking properly:

```
 unresolved external symbol "void * __cdecl btAlignedAllocInternal.......

```

I have already checked the Additional Library Directories and Additional Dependencies

The small code I have calling some bullet stuff is:

```
#pragma once

#include "btBulletDynamicsCommon.h"
#include <stdio.h>

class BTPhysics
{
public:
    BTPhysics();
    ~BTPhysics();

    void Init();

private:
    btDefaultCollisionConfiguration* m_pCollisionConfiguration;
    btCollisionDispatcher* m_pDispatcher;
    btBroadphaseInterface* m_pOverlappingPairCache;
    btSequentialImpulseConstraintSolver* m_pSolver;
    btDiscreteDynamicsWorld* m_pDynamicsWorld;
};

```

Am I supposed to grab the library files from somewhere else other than the bin directory after building the bullet3 solution?

# Answer
After looking further into the differences between the Bullet libraries and my own project turns out the runtime libraries were different. **Multi-threaded Debug (/MTd)** is the default after building Bullet. Changed it to **Multi-threaded Debug DLL (/MDd)** and it works fine!
> 3 votes

---
Tags: c++, bullet-physics
---


# Question
Title: How to find position of the edge of an object?
I have two planes and I want to put both planes one after another so that I can form a road. I set them from the editor and that was very easy but I wanted to do this from code. So in the code:

```
void Start() {
  secondRoad.position = firstRoad.position;
}

```

But this just set the **second plane** in the center of the **first plane**, kind of overlapping. But I want the second plane to be placed next to the first plane where it ends right the edge of the first plane. How will I do this?

# Answer
> 3 votes
Since your pivots are in the centers of the objects, to line up the planes edge to edge horizontally you'll need to shift to the right by...

* half the width of the first (to reach its right edge from its center)
* plus half the width of the second (to reach its center from its left edge)

In this case both objects are standard Unity planes (width = 10), so assuming you haven't scaled them, the two halves add up to one whole and we get:

```
float spacing = 10f;
secondRoad.position = firstRoad.position + Vector3.right * spacing;

```

To handle arbitrary shapes without a size known in advance, you can use the bounds of their renderers to determine the appropriate spacing.

---
Tags: unity
---


# Question
Title: Moving a 2D object up & down y axis within certain limits
This was originally written to move a 2D object along the negative x axis.

Now I also want to move the same 2D object along the y axis (up and down within certain limit and at different speed than the x axis movement) while the movement along the negative x axis continues as before.

So far I have the x axis movement working the way I want, but on the y axis it goes either up or down without a limit. I don't know how to use `Mathf.Clamp` in this scenario, that is my problem.

```
public class Mover : MonoBehaviour
{

    public float speed = 1.5f;
    public float yspeed = 0.5f;

    void Update()
    {
        MoveObstacle();
    }

    void MoveObstacle()
    {
        transform.Translate(
              -speed * Time.deltaTime,
              yspeed * Time.deltaTime,
              0
        );
    }

}

```

# Answer
> 0 votes
It looks like you want either something like this:

```
var newPosition = transform.position;
newPosition.x -= xSpeed * Time.deltaTime;
newPosition.y += ySpeed * Time.deltaTime;

newPosition.y = Mathf.Clamp(newPosition.y, yMin, yMax);

transform.position = newPosition;

```

This will continue moving with `ySpeed` until it hits either `yMin` or `yMax` and hold at that height until you change the `ySpeed` variable to go the other way.

Or, if you want it to oscillate on its own, without changing the speed variable to tell it when to switch, you can use something like...

```
newPosition.y = 0.5f * (yMin + yMax)
               +0.5f * (yMax - yMin) * Mathf.Sin(Time.time * frequency);

```

This will give you a smooth wave between `yMin` and `yMax`, which you can make tighter or looser by adjusting the `frequency` variable. You can use `Mathf.PingPong` in a similar way to get a pointy saw wave instead of a smooth sine wave.

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


title: websockets authentication security

text:
# Question
Title: websockets authentication security
Im doing a online game havingclient, js html5, and server, nodejs with websockets. I've read some blogs about websockets security, and its limitations, but no real implementation or example.

Could JWT tokens in the messages sent to the server, be a good option? Meaning when the clients connect to the server, it gets a token and passes it around on every message? And use wss instead of ws.

Thanks in advance!

# Answer
WSS means Websocket over TLS. So when you force the use of WSS instead of WS, you already solved most problems. Just make sure that

1. The server certificate is valid and signed by a root CA
2. The client authenticates with their username and password every time they initiated a new websocket connection (TLS on the web usually only authenticates the server, not the client).

The TLS protocol already provides you with encrypted channels which are encrypted with an unique encryption key for each connection. That means passing a token with each message is not required because the protocol itself already takes care of telling the connections apart. If implemented correctly it should not be possible for a man-in-the-middle attacker or eavesdropper to take over the connection of a different client.

However, TLS on the web usually only authenticates the server (client-sided certificates *do* exist, but are rarely used because they are difficult to set up for the end-user of the client). So after building the TLS connection you need to make sure that the client is who they pretend to be. The usual way to do that is by authenticating them via username&password.
> 1 votes

# Answer
Simple answer: No, it would not. Even if you would use Diffie Hellman key exchange on elliptic curves along with AES encryption, it would not.

Why: There can be the man in the middle attack, where someone will get in the middle of client and server, and read all data, and just forward them. Like this, you CAN bypass even Diffie Hellman key exchange.

That is way why SSL is here, since once you have SSL cert, then no one can really decrypt the communication, and your server is identified by the cert (so I can no create a fake server, as I would not have the certificate).

Also question: What do you want to secure? Make sure that other client does not send you a message as someone else? If so, then socket connection has a unique ID, therefore, you as the server can identify who sent you the message. (as far as I know)
> 0 votes

---
Tags: node.js, security, websocket
---


title: Google street view racing game?

text:
# Question
Title: Google street view racing game?
How would one create a map for gaming using Google street view? Are there any programs for doing this? The cars, people and objects could be edited out and replaced with digital copies if the same objects for that area. Originally I was thinking GTA Local but would require a much more work.

3D game with Pre-rendered background

https://law.stackexchange.com/questions/37810/do-objects-in-the-public-view-need-licencing

# Answer
> 3 votes
This is, in a way, available from Google via their Google Maps Platform. The data provided by this platform is a combination of aerial, satellite and street view data.

I'm not sure how far down the thought process of your idea:

> The cars, people and objects could be edited out and replaced with digital copies if the same objects for that area

But that would certainly be exceptionally difficult with just the street view data alone (even more so with the limited data provided to end users). Utilizing the above listed combination of data sources, Google is able to use complicated machine learning and computer vision AI to remove the people, cars and other dynamic objects in a city environment.

# Answer
> 2 votes
What you would need to do is:

1. detect and remove certain kinds of objects from static photos
2. generate 3d models of environments from static photos

and those fully automatized and in real-time.

Doing things like that is an area which is currently heavily researched. The usual methods people use to solve them are machine learning and other AI based approaches. While I have seen some pretty impressive proofs of concept in these areas, I doubt that the technology is already far enough to do what you want. And most of what I have seen are proprietary technologies not available to the public, at least not for a license fee anyone can afford.

My estimate is that you should give the technology about ten more years.

---
Tags: loading, virtual-reality, racing, 360-video, overlay
---


# Question
Title: Player gets stuck on edges between TilemapCollider2D tiles
I'm currently working on a simple 2D Physics-Based Platformer Project. However, I ran into the following issue:
I'm using a Tilemap and a TilemapCollider2D to display the world. When I move the player object, it sometimes gets stuck on the edges between the different squares of the TilemapCollider2D.
Here is a little gif showcasing my problem. Please note that I'm continually pressing A/D to move over the surface. The stopping is the bug I mentioned:

Here is my player code:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{

Rigidbody2D rb2d;

[Header("Background Variables")]
public float speed = 5.0f;
public float maxSpeed = 10.0f;
public float jumpStrength = 10.0f;
public float friction = 2.5f;

public bool isGrounded = false;
public int walling = 0; // 0 = no wall collision; 1 = left side collision; 2 = right side collision

private void Start()
{
    rb2d = GetComponent<Rigidbody2D>();
}

private void LateUpdate()
{
    if(rb2d.velocity.x > maxSpeed)
    {
        rb2d.velocity = new Vector2(maxSpeed, rb2d.velocity.y);
    }
    else if(rb2d.velocity.x < -maxSpeed)
    {
        rb2d.velocity = new Vector2(-maxSpeed, rb2d.velocity.y);
    }

    if(Input.GetAxisRaw("Horizontal") != 0.0f)
    {
        rb2d.AddForce(speed * Vector2.right * Input.GetAxisRaw("Horizontal"), ForceMode2D.Impulse);
    }
    else
    {
        rb2d.velocity = Vector2.Lerp(rb2d.velocity, new Vector2(0.0f, rb2d.velocity.y), friction);
    }

    if(Input.GetButtonDown("Jump"))
    {
        rb2d.velocity = new Vector2(rb2d.velocity.x, jumpStrength);
    }
}

// These two methods currently have no effect, but I plan on extending them later
public void SetGrounded(bool isGrounded)
{
    this.isGrounded = isGrounded;
}

public void SetWalling(int walling)
{
    this.walling = walling;
}
}

```

My player uses a Rigidbody2D and BoxCollider2D.
Is there any good way to prevent this from happening or at least a workaround?

Thank you in advance!

# Answer
> 18 votes
After trying to write a code that merges the squares effectively (especially for large Tilemaps) both horizontally and vertically I decided to look if there is a better suited collider than the PolygonCollider2D which I've been using. Then I stumbled across a certain component and now I feel really stupid...

The trick to avoid the problem I mentioned in my question involves absolutely 0 lines of code.

1. For the TilemapCollider2D check the box "Used by Composite".
2. Then add the Component CompositeCollider2D (Found under Physics2D). This will automatically add a Rigidbody2D to your object if it doesn't have one already.
3. Change the "Body Type" of the Rigidbody2D to Kinematic unless you want physical interaction with the tilemap.
4. Profit.

I did some testing and it seems like my problem is solved now. If I should run across another error with this method, I'll update this answer accordingly.

# Answer
> 1 votes
Two things:

* Using `LateUpdate` instead of `FixedUpdate` might be the culprit - try `FixedUpdate`.
* It may also be related to the box collider on your players character - try sphere/capsule colliders instead.

---
Tags: unity, collision-detection, tilemap
---


# Question
Title: How can I evaluate varying conditions in a Scriptable Object?
I'm new to using Scriptable Objects, so this might just be a bit of confusion.

Let's say we have a Scriptable Object that defines the abilities a character might have in the game, and a character class that triggers these abilities:

```
public class Ability : ScriptableObject
{
    public string Name = "New Ability";
    public int ManaCost = 10;
    public Sprite AbilitySprite;

    public void Execute(ref Character character)
    {
        if (character.Mana < ManaCost)
        {
            return;
        }

        // Do something, like instantiating and moving the sprite

        character.Mana -= ManaCost;
    }
}

public class Character : Monobehaviour
{
    public int Health = 100;
    public int Mana = 100;

    public List<Ability> AbilityList = new List<Ability>();

    private void Update()
    {
        // Crude implementation for example purposes
        if (Input.GetKeyDown(KeyCode.Alpha1)) Abilities[0].Execute(ref this);
        if (Input.GetKeyDown(KeyCode.Alpha2)) Abilities[1].Execute(ref this);
    }
}

```

Obviously we can make numerous abilities with different mana costs, and add them to each character in the scene as needed; some characters may have a "Bolt" ability, while others might have an ability that casts "Fire." The `Execute()` method will then evaluate whether or not the character can use these ability based on the character's current mana.

But what if *some* of these abilities, all of which have similar effects, needed to also check the character's health, or perhaps a collision state, like `isGrounded`? For instance, maybe a certain ability can only be executed when the character has the appropriate mana value, and is also airborne. Would it be necessary to make many different subclasses of the `Ability` class to accommodate these different conditions, each with its own logic?

At first I tried changing the `Execute()` method to take in a bool, like this:

```
public void Execute(ref Character character, bool canExecute)
{
    if (!canExecute || character.Mana < ManaCost)
    {
        return;
    }
}

```

The problem with this is that I have to hard code the conditions for `canExecute` and compare the current ability against its `Name`, and that sort of defeats the purpose of Scriptable Objects. My goal is to be able to create abilities that might need to check varying conditions while performing the same functionality, and assign them in the inspector to each character as needed.

# Answer
It sounds like you might want to pull out your criteria to one (or more) separate types, rather than embed them in the ability itself. Here's a simple example with a condition struct that uses an enum to switch it between multiple modes. You could also just as easily define this as an interface or abstract type with multiple implementations for different criteria types.

```
[System.Serializable]
public struct CharacterCondition {
    [System.Serializable]
    public enum Criterion {
        isGrounded,
        hasMana,
        hasHealth
    }

    public Criterion criterion;

    // You can use a custom editor / property drawer to style this as a checkbox
    // if and only if a boolean criterion is selected, using 0 = false, 1 = true.
    public float value;

    public bool Evaluate(Character character) {
        switch(criterion) {
            case Criterion.isGrounded:
                return character.isGrounded == (value != 0f);
            case Criterion.hasMana:
                return character.mana >= value;
            case Criterion.hasHealth:
                return character.health >= value;
        }
    }
}

```

Then you can pair your abilities with any number of conditions - either inside their ScriptableObject (if every character using this ability SO should be subject to the same conditions), or inside the character (if different characters can use the same ability SO under different conditions):

```
[System.Serializable]
public struct ConditionalAbility {
    public CharacterCondition[] conditions;
    public Ability ability;

    public bool TryExecute(Character character) {
        // When asked to execute the ability, first check all conditions.
        // If any are false, abort!
        // (Note you can leave the array empty for unconditional abilities)
        foreach(var condition in conditions) {
            if(condition.Evaluate(character) == false)
                return false;
        }

        // We don't need "ref" here.
        // (Character is a class, so its instances are always passed by reference)
        ability.Execute(character);
        return true;
    }
}

```

So for example, your character could contain an array `ConditionalAbility[]` and attempt to trigger them with `TryExecute(this)`, processing any conditional requirements automatically inside that method.
> 1 votes

# Answer
`bool canExecute` doesn't make any sense here. How does the *character* know whether or not to pass `true` or `false` when it invokes this method? The character doesn't even know what condition the ability wants to check for!

Considering that the ability is already checking Mana, why can't it also check Health? This is, afterall, a check that the *ability* needs to make.

```
public void Execute(ref Character character)
{
    if (character.Mana < ManaCost || character.Health < HealthNeeded)
    {
        return;
    }
}

```
> 0 votes

---
Tags: unity, architecture
---


title: Passing a value to a stuct

text:
# Question
Title: Passing a value to a stuct
So I've been making a 2D grid and pathfinder using SFML. Now I ran into a problem. I've been making a vector for the path nodes.

```
struct Node
{
    std::pair <int, int> node; // position of the node <x,y>
    std::pair <int, int> previous;
    bool iswall = false;
    sf::Vector2f rectCenter = sf::Vector2f(0, 0);
    sf::Vector2f position;

};

class Gridspot
{
    Node start;
    Node end;
    std::vector <Node> Openset
    std::vector <Node> Closedset;
    std::vector <Node> Path;
};

```

I then make a function so I can set grid cell's center:

```
void Gridspot::calculaterectCenter(sf::Vector2f& center, int i, int j)
{

    for (auto path : Path)
    {
        if (path.node == std::make_pair(i, j))
            path.rectCenter = center; break;
    }
}

```

in the main:

```
for (auto path : cell.Path)
{
    if (i == path.node.first && j == path.node.second)
    {

sf::Vector2f center(box[i][j].getPosition().x + box[i][j].getSize().x / 2, box[i][j].getPosition().y + box[i][j].getSize().y / 2);

                box[i][j].setFillColor(sf::Color::Magenta);
                cell.calculaterectCenter(center, i, j);

    }

}

```

the problem that I'm facing is that when I enter the value the vector element in question rectcenter variable doesn't change.

# Answer
> 3 votes
you are copying in your ranged-for loop. You should use

`for (auto& path : Path)`

This will pass by reference and allow you to make changes to the variable correctly.

---
Tags: c++, game-design, sfml, oop
---


# Question
Title: Unity3d UnityWebRequest EscapeURL standard does not match Swift url encoding. How to decode it?
How should I decode escaped URL by unity in Swift?

I am developing a game with Unity3d. Something MMORPG. With server implemented by me in `Swift` under `Kitura framework` A framework doesn't matter that much. It is more about swift and Unity itself.

Let me describe the problem here.

Unity

```
UnityWebRequest.EscapeURL("First Last")

```

Escapes string with encoding used in the `application/x-www-form-urlencoded` content-type: https://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1 Which produce string `First+Last` where `+` maps to `" "` space.

Swift:

```
import Foundation

var str = "First+Last"
print(str)
print(str.removingPercentEncoding)

```

The character used on this string `+` isn't considered as a percentage encoding in the standard used by `swift`. It would be if the character escaped as this would be represented by `%20`.

So my server and client ended up with different string values. Later on returned from one to the other weren't equal. Which ended up considering them as two different clients.

# Answer
> 1 votes
Reason: Unity uses a different standard to escapes URLs then swift one.

Escapes string with encoding used in the application/x-www-form-urlencoded content-type: https://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1 Which produce string First+Last where + maps to " " space.

Possible solution: Is to replace `"+"` by yourself with `" "` before attempting to encode URL in swift.

```
"Encoded+String%2B".replacingOccurrences(of: "+", with: " ").removingPercentEncoding

```

---
Tags: unity, networking, unityscript, unity-networking
---


title: To use or not use ScriptableObjects?

text:
# Question
Title: To use or not use ScriptableObjects?
I have a Level Prefabs that contain enemies Prefabs inside them. Those Enemy Prefabs contain behavior script components that contain certain values controlling the behavior of this specific enemy. **The problem is that those values are almost always unique for every single enemy.**

**Should I use `ScriptableObjects` in my situation and if yes, then how exactly?**

The reason for my question is that I am totally new to `ScriptableObjects` so I wanted to ask the experts is there a way to utilize them in this situation, because I want to use the best ways / tools / features for my project right away.

# Answer
Scriptable objects are useful when you have certain tuples of data which you want to be able to maintain separately and assign to many different objects.

When each of the enemies in the scene has unique properties, then moving those properties to scriptable objects is unlikely to have any benefit. All it does is that you now need to maintain the properties of the same object in two separate places: The object in your scene and the ScriptableObject in your asset library. Having everything in one place will be a lot more convenient.

You also don't have much of a benefit when you can represent objects with different sets of properties as prefabs. For example if you have a prefab for each type of enemy which differ by their stats (among other things) then you can set these stats on each enemy prefab in the appropriate component of the prefab. Using scriptable objects gives you practically no benefit in this case.

ScriptableObjects mostly make sense when you want to reuse data between objects which do not make sense to represent with a prefab. For example, let's say you have 20 different enemies in the game and 10 different kinds of attacks which can be used by enemies. That means some enemies share attacks with each other. And maybe you also want the player to be able to use the same attacks with the same mechanics. In that case it might make sense to represent these attacks as scriptable objects so you can maintain them separately from the enemies and the player.
> 9 votes

# Answer
I just want to share another cool use for ScriptableObjects(SO).

The drag and drop capabilities of SO can be used to achieve purely visually controlled (i.e. controlled through Unity UI) strategy pattern. SO can not reference scene GameObjects(GO) and/or components but we can use delegate pattern (if I'm correct about the name) - the component passes itself (or its GO) to the SO method and that SO method does manipulations on the component and or GO.

I see SOs as a fast to implement tool that represents instances (data or behaviour) as dragable assets.

Concrete example: a MonoBehaviour (MB) that passes itself to a SO called State. The State's method loops over a list(or a complex composition) of SOs called Actions and passes the MB to each of them. Each State can modify the received MB to swap to looping different State. The result is a bunch of States that each can have its own list of Actions and transitions to States arranged purely through the inspector. In other words you have inspector controlled/designed state machine (think super simple/basic PlayMaker).
> 2 votes

---
Tags: unity
---


# Question
Title: Minimax not blocking moves on board game
I have a minimax player for the gomoku game, connect 5. The minimax player does not block the moves when there is potentially 5 in a row or 4 in a row. I would appreciate if anyone can show me what I am doing wrong please. Thank you very much.

```
    class PlayerMinimax
{
    // instance variables
    int empty = 0;
    int columns = 8;//
    int rows = 8;//
    int [][] intBoard;
    boolean justLauched = true;
    int aiPiece;
    int pcPiece;

    public Move chooseMove(Color[][] board, Color me) {
        setColorToInt(me); //change color to integers for both players
        intBoard = convertBoardtoInt(board,me); //convert board to integers.
        int best[] = miniMax(intBoard,3,Integer.MIN_VALUE,Integer.MAX_VALUE, true);
        return new Move(best[0],best[1]);
    }

      //minimax algorithm
    private int[] miniMax(int[][]mboard,int depth,int alpha, int beta, boolean maximizingPlayer)
    {
        if(depth == 0 || terminalReached(mboard) == true)
        {
            if (terminalReached(mboard))
            {
                if (checkIfWon(mboard, aiPiece)) // ours
                {
                    int [] ap = new int [3];
                    ap[2] = 1000000;
                    return ap;
                }
                else if (checkIfWon(mboard,pcPiece))
                {
                    int [] sp = new int [3];
                    sp[2] = -1000000;
                    return sp;
                } //dont handle game over situation as no need to.
            }
            else//depth is 0
            {
                int [] es = new int[3];
                es[2] = scorePosition(mboard,aiPiece);
                return es;
            }

        }
        if (maximizingPlayer)
        {
            int value = Integer.MIN_VALUE;
            int [][] clone = new int[rows][columns];
            int[] best = new int[3];
            for(int i = 0 ; i < rows ; i++)
            {
                for(int j = 0 ; j < columns ; j++)
                {
                    clone = cloneBoard(mboard); //clone board for each simulation
                    //simulatePlay
                    if(clone[i][j] == empty) //empty location
                    {
                        clone[i][j] = aiPiece; // drop the ai piece
                        int newScore = (miniMax(clone,depth -1,alpha,beta,false))[2]; //we want only the score here index 2
                        if (newScore > value)
                        {
                            value = newScore;
                            best[0] = i;
                            best[1] = j;
                            best[2] = value;
                        }
                        alpha = Math.max(alpha,best[2]);
                        if (alpha >= beta)
                        {
                            break;
                        }
                    }
                }
            }
            return best;
        }
        else // minimizing player
        {
            int minvalue = Integer.MAX_VALUE;
            int [][] clonemin = new int[rows][columns];
            int[] bestmin = new int[3];
            for(int i = 0 ; i < rows ; i++)
            {
                for(int j = 0 ; j < columns ; j++)
                {
                    clonemin = cloneBoard(mboard); //clone board for each simulation
                    //simulatePlay
                    if(clonemin[i][j] == empty) //empty location
                    {
                        clonemin[i][j] = aiPiece; // drop the ai piece
                        int newScore = (miniMax(clonemin,depth -1,alpha,beta,true))[2];
                        if (newScore < minvalue)
                        {
                            minvalue = newScore;
                            bestmin[0] = i;
                            bestmin[1] = j;
                            bestmin[2] = minvalue;
                        }
                        beta = Math.min(alpha,bestmin[2]);
                        if (alpha >= beta)
                        {
                            break;
                        }
                    }
                }
            }
            return bestmin;
        }
    }

    //check to see if any more valid moves exists, or if either player wins.
    private boolean terminalReached(int[][]curboard)
    {
        boolean term = false;
        for (int row = 0; row < rows; row ++)
        {
            for(int col = 0; col < columns; col++)
            {
                if(curboard[row][col] == empty)
                {
                    term = false;
                    break;
                }
            }
        }
        if(checkIfWon(curboard,aiPiece) == true || checkIfWon(curboard,pcPiece) == true || term == true)
        {
            return true;
        }
        return term;
    }

    private int scorePosition(int[][] curBoard, int piece)
    {
        int score = 0;

        ArrayList<Integer> window = new ArrayList<Integer>(); //array to store 5 consecutive board pieces
        //get horizontal score on the board
        for (int row = 0; row < rows; row ++){
            for(int col = 0; col < columns - 4; col++){
                window.clear(); //clear arraylist at each iteration
                for(int i = 0 ; i < 5; i++)
                {
                    window.add(curBoard[row][col+i]); //create a window of 5 pieces
                }
                score += evaluateWindow(window,piece); //getScore of that window
            }
        }
        //get vertical score of the board
        for  (int col = 0; col < columns; col++){
            for (int row = 0; row < rows - 4; row ++){
                window.clear();
                for(int i = 0 ; i < 5; i++) //window size of 5
                {
                    window.add(curBoard[row+i][col]); //each row, start at different columns
                }
                score += evaluateWindow(window,piece);
            }
        }

        //check negative diagonal slope
        for  (int row = 0; row < rows - 4; row++)
        {
            for (int col = 0; col < columns - 4; col++)
            {
                window.clear();
                for(int i = 0 ; i < 5; i++) //window size of 5
                {
                    window.add(curBoard[row+i][col+i]); //each row, start at different columns
                }
                score += evaluateWindow(window,piece);
            }
        }
        //check positive diagonal slope
        for  (int row = 0; row < rows - 4; row++)
        {
            for (int col = 0; col < columns - 4; col++)
            {
                window.clear();
                for(int i = 0 ; i < 5; i++) //window size of 5
                {
                    window.add(curBoard[row-i+4][col+i]);
                }
                score += evaluateWindow(window,piece);
            }
        }
        return score;
    }

    private int evaluateWindow(List<Integer> window, int piece)
    {
        int winScore = 0;
        int wsize = window.size();
        int oppPiece = pcPiece;
        if (piece == pcPiece){
            oppPiece = aiPiece;
        }
        int countPiece = 0; //count number of times values, 0, 1, 9 appear in the kern window. zero/one defined in constructor
        int countempty = 0;
        int countOpp = 0;
        for(int i = 0; i < wsize; i++)
        {
            if(window.get(i) == piece)
            {
                countPiece++;
            }
            else if (window.get(i) == empty) //empties
            {
                countempty++;;
            }
            else if(window.get(i) == oppPiece)
            {
                countOpp++;
            }
        }
        if(countPiece == 5){
            winScore = winScore + 100;
        }else if (countPiece == 4 && countempty == 1){
            winScore = winScore + 10;
        } else if (countPiece == 3 && countempty == 2){
            winScore = winScore + 5;
        }else if (countPiece == 2 && countempty == 3){
            winScore = winScore + 1;
        }

        if(countOpp == 4 && countempty == 1) {
            winScore = winScore - 100;

        } else if(countOpp == 3 && countempty == 2) {
            if(window.get(0) == empty && window.get(4) == empty) {
                winScore = winScore - 100;
            }
            else {

                winScore = winScore - 10;
            }

        }
        return winScore;
    }

    //convert colour to integer numbers for the players
    private void setColorToInt(Color myCol)
    {
        int aiColorInt = 0;
        int pcColorInt = 0;
        if (myCol == Color.BLACK){
            aiColorInt = 1; pcColorInt = 2;
        } else if (myCol == Color.WHITE){
            aiColorInt = 1; pcColorInt = 2; // not sure if need to swap.
        }
        aiPiece = aiColorInt;
        pcPiece = pcColorInt;
    }

    //convert the board to integer numbers and get valid moves
    private int[][] convertBoardtoInt(Color[][] board, Color me)
    {
        int [][] conBoard = new int[rows][columns]; //converted board initialised
        for (int row = 0; row < rows; row++){
            for (int col = 0; col < columns; col++){
                if(board[row][col] == null){
                    conBoard[row][col] = empty;
                }
                else if (board[row][col] == me){
                    conBoard[row][col] = aiPiece; //ai
                }
                else{
                    conBoard[row][col] = pcPiece; //computer
                }
            }
        }
        return conBoard;
    }

    //clone board to avoid referencing the original board
    private int[][] cloneBoard(int [][] curBoard)
    {
        int[][]clonedB = new int[rows][columns];
        for (int i = 0; i < curBoard.length; i++)
        {
            clonedB[i]= new int[curBoard[i].length];
            for (int j = 0; j < curBoard[i].length; j++)
            {
                clonedB[i][j] = curBoard[i][j];
            }
        }
        return clonedB;

    }

    //evaluate player's move in all directions to see if it is a win, 5 in a row.
    private boolean checkIfWon(int [][] curBoard,int piece)
    {
        //horizontal
        for (int r = 0;  r < rows; r++) {
            for(int c = 0; c < columns - 4; c++){
                if (curBoard[r][c] == piece && curBoard[r][c+1] == piece && curBoard[r][c+2] == piece && curBoard[r][c+3] == piece  && curBoard[r][c+4] == piece){
                    return true;
                }
            }
        }
        //vertical
        for (int r = 0; r < rows - 4; r++) {
            for(int c = 0; c < columns; c++){
                if (curBoard[r][c] == piece && curBoard[r+1][c] == piece && curBoard[r+2][c] == piece && curBoard[r+3][c] == piece  && curBoard[r+4][c] == piece){
                    return true;
                }
            }
        }
        //diagonals
        for (int r = 0; r < rows - 4; r++) {
            for(int c = 0; c < columns - 4; c++){
                if (curBoard[r][c] == piece && curBoard[r+1][c+1] == piece && curBoard[r+2][c+2] == piece && curBoard[r+3][c+3] == piece  && curBoard[r+4][c+4] == piece){
                    return true;
                }
            }
        }

        for (int r = 0; r < rows - 4; r++) {
            for(int c = 0; c < columns - 4; c++){
                if (curBoard[r+4][c] == piece && curBoard[r+3][c+1] == piece && curBoard[r+2][c+2] == piece && curBoard[r+1][c+3] == piece  && curBoard[r][c+4] == piece){
                    return true;
                }
            }
        }
        return false;
    }

}

```

# Answer
When you evaluate possible moves you can check if the opponent of AI has some of "not blocked 4 in a row" and give a huge negative bonus for this situation (at the start for testing purpose it can be an extremely big bonus).

So other alternatives with blocking behaviour will be chosen more likely.
> 0 votes

---
Tags: ai, board-game
---


# Question
Title: Unity shaders - blend edges of tile textures stored in an atlas
I'm creating a tile based game. The tiles can have different textures. All the textures are loaded at startup and dynamically packed in a texture atlas (this is done to make modding easier). Each tile stores the UVs of it's texture.

Here is an example from the game, in which the terrain is mostly made up of "grass" tiles, and there are also "stone" and "dirt" tiles in the center:

As you can see, the edges between different tile types are "hard". I want to make them "soft", so the tiles would **blend** into each other.

It was suggested to me to create special "edge tile" textures and use them for the edge tiles, but I would rather avoid that because it would require creating an edge tile texture for every 2 possible tile combinations (perhaps more for corners), and would massively bloat up the texture atlas.

Therefore I thought this should be done using a shader. I'm not too familiar with shaders though. I've created simple shaders that make grass sway and such, but I have no idea how to approach this problem. For starters, I'm not even sure how to "tell" the shader what are the UVs in the surrounding tiles (I need the UVs to sample the texture from the Atlas)?

Any help would be appreciated.

Thank you.

# Answer
> 1 votes
> It was suggested to me to create special "edge tile" textures and use them for the edge tiles, but I would rather avoid that because it would require creating an edge tile texture for every 2 possible tile combinations (perhaps more for corners), and would massively bloat up the texture atlas.

This is the correct way to go, but you don't have to create a separate texture for each combination of 2 blended textures. Just make each floor texture have an edge which is half alpha, and half the desired texture. Then when you place a tile on the floor, make all surrounding tiles have 2 textures, one from the newly placed tile, and one from it's old tile.

Using the same logic, you can also make corner tiles, to support a tile being surrounded by 4 different tiles, or weird shapes.

---
Tags: unity, shaders, textures, tiles, texture-atlas
---