# Question
Title: How To Blit an Image onto Only Opaque Parts of a Surface?
I want to blit an image onto the parts of a surface that aren't transparent. I was wondering if there were a quick way to do this in Pygame. I want to be able to add effects to stuff.

I know that I could use `set_at` and `get_at` to do it, but that would be too slow.

# Answer
Do a pixel by pixel set inside a loop is, as observed in the question, not efficient enough for game development. Masking is the way to go (assuming our libraries of choice implement this in an efficient way).

**How to mask in pygame**

When calling Surface.blit() you will use the special\_flags parameter to control how pixels are combined. In concrete, most situations will require the pygame.BLEND\_RGBA\_MULT and an extra image asset to use as the mask image, probably all opaque pixels to white and the rest with alpha set to 0. Procedural generation of the mask image is possible but I found more practical to use an asset.

Also I find more efficient to cache a version of the image with the mask already applied.

BLEND\_RGBA\_MULT will multiply source pixels with destination surface pixels. This can be used to achieve many funny effects, but the most useful is when your mask image contains all white pixels and those you want to discard with alpha set to 0. Alpha 0 in the mask results in alpha 0. And a white pixel in the mask results in the same color than source image.

**Demonstration**

To run the following demo you will need the following assets:

avatar1.png

avatar2.png

avatar3.png

mask.png

mask.png image is invisible with this site background color, but if you move the mouse pointer over it you will see where it is. Right click and save.

The assets were quickly made thanks to opengameart.org. Original authors require attribution so:

1. Credit Noble Master Games as follows (linking is optional): "Avatar graphics created by Noble Master Games" and link to http://www.noblemaster.com
2. Credit the artist "Liea" as follows (optional): "Avatar graphics designed by Mei-Li Nieuwland" and link to http://liea.deviantart.com

From game: http://www.ageofconquest.com/

And finally, the Python code:

```
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys, pygame
pygame.init()

size = width, height = 640, 480
black = 0, 0, 0

screen = pygame.display.set_mode(size)

# some globals we need
avatar_w = 64
avatar_h = 64

# our game objects are (inneficient) maps with two keys: rect and image
avatar1 = dict()
avatar2 = dict()
avatar3 = dict()

avatar1["rect"] = pygame.Rect(16, 16, avatar_w, avatar_h)
avatar2["rect"] = pygame.Rect(16 + avatar_w + 8, 16, avatar_w, avatar_h)
avatar3["rect"] = pygame.Rect(16 + avatar_w * 2 + 8 + 8, 16, avatar_w, avatar_h)

clickables = (avatar1, avatar2, avatar3)

# resource loading
# crash if the files are not in place (OK for now)
avatar1["image"] = pygame.image.load("avatar1.png")
avatar2["image"] = pygame.image.load("avatar2.png")
avatar3["image"] = pygame.image.load("avatar3.png")
selected_avatar = None

# procedural generation of a circled mask is possible but for now we
# will use an asset
mask = pygame.image.load("mask.png")

masked_avatar = dict()
masked_avatar["image"] = mask
masked_avatar["rect"] = pygame.Rect(size[0] / 2 - avatar_w / 2, 16 + avatar_h * 2, avatar_w, avatar_h)

renderables = (avatar1, avatar2, avatar3, masked_avatar)

def update_masked_avatar (avatar):
    global masked_avatar
    # TODO: consider clearing then blit to masked_avatar rather than
    # cloning mask each time, but it's not so simple as it sounds, when
    # you blit, you need the alphas from mask to be transferred too.
    # The lazy, I don't want to do research now, approach is to clone.
    surf = mask.copy()
    surf.blit(avatar["image"], (0, 0), None, pygame.BLEND_RGBA_MULT)
    masked_avatar["image"] = surf

# main loop
while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    mouse_pos = pygame.mouse.get_pos()

    # process the clickables list
    for obj in clickables:
        if obj["rect"].collidepoint(mouse_pos):
            if selected_avatar != obj:
                selected_avatar = obj
                update_masked_avatar(obj)

    screen.fill(black)

    # process the renderables list
    for obj in renderables:
        screen.blit(obj["image"], obj["rect"])

    pygame.display.flip()

```
> 1 votes

# Answer
I don't think there is a single call that can make objects appear on opaque parts of a screen. You would probably have to create a background class and have a function tied to that class that uses the .blit command to only show objects on the opaque parts.

```
class Background(pygame.sprite.Sprite):
    def __init__(self, image_file, location):
        pygame.sprite.Sprite.__init__(self)  #call Sprite initializer
        self.image = pygame.image.load(image_file)
        self.rect = self.image.get_rect()
        self.rect.left, self.rect.top = location

```

And inside this class have a function that calls in your objects.
> 0 votes

---
Tags: python, pygame
---


title: Update and FixedUpdate together

text:
# Question
Title: Update and FixedUpdate together
I know some differences between `Update()` and `FixedUpdate()` and recently I have used both functions in one script. The code is working, but I have a question:

Does using both of these functions cause any problems? Is it safe to use them both?

# Answer
**Update Order**

When you’re keeping track of game logic and interactions, animations, camera positions, etc., there are a few different events you can use. The common pattern is to perform most tasks inside the Update function, but there are also other functions you can use.

**FixedUpdate:**

> FixedUpdate is often called more frequently than Update.

It can be called multiple times per frame if the frame rate is low and it may not be called between frames at all if the frame rate is high. All physics calculations and updates occur immediately after FixedUpdate. When applying movement calculations inside FixedUpdate, you do not need to multiply your values by Time.deltaTime.

> FixedUpdate is called on a reliable timer, independent of the frame rate

.

**Update:**

> Update is called once per frame. It is the main workhorse function for frame updates.

**LateUpdate:**

> LateUpdate is called once per frame after Update has finished.

Any calculations that are performed in Update will have completed when LateUpdate begins. A common use for LateUpdate would be a following third-person camera. If you make your character move and turn inside Update, you can perform all camera movement and rotation calculations in LateUpdate. This will ensure that the character has moved completely before the camera tracks its position.

> To use Fixed Update, Update and Late Update Simultaneously is safe.

```
using UnityEngine;
using System.Collections;

public class CheckFunctionExecutionOrder : MonoBehaviour
{
    void FixedUpdate ()
    {
        Debug.Log("FixedUpdate time :" + Time.deltaTime);
    }

    void Update ()
    {
        Debug.Log("Update time :" + Time.deltaTime);
    }

    void LateUpdate()
    {
       Debug.Log("late Update time :" + Time.deltaTime);
    }
}
```

> So the execution order for all of is different but they run simultaneously.FixedUpdate is updated for fixed timeframe independent of device fps, Update is called per frame depend on device fps.
> 6 votes

# Answer
They are actually all running at the same time, your scripts just do stuff in those functions. Update is called once per frame and FixedUpdate is called once every "physics update" (which is once every fixed amount of time that you can adjust).

There's also LateUpdate, if you want certain functions to run after the Update function of that reference frame. For a full list of messages, see the MonoBehaviour reference.

Here's a link to the Unity tutorial that covers this.
> 2 votes

# Answer
It is safe to use Update(), FixedUpdate(), and LateUpdate() all in one script. At least I do and have never had any issues. I'll generally use Update() for my main loops, FixedUpdate() for stuff like physics, and LateUpdate() for loops I want to execute after everything else.
> 0 votes

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


title: Is this paint method okay?

text:
# Question
Title: Is this paint method okay?
I dont know why i need to call super.paintComponent() and super.repaint() to make the player's movements update, if i just put paintComponent the game seems like to always be stopped. However I think that my mistake is the render() method, if a remove it, it doesn't make any difference, so it is useless, I've been looking for the error but I still can not see it. I would appreciate some help

**Here is the paint method of the drawing class**

```
public void paint(Graphics g) {
    super.paintComponent(g);

    setFocusable(true);
    requestFocusInWindow();
    setBackground(Color.BLACK);
    player.drawPlayer(g, getPosX(), getPosY());
    enemy.drawEnemy(g);
    //I know this should not be here
    super.repaint();
}

```

**Pricipal GameLoop and render method**

```
public void run() {
    long lastLoop = System.nanoTime();
    final int TARGET_FPS = 60;
    final long OPTIM_TIME = 1000000000 / TARGET_FPS;
    long lastFPSTime = 0;
    int fps = 0;
    double delta = 0;

    while (running) {
        long now = System.nanoTime();
        lastLoop = now;
        delta += (now - lastLoop) / ((double) TIEMPO_OPTIMO);

        lastFPSTime += (now - lastLoop);
        fps++;

        if (lastFPSTime >= 1000000000) {
            System.out.println("[FPS : " + fps + " ]");
            lastFPSTime = 0;
            fps = 0;
        }

        while (delta >= 1) {
            render();
            delta--;
        }

        try {
            Thread.sleep((System.nanoTime() - lastLoop + OPTIM_TIME) / 1000000);
        } catch (InterruptedException ex) {
            Logger.getLogger(mainGameLoop.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

public void render() {
    BufferStrategy bs = this.getBufferStrategy();
    if (bs == null) {
        createBufferStrategy(2);
        return;
    }
    Graphics g = bs.getDrawGraphics();
    drawing.paint(g);
    g.dispose();
    bs.show();
}

```

And as last and least probable, I thought that maybe there is something that is not adding correctly to my window

**A normal window class**

```
Drawing drawing = new Drawing();

public Window(String title,int width, int hight, mainGameLoop mainGame){
    JFrame frame = new JFrame(title);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(width, hight);
    frame.setLocationRelativeTo(null);
    frame.setResizable(false);
    frame.setVisible(true);
    frame.add(mainGame);
    frame.add(drawing);

    mainGame.start();
    mainGame.run();

```

# Answer
`paintComponent()` method is called when you call `repaint()`. I used `paintComponent()`. It's very good solution.
> -1 votes

---
Tags: java, 2d, game-loop
---


# Question
Title: Invulnerability timer while standing on spikes
I want to decrement the player's health every .7 seconds while the warrior is standing on a spike tile. Every frame, the game calculates what kind of tile the player is walking into. I've tried calling a function that uses `setTimeout` from the spike tile code in the `walkingIntoTileType` switch statement and I've tried using `setInterval` directly in the switch statement. My current implementation has this declaration at the top of the warrior class:

```
this.interval = setInterval(function() {
            //blank
        }, 1000);
clearInterval(this.interval);

```

I then have this in the warrior movement code, which gets run every frame:

```
switch( walkIntoTileType ) {
  case TILE_GROUND:
    this.x = nextX;
    this.y = nextY;
    this.onSpikes = false;
    break;
  //other tile type code...
  case TILE_SPIKES:
    this.x = nextX;
    this.y = nextY;
    this.onSpikes = true;
  default:
    // any other tile type number was found... do nothing, for now
    break;
}
if(this.onSpikes){
    if(!this.running){
        this.running = true;
        this.interval = setInterval(function() {
            this.playerHealth--;
        }, 700);
    }
}
else{
    this.running = false;
    clearInterval(this.interval);
}

```

Despite this, the player's health never gets decremented when on the spikes, and the console returns no errors. I would think the interval is not falling victim to garbage collection since its variable is declared at the top of the class, but obviously I could be wrong.

# Answer
You need to store the last time the player tripped on a spike:

```
var spikeTimer = 0;

```

If the player stands on a spike and the difference between the current time and the spikeTimer's value is greater, than 700 ms, then damage the player, and set the timer to the current time:

```
if (Date.now() - spikeTimer >= 700) {
    spikeTimer = Date.now();
    // Damage the player
}

```
> 0 votes

---
Tags: javascript, timer
---


title: Instantiate prefab disabled scripts

text:
# Question
Title: Instantiate prefab disabled scripts
I'm creating a script to dynamicly load a menu with buttons. On every button there is a script that need to be run when the button has been clicked. For the button there is a prefab where the script in enabled on. After instantiating the prefab the script on it has been disabled. When I manually enable it by code it does nothing. When enabling the script using the editor it does wor.

My code for generating the buttons on my menu looks like:

```
 foreach (BuildingModel model in models)
    {
          GameObject tempButton = Instantiate(buttonPrefab);

          PlaceObjectToScene script = tempButton.GetComponent<PlaceObjectToScene>();

           script.objectName = model.modelLocation + "/" + model.modelName + ".fbx";

           script.gameObject.SetActive(true);
            script.enabled = true;

            tempButton.transform.SetParent(horizontalLayoutGroup.transform);

    }

```

I searched on the internet for some answers and found forum thread with the same issue but non of the sollutions works in my situation. Can someone help me how to enable the script that is default enabled on the prefab?

# Answer
> 0 votes
Ok found the issue. It was an error in my code. I had added a enabled = false in there. And is not the correct behaviour of my script.

---
Tags: unity, models
---


# Question
Title: C++ glGenBuffers does not return proper VBOID when called in thread
I'm currently learning to properly use multithreading in C++ in combination with OpenGL and GLFW, and I encounter a strange bug in my application. I'm generating a procedurally generated terrain in a sidethread, but everytime I want to create the buffer for the generated terrain(chunk), glGenBuffers() just gives me back the value I put in! It does not create a proper buffer. I even checked with gDEBugger, no VBO's created.

**Here's the pseudo code:**

```
void init(){ //This is in the main thread!
    sharedWindow = glfwCreateWindow(1, 1, "shared", NULL, NULL);
    mainWindow = glfwCreateWindow(400, 400, "main", NULL, sharedWindow);
    glfwMakeContextCurrent(mainWindow);
}

void terrainGeneratorLoop() { //This is in another thread!
    glfwMakeContextCurrent(sharedWindow);
    while(running){

        /* Generate vertex data for terrain */

        //Upload generated data into GPU:
        unsigned int m_vbo = -1;
        glGenBuffers(1, &m_vbo); //After this call, m_vbo is still -1 (Well actually 4294967295, but you get the point)
        glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
        glBufferData(GL_ARRAY_BUFFER, data.size() * sizeof(vertex), &data.at(0), GL_STATIC_DRAW);
    }
    glfwMakeContextCurrent(nullptr);
}

```

I'm pretty sure I'm doing something wrong with my context handling and that shared window. And sorry because of the fact that this is only pseudo code, my structure of the project and classes is way to complex to paste in in here!

**EDIT:** When I call the `terrainGeneratorLoop()` in the main thread, everything works as It should.

# Answer
> 1 votes
Okay, my code above is correct. I didn't properly store the shared GLFW window! That was somewhere else.

---
Tags: opengl, c++, multithreading, glfw, glew
---


title: 2D Collision Detection Problem

text:
# Question
Title: 2D Collision Detection Problem
while making my game called "Journeys of Nemo the Fish" i stumbled upon a collision detection problem. Please, help me to solve it.

The problem is: the program runs only the first if statement adjusting the coordinates of the player without taking in consideration what type of collision occurred.

Here is my code:

```
    short int py = player.getPosition().y;
    short int px = player.getPosition().x;
    short int pw = player.getGlobalBounds().width;
    short int ph = player.getGlobalBounds().height;

    for (int i = 0; i < block.size(); i++) {
        short int by = block[i].getPosition().y;
        short int bx = block[i].getPosition().x;
        short int bw = block[i].getGlobalBounds().width;
        short int bh = block[i].getGlobalBounds().height;

        if (player.getGlobalBounds().intersects(block[i].getGlobalBounds())) {
             // UP and DOWN
             if (px+pw > bx && px < bx+bw) {
                 if (py < by+bh && py > by) {
                     py = by + bh;
                 } else if (py+ph > by && py < by) {
                     py = by - ph;
                 }
             }

             break;
         }

          if (player.getGlobalBounds().intersects(block[i].getGlobalBounds())) {
             //LEFT and RIGHT
             if (py+ph > by && py < by+bh) {
                 if (px < bx+bw && px+pw > bx+bh) {
                     px = bx + bw;
                 } else if (px+pw > bx && px < bx) {
                     px = bx - pw;
                 }
             }

             break;
         }
     }

```

Here is a link to the video: Journeys of Nemo the Fish.

Thank you in advance.

# Answer
> 0 votes
EDITED

When a collision occurs

```
if (px+pw > bx && px < bx+bw) {

```

Will be true in the two collision types. There is no way to know wich type of collision is. I would create a new variable called typeOfMovement to know wether fish is moving up/down or left/right

```
short int py = player.getPosition().y;
short int px = player.getPosition().x;
short int pw = player.getGlobalBounds().width;
short int ph = player.getGlobalBounds().height;

for (int i = 0; i < block.size(); i++) {
    short int by = block[i].getPosition().y;
    short int bx = block[i].getPosition().x;
    short int bw = block[i].getGlobalBounds().width;
    short int bh = block[i].getGlobalBounds().height;

    if (player.getGlobalBounds().intersects(block[i].getGlobalBounds())) {
         // left/right
         if (typeOfMovement == 0) {
             if (py < by+bh && py > by) {
                 py = by + bh;
             } else if (py+ph > by && py < by) {
                 py = by - ph;
             }
         }
         // Up/Down
        else if (typeOfMovement == 1) {
             if (px < bx+bw && px+pw > bx+bh) {
                 px = bx + bw;
             } else if (px+pw > bx && px < bx) {
                 px = bx - pw;
             }
         }

     }

 }

```

---
Tags: c++, collision-detection, sfml
---


title: Issue with dark .PNG files in Unity

text:
# Question
Title: Issue with dark .PNG files in Unity
I made sprite assets in Krita and I exported them as .PNG files. When I import the files into Unity assets, however, they become a lot darker than the original colors. So far, I haven't found the issue, and I was wondering what's going on?

# Answer
I was experiencing the same problem and this is how I managed to finally resolve it.

In Krita under \[Image\] \> \[Properties\] I set my profile mode to "sRGB built-in"

After that I just re-exported as PNG and imported the new image to Unity, and color was as fine.
> 1 votes

---
Tags: unity, assets, image, png
---


# Question
Title: How can I get game objects and prefabs to recognize modifications in enum values from scripts in the scene window
I have made a script with several properties and enums that I attached to an empty game object. I am making changes to the values within the inspector, since they a public. How can I get the scene window to recognize these changes as they occur?

# Answer
> 1 votes
If we're talking solely about changes in the Inspector, you can use the `OnValidate()` MonoBehaviour message.

This is called in-Editor-only (including in & out of play mode) whenever an Inspector property in the script is changed.

You can use this to validate and adjust the new settings, update other object properties to reflect them, or fire off other reaction scripts & events.

This will not be called in a standalone build of the game, so you can use setter methods instead to react to runtime changes caused by other scripts in your game.

---
Tags: unity
---


title: OnClick unity from another class

text:
# Question
Title: OnClick unity from another class
I have class "Button" with function

```
public void SetOnClickListener(UnityAction listener)
{
    btn.onClick.AddListener(listener);
}

```

I have class "A" with fllow code

```
void D()
{
    Button btn = new Button();
    btn.SetOnClickListener(new UnityAction(SomeFunction));
}
public void SomeFunction()
{
    Debug.Log("Some Function was called!");
}

```

And it doesn't work. But if I do next change-\>

```
void D()
{
    Button btn = new Button();
    btn.SetOnClickListener(new UnityAction(SomeFunction));
}
public static void SomeFunction()
{
    Debug.Log("Some Function was called!");
}

```

All work correctly. Why I must use `static` and can I not use it?

# Answer
> 1 votes
Because with a static method all it needs is function index to store a reference to it. But when you are trying to pass member function it doesn't have a reference to an instance to call it from.

If you want to learn more about function pointers the best way I know of is to try implementing delegate or action in C++.

You can try passing `button.onClick.AddListener(delegate { this.SomeFunction(); });`instead of `new UnityAction(...)`. - This should work and that is how I do it.

Also, I guess you have your own class `Button` because of the constructor in `UnityEngine.UI.Button` is protected and cannot be instantiated.

---
Tags: unity
---


# Question
Title: No sound effects until DirectX reinstalled in my Monogame project; what DLL to ship?
Environment: Windows 10 (fresh install), using Monogame 3.6 (same goes for 3.5 for this matter) on DirectX projects. Problem: I can’t hear any sound effect unless I reinstall DirectX.

Before reinstalling DirectX, there is no exception or status information I could use to trace why the sound is not audible. After reinstalling, it just works. Same code, even same binary.

I don’t want my users to have to reinstall DX. This will be awkward as Win10 comes with DX pre-installed.

So I wonder if someone knows which additional DX libraries I may include in project folder so that the sound effects are audible without reinstalling DX?

# Answer
This is most likely one of the following XAudio DLLs (list taken from my own PC, date formats may be diferent for you), all present in C:\Windows\System32:

```
05/03/2008  17:04           489,480 XAudio2_0.dll
30/05/2008  15:19           511,496 XAudio2_1.dll
31/07/2008  11:40           513,544 XAudio2_2.dll
27/10/2008  11:04           518,480 XAudio2_3.dll
16/03/2009  15:18           521,560 XAudio2_4.dll
04/09/2009  18:44           517,960 XAudio2_5.dll
04/02/2010  11:01           530,776 XAudio2_6.dll
02/06/2010  05:55           518,488 XAudio2_7.dll
18/03/2017  21:57             3,584 XAudio2_8.dll
18/03/2017  21:57           574,464 XAudio2_9.dll

```

When Microsoft still issued the old DirectX SDK they frequently issued new DLLs for certain components with it, bumping the version number, and making them incompatible with any PC that was running an older version of the runtimes. Unfortunately, they also didn't include these updated DLLs with fresh installs of Windows either. The same thing happened with D3DX DLLs and hence the fact that re-installing DirectX appears to fix it. It's not actually a full reinstall of DirectX; all that happens is the missing DLLs are copied over and everything then works.

The good news is that this most likely won't affect your users. Anybody who has run a Direct3D 9 game on their PC has likely already had the DLLs updated. If not the DirectX End-User Runtime Web Installer provides a lighter download that will only grab the missing components.
> 1 votes

---
Tags: directx, monogame, sound-effects, dll
---


title: Applying a face image to a mesh head

text:
# Question
Title: Applying a face image to a mesh head
I'm playing around with 3D graphics programming and it's only a few weeks I'm into OpenGL and able to render meshes with textures with few basic transformations.

I've a hobby project where I want to apply a picture of human face on a 3D mesh head. I'm not very clear about the best programmatic approach to do that.

I read about how textures are created using a UV map which is created using some sort of projection of vertices in 3D onto a 2D image plane. This UV map is taken as reference to create the texture so that the texture appears correctly when it folds around the 3d mesh object.

So for my application let's say I've 3D mesh head with a UV map. I'd like my application to map the picture of my face onto this UV-map and create a texture which folds as seamlessly as possible on the 3D mesh head.

Please suggest some approaches I can explore. Also what kind of image processing algorithm I should refer and what libraries would best suit my needs?

Edit 1: Please check a similar app which is in market. https://play.google.com/store/apps/details?id=itseez3d.game.avatar&hl=en They are taking only one selfie image and superimposing it with a UV-map template to create it. I'd like to do something on similar lines.

# Answer
> 7 votes
I am one of the developers of the itSeez3D application you linked in your post. Accidentally stumbled upon your question.

@Kevin van der Velden provided an entirely relevant reference here, I would not say it took us five years, but definitely not less than a year :)

There are several problems with the simplistic approach you're describing. First of all, if you just get the static mesh and try to use human photo as a texture you won't get anywhere near as convincing results. Human faces are intrinsically different in shape and to infer the 3D shape we use deep learning algorithms. With a bunch of trained neural networks we can predict the 3D shape of the face from the selfie (not precisely, but rather accurately). Thus we don't use static models, but rather each generated model is unique.

The other problem is an alignment of the texture. Of course, eyes on the texture should correspond to the eyes on 3D mesh, same with nostrils, etc. This is actually easier to achieve, you can use face landmarks to roughly align the texture.

Actually, the app mentioned in the post uses publicly available Web API that we created, it is called Avatar SDK. You can find the documentation here.

With this API you can send any human photo to our server, the neural networks will do their job and will generate a textured model of the human head for you with a bunch of available haircuts (currently in .ply format). There's also a Unity plugin for even easier integration. We're actively developing this SDK constantly adding features and we're strongly encouraging you to try it. It is free for trial and demo use, so you're not losing anything I guess. Please ask me here or write to support@itseez3d.com if you have any questions. Good luck!

---
Tags: textures, rendering, 3d-meshes, uv-mapping, image-processing
---


# Question
Title: How to setup different weapon colliders for multiple weapons in Unity2D?
I want to design a Metroidvania style game that uses different primary weapons, having very different hitboxes. I understand that many devs simply hardcode a collider in front of the character, but what would the most efficient way to organize multiple colliders (so that you would activate one whenever its corresponding weapon is swung)?

Also, is it possible that ray casting may be a better option for this function?

# Answer
> 1 votes
You might consider using OverlapArea instead of a collider for the hitbox. Then the hit area is programmatically defined, instead of a box manually placed in the scene.

Of course you may find that editing it is a little trickier now that it's not a box in the scene; that's pretty easy to handle by drawing a custom Gizmo in the Scene view.

---
Tags: unity, 2d, collision-detection
---


# Question
Title: rotate object 0 to 90 with speed 1 then wait then 90 to 0 degree with 1 speed unity c#
i want to Rotate my object 0 to 90 degree with 1 speed --\> then wait for 3 Sec ---\> Then Rotate again 90 to 0 degree with 1 speed --\> Then wait for 3 sec

i need above process in loop

i m success with it but it working only 1 time in Start Function

In update function its not working

below my code

```
IEnumerator Start()
{
    StartCoroutine( RotateMe1(Vector3.forward * 90f, 1f));
    yield return new WaitForSeconds(3);
    StartCoroutine(RotateMe2(Vector3.forward * 0f, 1f));
    yield return new WaitForSeconds(3);
}

IEnumerator RotateMe1(Vector3 byAngles1, float inTime1)
{
    var fromAngle1 = transform.rotation;
    var toAngle1 = Quaternion.Euler(transform.eulerAngles + byAngles1);
    for (var t = 0f; t < 1; t += Time.deltaTime / inTime1)
    {
        transform.rotation = Quaternion.Lerp(fromAngle1, toAngle1, t);
        yield return null;
    }
}

IEnumerator RotateMe2(Vector3 byAngles2, float inTime2)
{
    var fromAngle2 = transform.rotation;
    var toAngle2 = Quaternion.Euler(transform.eulerAngles + byAngles2);
    for (var t = 0f; t < 1; t += Time.deltaTime / inTime2)
    {
        transform.rotation = Quaternion.Lerp(fromAngle2, toAngle2, t);
        yield return null;
    }
}

```

Below my Update Function code

```
void Update()
{
    StartCoroutine(RotateMe1(Vector3.forward * 90f, 1f));
    StartCoroutine(Wait());
    StartCoroutine(RotateMe2(Vector3.forward * 0f, 1f));
    StartCoroutine(Wait());
}

IEnumerator RotateMe1(Vector3 byAngles1, float inTime1)
{
    var fromAngle1 = transform.rotation;
    var toAngle1 = Quaternion.Euler(transform.eulerAngles + byAngles1);
    for (var t = 0f; t < 1; t += Time.deltaTime / inTime1)
    {
        transform.rotation = Quaternion.Lerp(fromAngle1, toAngle1, t);
        yield return null;
    }
}

IEnumerator RotateMe2(Vector3 byAngles2, float inTime2)
{
    var fromAngle2 = transform.rotation;
    var toAngle2 = Quaternion.Euler(transform.eulerAngles + byAngles2);
    for (var t = 0f; t < 1; t += Time.deltaTime / inTime2)
    {
        transform.rotation = Quaternion.Lerp(fromAngle2, toAngle2, t);
        yield return null;
    }
}

IEnumerator Wait()
{
    yield return new WaitForSeconds(3);
}

```

Here i recorded Video for issue of Update Function

i attached above script on AXE in attached above Video

Please help me

# Answer
> 3 votes
Use a `Tweening` engine like `DOTween`: http://dotween.demigiant.com/

Then, you create a script like `TestRotation` and achieve your rotation in 3 lines of code:

```
using UnityEngine;
using DG.Tweening;

public class TestRotation : MonoBehaviour {

    void Start(){
        Sequence sequence = DOTween.Sequence(); // create a sequence
        sequence.Append(this.transform.DORotate(new Vector3(90f, 0f, 0f), 1f).SetDelay(3f)); // rotate it by 90 on X axis for 1 second, and delay it for 3 seconds
        sequence.SetLoops(-1); // repeat continously
    }

}

```

Tweening makes the life 300% easier, really.

# Answer
> 0 votes
In RotateMe2 you have this line: `var toAngle2 = Quaternion.Euler(transform.eulerAngles + byAngles2);`

The current `transform.eulerAngles` is (90,0,0). The byAngles2 (passed to the function from Start) is (0,0,0).

(90,0,0) + (0,0,0) = (90,0,0).

Surprise, nothing changes when you attempt to rotate. You've confused *byAngles* with *toAngles.*

Also, RotateMe1 and RotateMe2 are identical, except with differently named paramter and local variables names. So there's really no reason for it at all.

Corrected code:

```
IEnumerator Start()
{
    StartCoroutine( RotateMe1(Vector3.forward * 90f, 1f));
    yield return new WaitForSeconds(3);
    StartCoroutine(RotateMe1(Vector3.forward * -90f, 1f));
    yield return new WaitForSeconds(3);
}

```

# Answer
> 0 votes
You can use a single coroutine to do the job, use it instead. Basically, this.

```
void Start()
{
    StartCoroutine(RotateMe(Vector3.forward * 90f, 1f));
}

IEnumerator RotateMe(Vector3 byAngles1, float inTime1)
{
    while (true)
    {
        var fromAngle1 = transform.rotation;
        var toAngle1 = Quaternion.Euler(transform.eulerAngles + byAngles1);
        for (var t = 0f; t < 1; t += Time.deltaTime / inTime1)
        {
            transform.rotation = Quaternion.Lerp(fromAngle1, toAngle1, t);
            yield return null;
        }
        yield return new WaitForSeconds(1);
        byAngles1 *= -1;
    }
}

```

# Answer
> -1 votes
i got Answer from @Programmer in Stackoverflow.

```
void Start()
{
    StartCoroutine(rotateForever());
}

IEnumerator rotateForever()
{
    while (true)
    {
        StartCoroutine(RotateMe1(Vector3.forward * -90f, 1f));
        yield return new WaitForSeconds(3);
        StartCoroutine(RotateMe2(Vector3.forward * 90f, 1f));
        yield return new WaitForSeconds(3);
    }
}

IEnumerator RotateMe1(Vector3 byAngles1, float inTime1)
{
    var fromAngle1 = transform.rotation;
    var toAngle1 = Quaternion.Euler(transform.eulerAngles + byAngles1);
    for (var t = 0f; t < 1; t += Time.deltaTime / inTime1)
    {
        transform.rotation = Quaternion.Lerp(fromAngle1, toAngle1, t);
        yield return null;
    }
}

IEnumerator RotateMe2(Vector3 byAngles2, float inTime2)
{
    var fromAngle2 = transform.rotation;
    var toAngle2 = Quaternion.Euler(transform.eulerAngles + byAngles2);
    for (var t = 0f; t < 1; t += Time.deltaTime / inTime2)
    {
        transform.rotation = Quaternion.Lerp(fromAngle2, toAngle2, t);
        yield return null;
    }
}

```

just need to do in repeat forever.

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


# Question
Title: Play animation of the jump properly in Unity2D
Here is what I want to do:

* when player jumps I would like to play an animation of jumping once
* on playing it I would like to stop at the penultimate animation frame till the player falls to the ground
* on falling to the ground I would like to play the last frame of the animation

Here is a screenshot which I hope will make my objective clearer:

Here is an idea I have right now:

1. I will add an event to occur exactly between penultimate and last animation frames, this even will stop animation.
2. When grounding I will add an event which will continue my animation to play till the end.
3. At the end I will use a flag to say all other animations that they are free to play.

Here is stuff which I think is a flaw:

* using of flags will make any code messier in general
* there will be problems if a user jumps once and try to run, jump again or do something that needs an animation right away after grounding because the last frame will be playing at that time
* I do not know how to stop animation, since according to this stopping an animation also Rewinds it to the Start, while I do not want to rewind it to start, but stop before the last animation frame.

# Answer
> 2 votes
**Jump Animation in 2D Games**

> There are three main state in any Jump state which can be understood with the help of this image

.

so for smooth jump animation-

> First thing we need to set the First and Last frame similar so that it will be look repeatable.

Then we have a great conversation that

> How many number of frame we need to apply for particular Animation. Its actully depend on your Game. If you are making a Mario style game you need less number of frame and if you are wanna make Limbo kind of game you need more animation sprite.

So for

> **Mario** kind of game I prefer simple sprite sheet animation which has all the three type of stages animation.

and if you are intrested in making

> **Limbo** kind of character animation you need to use **Spine Tool** which is best for your 2D Character Skeletal animation either character animation VFX animation. You can check it from this link also http://esotericsoftware.com/

Now ***what kind of animation you need to create is depend on your game*** . Like your character can do **Double jump\*** or ***Wall Jump*** or either ***Single jump*** so you need to aware about all of the things first. so for

> **Single Jump:** We can use single animation state in which you can use all the three animation sprite (e.g Jumping, Falling, Landing).

and for

> **Double Jump and Wall Jump** You need to create a blend tree.(e.g jumping state, falling state, landing state)

I would like to show you my 2D Character Animation Controller and Blend tree.

> Animator controller used to handle different conditions to handle or to switch between different state animation.

and

> Blend tree is used to controller different state of a single animation state .Like Jumping( Jump, Fall, Landing).

# Answer
> 2 votes
It would be smarter to create a separate animation for the landing frame, and make sure your current animation is set to not loop when you click on it in the inspector. Use an animation controller to switch to the landing animation when you hit the ground.

---
Tags: unity, 2d, animation, jumping
---


# Question
Title: Is it possible to configure a unity project so it only runs on a device?
I am want to give someone a sample Android Unity project and I want them to be able to run it only on a device, not the simulator. Is there a way that I can configure the project so that it will only run on a device?

# Answer
I'm not very well-versed with Unity and Android interaction but perhaps you can use android developer's answer over on SO to identify if you're running on an Android emulator and then terminate the application if `isEmulator` returns true.

Here's what you need to check to see if the app is an emulator. If any of these statements (one for each line) return true it is an emulator.

```
Build.FINGERPRINT.startsWith("generic");
Build.FINGERPRINT.startsWith("unknown");
Build.MODEL.contains("google_sdk");
Build.MODEL.contains("Emulator");
Build.MODEL.contains("Android SDK built for x86");
Build.MANUFACTURER.contains("Genymotion");
(Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic")); // Note the &&
"google_sdk".equals(Build.PRODUCT);

```
> 1 votes

---
Tags: unity, android
---


title: Increase friction with a friction joint

text:
# Question
Title: Increase friction with a friction joint
I'm making a topdown 2.5D game (think the legend of zelda: a link to the past) using libgdx and box2D.

to simulate friction from a topdown perspective, i've set the gravity for the box2D world to 0, and added a friction joint to simulate friction with the floor.
this joint requires 2 bodies, one moving and one stationary and it slows down the moving one simulating friction.
my movable body is a dynamic body (player), and my stationary body (anchor) is a static body that is a sensor (to avoid collisions with bodies)

now I've increased the speed of the playable character, and it feels like he's skating over the ground.
I want to increase the friction, but after I'm not noticing any difference after changing variables.

the variables i've tried changing (that didn't seem to do anything) include:

* the .friction on the fixtureDef of either body (player + anchor)
* the size of the anchor
* the .maxForce of the joint

How do I increase the friction caused by a friction joint in libgdx's box2D implementation?

# Answer
After some further fiddling with the variables, increasing the maxForce on the FrictionJointDef did in fact increase the friction. it just needed a very large number (i'm using 55k) to get to a value that feels good.
> 1 votes

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


# Question
Title: QuadTree: store only points, or regions?
I am developing a quadtree to keep track of moving objects for collision detection. Each object has a bounding shape, let's say they are all circles. (It's a 2D top-down game)

I am unsure whether to store only the position of each object, or the whole bounding shape.

If working with points, insertion and subdivision is easy, because objects will never span multiple nodes. On the other hand, a proximity query for an object may miss collisions, because it won't take the objects' dimensions into account. **How to calculate the query region when you only have points?**

If working with regions, **how to handle an object that spans multiple nodes?** Should it be inserted in the nearest parent node that completely contains it, even if this exceeds the node's capacity?

Thanks.

# Answer
> 4 votes
If storing extended objects (regions) in a quadtree, the object should be referenced from all the leaf nodes it touches. I wouldn't try to find the least common ancestor and store it there, because then e.g. a small object that happens to cross a high-level boundary will end up in a very high node, and must be tested against everything else in that large, high-level node when you do collision queries and suchlike.

However, you also have to be careful because large objects could end up being referenced from many nodes, making them expensive to update when they move around, and causing them to be re-checked many times for collisions etc. Depending on your use case it might be worth using some kind of heuristic to store large objects at a higher level in the tree, but this would complicate the algorithms, so I probably woudn't bother unless you establish that it's really a performance problem in your particular case.

Similarly, to query a region, the query should look at all the leaf nodes the queried region touches.

These basically use the same algorithm, which is to start with a region and push it down through the tree to find the leaf nodes it touches. It's a depth-first traversal, but at each node you can prune any children that don't touch the region. You'll need to maintain a stack to keep track of where you are in the traversal.

# Answer
> 4 votes
You must store it in the smallest node that completely contains it- even if this exceeds capacity (use a resizable container).

# Answer
> 2 votes
I would add this as a comment in response to @Nathan Reed's answer, except it's too big to be a comment, and is perhaps in any case worthy of being a separate answer.

We were doing precisely what was proposed in his answer, and in fact have comment in the source linking to this page. For the most part, it has worked extremely well, except that once every two or three months, we've been losing a server at random that has gone non-responsive due to massive duration of search queries.

The root cause of the problem came to my attention while doing a performance check to try and figure what was causing this. It's likely only a concern if you permit overlapping objects. In our game we do, and in a worst case scenario it occasionally lead to a performance killing depth spike.

We had one edge case where about 100 objects, all with with bounding disks, were clustered in very close proximity. That lead to the problem of a very deep spike in the tree, because we got to the point where objects were larger than the area covered by the quadtree nodes, so each new object was showing up in multiple nodes, leading to massive subdivision of the tree, thus snowballing the problem out of control.

The takeaway from this is that if you allow object regions to overlap, keep a close eye on things if you get tight clusters of objects, to ensure your tree doesn't get too deep.

The solution I'm currently investigating is to store objects as points, and then when doing a search, increase the bounds of the search rectangle by the maximum radius stored in the tree. That should work for us, because the tree is a first pass search, we then do a true circle based range check, along with a few other criteria checks, so the extra false alerts will get filtered out.

Your actual mileage may vary.

---
Tags: quadtree
---


# Question
Title: How do you transform a coordinate system from Cartesian to Isometric?
*Apologies if my example is a bit contrived, I've been trying to figure out how to apply matrix transformations to this coordinate problem, and I'm not getting the right output. I need to understand the math for this (some pseudo code might be helpful). See graphic on bottom*.

Assume a game world has four properties `World => ( ORIENTATION = angle, MAP_SIZE = [mw,ml], CELL_SIZE = [cw, cl])`

Now assume we have a World instance called `World_A` with the following properties:

`World_A = ( -90, [4096,4096], [64, 64])`

In other words, `World_A` has a 2-dimensional, `4096 x 4096` pixel map with an initial orientation of `-90 degrees` (inverse Cartesian plane), which can be divided by `64 x 64` named cells (denoted by their calculated subcoordinates `[p,q]` e.g. Cell\_p\_q), and an active cursor (denoted by its rendered position `[x,y]`)

Using the coordinates of an active cursor `[x,y]` we can calculate which cell the cursor is over (some Cell\_p\_q) and designate that cell the `Active_Cell` which is then highlighted. Example: if the cursor is at `[8,16]` then we determine that it's over `Cell_1_1` and `Active_Cell = Cell_1_1`.

Now-- let's add a special mirror world called World\_B where `World_B = Isometric(World_A)`

Both worlds share the same `Cursor` with position \[x,y\].

**How do I transform the World\_A( Orientation, Map, Cells) to the isometric equivalent of World\_B( Orientation, Map, Cells), such that when the Cursor is over either map, the right Active\_Cell is highlighted?**

---

Here's a quick screenshot of what I'm experimenting with; you can see in this graph that World\_A is overlaying World\_B coordinates. My math is brute-force contrived, but it works, what I want is to understand the matrix transformation way of doing this.

# Answer
Assuming "up" is to the right top by default (with an orientation of 0) you need to rotate the coordimates by -45° plus the orientation in degrees, then scale it on the y axis by half. This results in the

```
| cos -45° + orientation, sin -45° + orientation |   |0.5,   0|
|-cos -45° + orientation, sin -45° + orientation | * |0  , 0.5|

```

matrix.
> 2 votes

# Answer
To convert Cartesian coordinates to isometric the basic matrix operations are:

1. Rotate 45 degrees
2. Scale ("squish") along vertical axis

You can composed the rotation and scaling into a single 2X2 matrix. If you want to also include a translation (to move the origin of your isometric projection), you'll have to use a 3X3 matrix.

This related answer goes into more detail with diagrams and pseudo-code. (Note I think there is a slight flaw in the pseudo-code because you need to apply the transformation matrix to the mouse position, too.)
> 1 votes

---
Tags: transformation, coordinates
---


# Question
Title: How can I get fastest region server in Photon C++ Client API?
I am facing problem with my online multiplayer board game. It takes long time to create and join room. Also sometimes other player doesn't get the data. After searching all over the Photon C++ code I found this function :

```
void NetworkLogic::onAvailableRegions(const ExitGames::Common::JVector<ExitGames::Common::JString>& availableRegions, const ExitGames::Common::JVector<ExitGames::Common::JString>& availableRegionServers)
{
    EGLOG(ExitGames::Common::DebugLevel::INFO, L"%ls / %ls", availableRegions.toString().cstr(), availableRegionServers.toString().cstr());
    mpOutputListener->writeLine(L"onAvailableRegions: " + availableRegions.toString() + L" / " + availableRegionServers.toString());
    // select first region from list
    mpOutputListener->writeLine(L"selecting region: " + availableRegions[0]);
    mLoadBalancingClient.selectRegion(availableRegions[0]);
}

```

In the last line its just passing 0th region of the available regions. I think that region could be the slower one. Anyways, I am still facing the problem and I need help. Thanks.

# Answer
The optional Listener::onAvailableRegions() callback only gets called, when you pass RegionSelectionMode::SELECT to the Client constructor. This approach is useful when you have special criteria for which region you want to choose or when you already know your preferred region. If you simply want to connect to the region with the lowest ping of all available server regions, then please use RegionSelectionMode::BEST instead. In that case your onAvailableRegions() implementation won't get called, but instead the client on receiving the list of available regions automatically sends a couple of pings to each of them and then continues with connecting to the region which had the lowest average ping result.

Please note that pinging takes a moment as the Client sends several pings (5 per region) to all available server regions of which some are located at the other end of the world. Therefor when pinging occurs, then the time for the initial connect() call on a freshly created Client instance will take up to 4 seconds longer than normal. For this reason the Client caches the ping result and directly uses the cached value for further connections. However the Client does not store the ping result (which can be retrieved by a call to Client::getRegionWithBestPing() (only after you have successfully connected with RegionSelectionMode::Best - in all other cases it just returns an empty string) ) in permanent memory so that your app should store it in a file.

This way your app can check if it already has a stored best region and then just use RegionSelectionMode::SELECT and pass the region code for this stored region to selectRegion() to shorten the time that is needed for the initial connection of a newly created Client instance considerably. You only should use RegionSelectionMode::BEST, if your app does not have a stored region yet, or if the user through your game UI explicitly requests to re-ping all regions.

In your stack exchange profile it says that you are located in India. The region at index 0 usually is the European region that is hosted in Amsterdam and the ping between Western Europe and most of Asia is rather high. Choosing the Indian region that is hosted in Chennai (the one with the "in" token) should give you a lot better results.

You can find the list of available regions, their tokens and where each of them is hosted at https://doc.photonengine.com/en-us/realtime/current/reference/regions
> 1 votes

---
Tags: c++, multiplayer, online, photon
---


# Question
Title: How can I fade a game object in and out over a specified duration?
I would like to know how I can fade a game object in and out. I would like to achieve this using a C# script. As I am quite new to Unity I've read about coroutines but still haven't fully grasped the concept. I would appreciate some assistance.

# Answer
> 1 votes
Assuming you've already configured your material in the Inspector to use transparent blending (otherwise it will ignore the mucking with alpha we're doing below), you can use a simple coroutine like this:

(If using a SpriteRenderer, you'd modify the color property of the SpriteRenderer rather than passing the material, but the rest can stay the same)

```
// Define an enumerator to perform our fading.
// Pass it the material to fade, the opacity to fade to (0 = transparent, 1 = opaque),
// and the number of seconds to fade over.
IEnumerator FadeTo(Material material, float targetOpacity, float duration) {

   // Cache the current color of the material, and its initiql opacity.
   Color color = material.color;
   float startOpacity = color.a;

   // Track how many seconds we've been fading.
   float t = 0;

   while(t < duration) {
       // Step the fade forward one frame.
       t += Time.deltaTime;
       // Turn the time into an interpolation factor between 0 and 1.
       float blend = Mathf.Clamp01(t / duration);

       // Blend to the corresponding opacity between start & target.
       color.a = Mathf.Lerp(startOpacity, targetOpacity, blend);

       // Apply the resulting color to the material.
       material.color = color;

       // Wait one frame, and repeat.
       yield return null;
   }
}

```

You can use this like so:

```
// .material getter clones the material,
// so cache this copy in a member variable so we can dispose of it when we're done.
_myMaterial = GetComponent<Renderer>().material;

// Start a coroutine to fade the material to zero alpha over 3 seconds.
// Caching the reference to the coroutine lets us stop it mid-way if needed.
_currentFade = StartCoroutine(FadeTo(_myMaterial, 0f, 3f));

```

# Answer
> 1 votes
If you are using a mesh, you will need to adjust the color on the material you are using with your mesh renderer like this.

```
GetComponent<Material>().color = somevalue;

```

If you are using a sprite, you can change the color from the spriterenderer like so:

```
GetComponent<SpriteRenderer>().color = somevalue;

```

The way I would suggest making your gameobject fade in and out is with two functions, FadeIn() and FadeOut().

```
    void FadeIn()
{
    renderer.material.color = new Color(1, 1, 1, Mathf.Lerp(0, 1, FadeTime));
    if (FadeTime > 1)
    {
        FadingIn = false;
    }
}
    void FadeOut()
{
    renderer.material.color = new Color(1, 1, 1, Mathf.Lerp(1, 0, FadeTime));
    if (FadeTime > 1)
    {
        FadingOut = false;
    }
}

```

Full code here: https://hastebin.com/upeqihamin.cs

Also, you need to make sure that if you are using a mesh and the default shader, the Rendering Mode, **must** be set to Fade or Transparent

# Answer
> 0 votes
The code from Ariss is quite ok, but if you want to take care of how long lasts the fade transition, it would be easier to use coroutines.

Coroutines in Unity are declared like **IEnumerators**

```
IEnumerator SomeAsyncStuff ( /*whatever parameter*/ )
{
    // some code
    // coroutines must have a 'yield' statement
    // which stops its execution for X time,
    // depending on the yield statement
    yield return new WaitForEndOfFrame ();    // this stops execution until next frame
}

// StartCoroutine is the method that invokes a coroutine
void Start () { StartCoroutine ( SomeAsyncStuff () ); }

```

Also, objects must have a material that supports transparency — Standard Shader does if rendering Mode is set to "Fade" or "Transparent". But the thing is, you don't want your object to be transparent when it's not fading. Mostly because semi-transparent objects don't cast shadows.

```
// this changes Standard Shader render mode
// 0 - opaque
// 1 - cutout
// 2 - fade
// 3 - transparent
material.SetFloat ( "_Mode", 0 );

```

Here you have complete code.

It's commented so you know what everything is there for.

---
Tags: unity
---


# Question
Title: NullReferenceException when importing model
This error most certainly is not caused by an error in my Script. I don't know where it came from, I don't know why it's here and I don't understand what problems it causes because everything seems to work just fine. But I've been getting this error for quite a while now every single time I run the Game Engine:

# Answer
It's in ModelImporter. It's a problem with one of the 3d models you're using.
> 1 votes

---
Tags: unity
---


# Question
Title: DirectX Assembler Stage, passing same data
I'm having problems with the Input Assembler.

The first time the data is passed through the pipeline, everything is fine.
But, when the index buffer (with a diffrent/higher index than before) refers to the same vertex in the first vertex buffer, then the other vertex buffers will pass the same data again.

Is it possible to change this behavior?

Here you can see that the last two vertices have the same data at obj15 and obj17 (obj 19 is the Instance data. This is only one instance) like the 2nd and 3rd vertices. But if you follow the setup below, then the last two should be:
0 4 2 1 -1 -1 1 1 0
0 5 1 -1 1 -1 2 1 0

The setup:

1 index buffer.
4 vertex buffers.
2 constant buffers.

Data for the first Constant buffer (Texture coordinates (float2)):

0.0 0.0 (top left) (UV 0)
1.0 0.0 (top right) (UV 1)
0.0 1.0 (bottom left) (UV 2)
1.0 1.0 (bottom right) (UV 3)

Secound Constant buffer (Normals (float3)):

0.0 0.0 -1.0 (Normal 0)
1.0 0.0 0.0 (Normal 1)
0.0 0.0 0.0 (not relevant) (Normal 2)
0.0 0.0 0.0 (not relevant) (Normal 3)

Data for the first Vertex buffer (Position coordinates (float3)):

-1.0 -1.0 -1.0 (bottom left) (Vertex 0)
-1.0 1.0 -1.0 (top left) (Vertex 1)
1.0 -1.0 -1.0 (bottom right) (Vertex 2)
1.0 1.0 -1.0 (top right) (Vertex 3)

Secound Vertex buffer (index of the Texture data (uint)) (one index per vertex)

0 1 2 (for Face 0)
0 1 2 (for Face 1)

Third Vertex buffer (index of the Normal data (uint)) (one index per face)

0 (for face 0)
1 (would be 0, but for now it is 1) (for face 1)

Fourth Vertex buffer (index of the Instance data (uint))
(irrelevant for this topic)

Data for the Index buffer:

0 1 2 (face 0)
3 2 1 (face 1)
Program Code:
vertex buffers:

```
vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
vertexBufferDesc.ByteWidth = sizeof(VertexType) * m->buffer.buffer_info.vertex_count;
vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; //0;
vertexBufferDesc.CPUAccessFlags = 0;
vertexBufferDesc.MiscFlags = 0;
vertexBufferDesc.StructureByteStride = 0;

vertexData.pSysMem = m->buffer.buffer_info.vertex_type;
vertexData.SysMemPitch = 0;
vertexData.SysMemSlicePitch = 0;

result = g.d3d.device->CreateBuffer(&vertexBufferDesc, &vertexData, &m->buffer.vertex_buffer);
if (FAILED(result)) return false;

```

(flags and stride are the same and they also have a data pointer)

```
texture_indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
texture_indexBufferDesc.ByteWidth = sizeof(TextureIndexType) * m->buffer.buffer_info.texture_index_count;
texture_indexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; //0;

normal_indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
normal_indexBufferDesc.ByteWidth = sizeof(NormalIndexType) * m->buffer.buffer_info.normal_index_count;
normal_indexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; //0;

```

index buffer:

```
indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
indexBufferDesc.ByteWidth = sizeof(IndexType) * m->buffer.buffer_info.index_count;
indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;

```

Input Layout:

```
D3D11_INPUT_ELEMENT_DESC polygonLayout[4];
// Create the vertex input layout description.

polygonLayout[0].SemanticName = "POSITION";
polygonLayout[0].SemanticIndex = 0;
polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
polygonLayout[0].InputSlot = 0;
polygonLayout[0].AlignedByteOffset = 0;
polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[0].InstanceDataStepRate = 0;

polygonLayout[1].SemanticName = "TEXCOORD";
polygonLayout[1].SemanticIndex = 0;
polygonLayout[1].Format = DXGI_FORMAT_R32_UINT;
polygonLayout[1].InputSlot = 1;
polygonLayout[1].AlignedByteOffset = 0;
polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[1].InstanceDataStepRate = 0;

polygonLayout[2].SemanticName = "NORMAL";
polygonLayout[2].SemanticIndex = 0;
polygonLayout[2].Format = DXGI_FORMAT_R32_UINT;
polygonLayout[2].InputSlot = 2;
polygonLayout[2].AlignedByteOffset = 0;
polygonLayout[2].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[2].InstanceDataStepRate = 0;

polygonLayout[3].SemanticName = "POSITION";
polygonLayout[3].SemanticIndex = 1;
polygonLayout[3].Format = DXGI_FORMAT_R32_UINT;
polygonLayout[3].InputSlot = 3;
polygonLayout[3].AlignedByteOffset = 0;
polygonLayout[3].InputSlotClass = D3D11_INPUT_PER_INSTANCE_DATA;
polygonLayout[3].InstanceDataStepRate = 1;

```

Vertex Shader:

```
#ifndef NUMBER_TEXTURE
    #define NUMBER_TEXTURE 256      //changes with each model
    #define NUMBER_NORMALS 256      //changes with each model
    #define NUMBER_INSTANCE 256     //stays the same for all models
#endif

cbuffer TextureBuffer : register(b0) {
    //float4 texture_type[(int)((float)NUMBER_TEXTURE / 2.0f) + 1];             //will be converted to a float2 array
    float4 texture_type[2];
};

cbuffer NormalBuffer : register(b1) {
    float4 normal_type[3];
    //float4 normal_type[(int)((float)NUMBER_NORMALS / 3.0f * 4.0f) + 1];           //will be converted to a float3 array
    //float4 NormalBuffer_padding;
};

cbuffer InstanceBuffer : register(b2) {
    matrix Instance[NUMBER_INSTANCE];
};

cbuffer MatrixBuffer : register(b3) {
    matrix view;
    matrix projection;
};

cbuffer CameraBuffer : register(b4) {
    float3 cameraPosition;
    float CameraBuffer_padding;
};

struct VertexInputType
{
    float4 position : POSITION0;
    uint tex : TEXCOORD0;
    uint normal : NORMAL0;
    uint instance : POSITION1;
};

struct PixelInputType
{
    float4 position : SV_POSITION;
    float2 tex : TEXCOORD0;
    //float3 normal : NORMAL;
    //float3 viewDirection : TEXCOORD1;
};

    PixelInputType main(VertexInputType input) {
    PixelInputType output;
    float4 worldPosition;

    //float2 Texture[NUMBER_TEXTURE] = (float2[NUMBER_TEXTURE]) texture_type;
    //float3 Normals[NUMBER_NORMALS] = (float3[NUMBER_NORMALS]) normal_type;
    float2 Texture[4] = (float2[4]) texture_type;
    //float3 Normals[4] = (float3[4]) normal_type;

    matrix world = Instance[input.instance];

    // Calculate the position of the vertex in the world.
    worldPosition = mul(input.position, world);

    output.position = worldPosition;
    output.position = mul(output.position, view);
    output.position = mul(output.position, projection);

    output.tex = Texture[input.tex];

    //output.normal = Normals[input.normal];
    //output.normal = mul(output.normal, (float3x3)world);
    //output.normal = normalize(output.normal);

    // Determine the viewing direction based on the position of the camera and the position of the vertex in the world.
    //output.viewDirection = cameraPosition.xyz - worldPosition.xyz;

    // Normalize the viewing direction vector.
    //output.viewDirection = normalize(output.viewDirection);

    return output;
}

```

if you are wondering, I was just playing around with padding a bit, but for now I left it away to reduce possible sources of errors. And the #Ifndef is just a trick to compile with visual studio, but then later insert macros with D3DX11CompileFromFile.
And finally the pixel shader.

```
Texture2D shaderTexture;
SamplerState SampleType;

//cbuffer LightBuffer
//{
    //  float4 ambientColor;
    //  float4 diffuseColor;
    //  float3 lightDirection;
    //  float specularPower;
    //  float4 specularColor;
//};

struct PixelInputType
{
    float4 position : SV_POSITION;
    float2 tex : TEXCOORD0;
    //float3 normal : NORMAL;
    //float3 viewDirection : TEXCOORD1;
};

float4 main(PixelInputType input) : SV_TARGET
{
    float4 textureColor;
    float3 lightDir;
    float lightIntensity;
    float4 color;
    float3 reflection;
    float4 specular;

    // Sample the pixel color from the texture using the sampler at this texture coordinate location.
    textureColor = shaderTexture.Sample(SampleType, input.tex);
    //return textureColor;

    return float4(input.tex.x, 0.0f, input.tex.y, 1.0f);
}

```

And to be sure that the Texture-vertex and index buffer is correct:

# Answer
Yeah, the answer is quite simple if you know the mistake.

So, the problem is that the index in the index buffer refers to an element in all of the vertex buffers.

For example, lets take a value from the index buffer, say 2 (one from question) and it would point to the third element in the vertex-buffer, the third element in the coord-buffer and also to the third element in the third element in the normal-buffer.

Solution:

replace the vertex-coord-buffer with the index buffer.
create another constant buffer with the vertex coordinates in it.
delete the index buffer.

call DrawInstanced(...) instead of DrawIndexedInstanced(...).

or just fill up the index buffer with 0 to the number of elements in the new index-vertex-buffer.
(all vertex buffers must have the same number of elements).
> 0 votes

---
Tags: directx11, pipeline, vertex-buffer, vertex-shader
---


# Question
Title: How to implement transition between screens
Last night I showed my game to my friends and they said it was a bit jumpy.

The example he gave was in the pokemon games when a battle starts music plays, the screen flashes then pixels out then the pokemon slide on from the side and the battle menu appears.

In my game you are walking along and the all of a sudden you are staring at the battle menu, I do see his point.

I am using a switch statement for my game loop, 1 is a fields and 2 is battle, in battle I run an if statement, if battle active do battle else display results screen/wait for user input.

I thought about making a state for the transition but them I would need a stater for field -\> battle, battle -\> field, town -\> field and the list goes on an on seeming like lots of repeated code to me but I cant think of a way to pause the state while i play an animation like pokemon

With that sort or architecture how would transition between screens smoothly like my mate suggests?

C++ and directX

Edit: the problem I have is that once the state is changed the update routeen for that state is not called so all the sprites disappear as they are textures and only the background remains so I cannot just play a animation then change state or it will look even worse.

# Answer
> 5 votes
I built a generic transition system for a 2d engine for iPhone. I'm going to try to explain it. This is only an approach, the implementation has more things that are not relevant.

Suppose that your engine is hierarchical, if it is not, there are a lot of of reasons why a game engine must be hierarchical. We can have two interfaces IState and ITransition inheriting from the SceneNode class. Like this:

Well, SceneNode can be updateable, this means that the parent calls the children method "update" and enabled, that receive or not input events ( so you can disable the user events when the transition is executing ).

Every state has a name, and every transition has the old and new state between the transition exists.

Ok. Now we can have two managers, Transition and StateManager, the purpose of these managers is to have a registry of all Transitions and States and offer features. These managers can be singleton to be accessible from everywhere.

With addTransition we attach a custom transition to a pair of menus, the order is important. When we call changeState, the manager is responsible of test if a transition has been added and execute it if exist.

With this simple architecture, we are to program a transition between the MainMenu to Battle.

The current scene graph is:

My transition implementation:

```
TransitionMenuToBattle : public ITransition
{
    public:
        void enter()
        {
            getOldState()->setActive( false );
            getRoot()->addChild( this );

            addChild( blackSprite );
        }

        void update( float delta )
        {
            // make fade of blackSprite
            // ...

            if ( blackSprite->getAlpha() == OPAQUE )
            {
                getRoot()->addChild( getNewState() );
                getNewState()->setActive( false );
            }

            if ( blackSprite->getAlpha() == INVISIBLE )
                exit();
        }

        void exit()
        {
            getRoot()->removeChild( this );
            getNewState()->setActive( true );
        }
};

```

When enter method finishes, the scene graph is:

When exit method is called in update:

when exit method finishes:

when the game begins we need to add the transition:

```
TransitionFactory::get()->addTransition( "StateMainMenu", "StateBattle", new TransitionMenuToBattle( ) );

```

Then, for example in a button callback from MainMenu, we can put the call TransitionFactory::get()-\>changeMenu( "StateMainMenu", "StateBattle" ); or wrap this method into:

```
IState::changeMenu( std::string newMenu )
{
    TransitionFactory::get()->changeMenu( getStateMenu(), newMenu );
}

```

You can complicate the transition much as you want. The transition has access to the two states and it can do things like overlap elements of two. The transition can receive the things that needs in his constructor. If TransitionManager detects that there is no transition added between two states can have a default behavior.

# Answer
> 0 votes
In your switch statement call to a transition routine. For a ridiculously oversimplified pseudo answer:

```
void changeState ( int destinationState, int *currentState ) {
    // check that destination state is valid
    // check that current state can transition to destination state
    doTransition ( *currentState, destinationState);
    *currentState = destinationState
}

```

\[Edit\] To call this using a switch statement that already exists you would do something like this:

```
switch (destinationState): {
1: {changeState ( 1, &currentState); break; } // switch from some state to fields
2: {changeState ( 2, &currentState); break; } // switch from some state to battle
}

```

Then you do still need to write doTransition() that would actually do that transition animation. doTransition would do your fade in/fade out/whatever you wanted it to do.

# Answer
> 0 votes
You could just make a single "transition" state, with which state you're going to and from indicated as a couple of variables in the object.

# Answer
> 0 votes
If you're not willing to change your architecture from a switch statement to using the state design pattern (which is fine, as you know your code best) then it's gonna be pretty ugly.

Assuming you're using an architecture with a fairly standard Update loop, perhaps you could have a flag checking whether a transition is required and on the next Update check for the flag being set right at the beginning of your update loop and if it's on, then play a transition and wait until the transition has completed before turning the flag off.

Quick, dirty pseudocode would be:

```
bool bStateChangeRequested;

while( bUpdate )
{
    if( bStateChangeRequested )
    {
        PlayTransition();
        WaitForTransitionToComplete();
    }

    DoStateStuff();
}

```

Hope that helps, although I'd highly recommend the state design pattern for solving this. It'll make everything so much cleaner and better organised, so a definite thing to think about in future iterations.

# Answer
> 0 votes
I use the SFML library to do all my graphics and windows and stuff, but one way of doing it is with a few variables:

```
#include <SFML/Graphics.hpp>

bool FaderHappens = false;
bool FaderTrue = false;
bool gameStarted = false;
bool gameStartedSub1 = false;
float FaderVar = 0;
int main() {
  while (window.isOpen())
  {
    sf::RenderWindow window(sf::VideoMode(840, 680), "Your Program Name",sf::Style::Default);

    window.setFramerateLimit(65);
    sf::RectangleShape Fader(sf::Vector2f(850, 550));
    while (window.pollEvent(event))
    {
      if (event.type == sf::Event::Closed)
        window.close();
    }
    window.clear();

    if (YOUR_EVENT) {
      FaderHappens = true;
      FaderTrue = true;
    }
    if (FaderTrue == true && FaderHappens == true) {
      if (gameStartedSub1 == false) {
        FaderVar = FaderVar + 63.75;
      }
    }
    if (FaderVar == 255 && FaderHappens == true && FaderTrue == true) {
      if (gameStarted == false && gameStartedSub1 == false) {
        gameStartedSub1 = true;
      }
      FaderTrue = false;
    }
    if (FaderTrue == false && FaderHappens == true) {
      FaderVar = FaderVar - 63.75;
    }
    if (FaderVar == 0 && FaderTrue == false && FaderHappens == true) {
      FaderHappens = false;
    }
    Fader.setFillColor(sf::Color(0, 0, 0, FaderVar));
    window.draw(Fader);
    window.display();
  }
}

```

This should give you a basic understanding of the logic that goes into making a fading animation. The 63.75s can be changed to make the animation slower or faster, though note that the number you put in must be the number 255 divided by any whole number (otherwise it would loop forever). I am sorry if something is mixed up, as I took this from my own project and was trying not to show irrelevant code. I believe it to be clean of any mistakes though.

---
Tags: c++, directx9
---


# Question
Title: How to create a Pixmap from an OrthographicCamera in LibGDX
I am trying to create a picture based on what one of my `OrthographicCamera` can see. LibGDX has a `ScreenUtils` class that has a `getFrameBufferPixels` method, but it does not what I want as I want to get only what one camera sees, not the whole screen.

# Answer
You need to render what the camera sees to an FBO and then get the pixmap from the FBO itself.

```
// Construct an FBO and keep a reference to it. Remember to dispose of it.
final FrameBuffer fbo = new FrameBuffer(Format.RGB565, width, height, false);

//In your render method
//Start rendering to the fbo.
fbo.begin();
//From the camera's perspective.
batch.setProjectionMatrix(camera.combined);
batch.begin();

//Draw whatever you want to draw with the camera.

batch.end();
// Finished drawing, get pixmap.
Pixmap pixmap = ScreenUtils.getFrameBufferPixmap(0, 0, width, height);
//Stop drawing to your fbo.
fbo.end();

//Now you can draw your normal screen as usual.

```

This will draw whatever you draw with your batch to your FBO from your camera's perspective. Remember to reset the projection matrix when you want to render from your main camera.
> 3 votes

---
Tags: libgdx, camera
---


# Question
Title: How to subscribe to an event fired from any Instance/Object of type X?
I'm currently working on a small game engine and I'm kinda stuck on finding the right pattern to subscribe to an event fired from any instance of type X. To understand what I'm trying to achieve, here are some code snippets:

```
 public class FireEffect : BaseEffect
 {
   public FireEffect(BaseAbility effectOwner)
   {
    this.Owner = effectOwner; // each effect belong to an ability
    this.Name = "Fire";
   }
   //apply effect on target
   public override void CalculateEffect(Unit target)
   {
    // set the event here (to get the target as argument for the event)
    this.Event = new EventDispatcher(this.Owner, new EffectEventArgs(target));
    this.Event.DispatchMyEvent(); // rise/dispatch this effect event
    base.CalculateEffect(target); // do stuffs like burn ..damage etc
  }
}

```

and let,s say we have two Units: a "dragon" with FireBall ability (contain **FireEffect**) and a "Shaolin" with a passiveAbility (contain **WindEffect**)

```
 public class PassiveAbility : BaseAbility
 {
   public PassiveAbility(Unit caster)
   {
    this.Name = "WindFury";
    this.Caster = caster; // ability caster (owner)
    this.EffectList = new List<BaseEffect>(); // effects that an ability possess
    this.EffectList.Add(new WindEffect(this));
    this.initListeners(); // subscribe to events (aka add listeners)
   }

   // apply all effects that this ability has on the selected target
   public override void DoAbility(Unit target)
   {
     foreach (BaseEffect eff in this.EffectList)
    {
        eff.CalculateEffect(target);
    }
   }
   // THE MAIN PROBLEM :
   public override void initListeners(){}

  //call this method if FireEffect.Event was rised
  public void CallBack(object sender, EffectEventArgs e)
  {
   BaseAbility ab = (BaseAbility)sender;
   this.DoEffect(ab.UnitCaster); // hit the unit caster back (revenge)
  }
}

```

How to **subscribe** via **PassiveAbility.initListeners()** to an **event** fired from **any instance of type FireEffect** (an ability that use fireEffect)?

In other words: when our dragon throws an ability with a FireEffect (like fireBall) on our friend "Shaolin", he should react to it using WindEffect via PassiveAbility.

**Notice please** that we can have so many dragons and Shaolins in this game or simulation and **any passive holder** (unit) should **only react** to the attacker (unit) etc.

Many thanks in advance for your support and contribution.

# Answer
If I understand your problem correctly, you're looking for a kind of a custom event system that behaves more like an event bus where event publishers and subscribers are loosely coupled and don't know about each other.

A naive implementation of such "event bus" would be a singleton containing a dictionary with keys being event types (i.e. plain old classes) and values being handlers accepting instance of event type as parameter. Such singleton would have generic `Subscribe()` method that would let you listen to an event type from any place and similarily a generic `Invoke()` method that would let you invoke an event from any place.

With such setup you can create an event type (for example `FireEffectUsed`) that is invoked when a dragon uses a FireEffect and holds information which Shaolin is the target. Given that all Shaolins would subscribe to this event upon creation, they would be notified about the event and the target Shaolin would be able to react by activating the WindEffect (other Shaolins would simply discard this event).

Hope this sheds some light on your problem.
> 0 votes

# Answer
It's not clear to me exactly how you're handling this now, but in C# with Unity you can use Events to get the job done. For example, you'll create your event handler (it doesn't have to follow the `object sender, EffectEventArgs e` format if you don't want it to):

```
public delegate void HandleAbilityEvent(BaseAbility ab, Unit caster);

```

This is a delegate method because we're going to treat it like a variable that's going to be passed around. There's no body because we're just telling C# what we want the signature of these delegates to look like. Next we create our event:

```
public event HandleAbilityEvent TriggerAbilityEvent;

```

This is an event is specific to the instance of the object that it's called on. For example, to use this we might do something like:

```
//When a target enters the range of our abilities, they can start listening to our events,
// you can use something like a trigger collider to detect when something has entered the
// range of your abilities
this.TriggerAbilityEvent += target.GetAbilityListener();

//Or when the target leaves our ability range

this.TriggerAbilityEvent -= target.GetAbilityListener();

```

Where each unit would also have their listener:

```
public void AbilityEventTriggered(BaseAbility ab, Unit caster) {
    //Notice the above signature matches the types of the signature of our delegate
    //Calculate events based on our defenses and possible passive abilities
    //this code is called inside the target, so we have everything needed
}

public HandleAbilityEvent GetAbilityListener() {
    //Because our signature matches the delegate signature, we can pass
    // this method back as a HandleAbilityEvent
    return AbilityEventTriggered;
}

```

You can find a more detailed explanation of events in this video I made (sorry, it's not free, but the site has a lot of useful info if you decide to sign up).
> 2 votes

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


# Question
Title: What functions should be called in C++ gameloop from Lua Script
I am using sol2 lua wrapper for my 2D game-engine to implement some lua scripting,but I have some questions about what should functions should i call from Lua scripts in c++, and i cannot find any good resources about this topic.

For example. lets say that i am trying to render a sprite on the screen, which sprite is created inside a lua script. As usually the sprite should call render() function every frame, my question is that, should i call every frame functions from Lua in my game-engine loop ? or its bad habit? i mean can i have a structure in lua like below :

```
function init()
   --called only once
end

function render()
  --called every frame in C++ gameloop
end

```

or should I implemented in other way? Can someone suggest me any books about this matter or any good resources ?

# Answer
I would generally recommend to avoid making *high volume* calls into Lua. That is *partly* about performance but mostly about engine architecture.

To get the perf bit out of the way: the bridging code between C++/Lua has overhead compared to just calling Lua from Lua or calling C++ from C++. Of course, even good Lua itself is significantly slower than decent C++ code. Some constructs very common to games - like such simple things as a 2D vector type - incur even more overhead in Lua due to its inability to have user-defined value types; that's even worse as treating such "fundamental" mathematical concepts as reference types opens one to all sorts of non-obvious bugs and hardships. The lack of static typing in Lua also starts to really hurt as the size of the code grows and the need for good accurate code navigation grows with it. In short, write as little real "game code" in Lua as possible for the best perf and likely best developer experience.

Now, on to engine architecture. You don't want a "sprite" to have its own render function, independent of whether you're working in Lua or C++ or any language. You also likely don't want many other sprite-specific functions that would be called frequently like that. Most of these features are much better suited to dedicated systems that handle all the specifics. For instance, for rendering a sprite, your sprite object should instead create a node in the graphics scene graph with the required properties (position, size, texture, etc.) and the graphics renderer then can figure out how to put the "sprite" on the screen every frame all by itself. This has several advantages:

First, it insulates the rendering code from the rest of the engine. You don't necessarily want to have a core renderer being dependent on your scripting module, or on physics, or input, or AI, or so on. Rendering should be fairly self-contained. That's going to make your code easier to read, easier to maintain, easier to optimize, and just all-around easier in general.

Second, putting *everything* related to rendering a sprite under the renderer's control allows for a lot of tricks that are very difficult to pull off otherwise. For instance, resource swapping, texture streaming, multi-threaded rendering, culling, shadowing, etc. If the graphics engine has to call back into game code or script code every time it needs to render, it's going to be very hard to branch that renderer out across multiple CPU cores and likewise hard to do many multi-pass algorithms.

The above are just as true for systems like physics, AI, and so on.

The idea then is that your game objects (sprites) should tell the low-level systems what to create and when to change them, rather than the low-level systems constantly re-querying the game objects every frame. Your script might then look something like:

```
-- asteroid.lua

function init(self)
  self.transform = game.transform.create{
    position=random_position(),
    scale=random_scale(),
    rotation=random(0, 2*PI)
  }
  self.renderable = game.graphics.createRenderable{
    texture='/images/asteroid.png',
    transform=self.transform
  }
  self.body = game.physics.createRigidBody{
    shape=game.physics.CIRCLE,
    linear_velocity=random_direction() * random_speed(),
    angular_velocity=random_number()
    transform=self.transform
  }
end

```

The individual systems like physics now have no idea that scripts exist or that other systems exist. In fact, the only thing binding these systems together at all here are that (a) they depend on a common `Transform` object so they can agree on a position, rotation, and scale, and (b) there's a Lua table somewhere that has handles to the individual systems' internal objects.

The structure above never needs to call into Lua after the object is initialized. You could of course still use Lua to hookup object-specific logic, like code to run on collision events or the like, for the high-level game scripting. The core systems though should have nothing to do with Lua.

The general architecture here is a form of component-oriented design, and with the muddling of the term one could also see it as a loose form of an "ECS" architecture (Entity-Component-System architecture).
> 3 votes

---
Tags: c++, rendering, game-loop, lua
---


# Question
Title: how to get surface direction of object in hit point in unity
I'm simulating shooting by raycasting. I want to instantiate a bullet hole or mark on the spot where a bullet hits an object. But the surface of the object at that point may have different angle or direction:

How can I find the object's surface direction to make the right transform for a bullet hole?

# Answer
> 1 votes
The direction a polygon is facing is called its "normal". Thus, you want to get the normal at the spot hit. Raycasts return that information: https://docs.unity3d.com/ScriptReference/RaycastHit-normal.html

---
Tags: unity
---


# Question
Title: Preventing a game object that has faded out from colliding with other game objects
I have the following cycle for fading sprites in and out

fade out (1 second) -\> delay (2 seconds)-\> fade in -\> delay (2 seconds)

Please see my code below:

```
IEnumerator FadeTo(Material material, float targetOpacity, float duration) {

    Color color = material.color;
    float startOpacity = color.a;

    float t = 0;

    while(t < duration) {
        t += Time.deltaTime;
        float blend = Mathf.Clamp01(t / duration);

        color.a = Mathf.Lerp(startOpacity, targetOpacity, blend);
        material.color = color;
        yield return null;
    }
}

IEnumerator EnemyCycle()
{

    while (isRepeating)
    {

        for (int j = 0; j < enemies.Length; j++) {

            var _myMaterial = enemies [j].GetComponent<Renderer>().material;
            var _currentFade = StartCoroutine(FadeTo(_myMaterial, 0f, 1f));
            enemies [j].GetComponent<CircleCollider2D> ().enabled = false;
        }

        yield return new WaitForSeconds (2);

        for (int j = 0; j < enemies.Length; j++) {

            enemies [j].GetComponent<CircleCollider2D> ().enabled = true;
            var _myMaterial = enemies [j].GetComponent<Renderer>().material;
            var _currentFade = StartCoroutine(FadeTo(_myMaterial, 1f, 1f));
        }

        yield return new WaitForSeconds (2);

    }
}

```

The above code cycle works when I am not disabling and enabling the colliders. i.e., without the following lines of code:

```
enemies [j].GetComponent<CircleCollider2D> ().enabled = false;
enemies [j].GetComponent<CircleCollider2D> ().enabled = true;

```

But when I place the two lines (as I've done in the above code), the enemy game objects don't follow the fade in and out cycle, mostly they don't even fade out. I really need to be able to prevent the enemies from colliding with other game objects when I have faded them out during my fade in and out cycle. How can I solve this issue?

# Answer
I just tested your code, it's working here for me. A few things

* Maybe there is another object interacting with this behaviour?
* Did you set the colliders?
* Are you getting any errors?
* There's a plats \[j\].GetComponent ().enabled = true;
* Also, how did u define the isRepeating variable? Is the value set to true?
* did you mean 'enemies' instead of plats ?

Sorry, i cannot comment, i dont have 50 reputation..
> 1 votes

---
Tags: unity
---


# Question
Title: Unity VR player not moving when running in device
I am following Udemy tutorials for learning VR using Unity and making a game named Ninja Slash. Everything seems to be working fine in the Unity Editor Play mode but when I run my app in a real device, my player doesn't move at all. I can't figure out what is the problem here. Here is my Player script.

```
public class Player : MonoBehaviour {

public GameObject sword;
public float speed = 4.5f;
public float walkingAmplitude = 0.25f;
public float walkingFrequency = 2.0f;
public float swordRange = 1.75f;
public float swordCooldown = 0.25f;

public bool isDead = false;
public bool hasCrossedFinishLine = false;

private float cooldownTimer;
private Vector3 swordTargetPosition;

// Use this for initialization
void Start () {
    swordTargetPosition = sword.transform.localPosition;
}

// Update is called once per frame
void Update () {
    if (isDead) {
        return;
    }

    transform.position += Vector3.forward * speed * Time.deltaTime;
    transform.position = new Vector3(
        transform.position.x,
        1.7f + Mathf.Cos(transform.position.z * walkingFrequency) * walkingAmplitude,
        transform.position.z
    );

    cooldownTimer -= Time.deltaTime;

    if (GvrViewer.Instance.Triggered ) {
        RaycastHit hit;

        if (cooldownTimer <= 0f && Physics.Raycast(transform.position, transform.forward, out hit)) {
            cooldownTimer = swordCooldown;

            if (hit.transform.GetComponent<Enemy> () != null && hit.transform.position.z - this.transform.position.z < swordRange) {
                Destroy (hit.transform.gameObject);
                swordTargetPosition = new Vector3 (-swordTargetPosition.x, swordTargetPosition.y, swordTargetPosition.z);
            }
        }
    }

    sword.transform.localPosition = Vector3.Lerp (sword.transform.localPosition, swordTargetPosition, Time.deltaTime * 15f);
}

void OnTriggerEnter (Collider collider) {
    if (collider.GetComponent<Enemy> () != null) {
        isDead = true;
    } else if (collider.tag == "FinishLine") {
        hasCrossedFinishLine = true;
    }
}}

```

Here is the screenshot for hierarchy view.

# Answer
> 1 votes
It's not clear if the problem is with your source code, but it could actually be an issue with how your scene is arranged. If you want to move the GameObject the `GvrViewer` script is attached to, you need to create a parent object, and move the parent object instead.

The `GvrViewer` script has functionality for changing its position and rotation based on the "head" of the user. While Google Cardboard does not have the 3 degrees of positional tracking, the script still modifies the position of the GameObject. In your case, it makes the GameObject stay in one spot. This counteracts all of the movement you're trying to apply to the GameObject.

So create something like this:

And make sure your movement script references the `Player` object as the one it adjusts the transform of.

---
Tags: unity, virtual-reality, google-cardboard
---


# Question
Title: Ignore UI elements when clicking to move
I have a click to move character that uses a Nav Mesh Agent and I want to ignore clicks that are made on UI elements. For example, I don't want clicking around in my inventory to move my player to the target under the inventory. The relevant part of the move script is very simple.

```
if (Input.GetMouseButton(0) && !playerHealth.isDead)
{
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;

    if (Physics.Raycast(ray, out hit))
    {
        navMeshAgent.destination = hit.point;
    }
}

```

I would think that this is a common question raised among beginner developers or that it would be covered in beginner courses, but I can't seem to find the info I'm looking for when Googling around, so I'll ask it here.

So how do I get my Nav Mesh Agent to ignore clicks made on a particular UI element? How about ignoring clicks made to any and all UI elements? Thanks.

# Answer
> 3 votes
Two things

Change to this:

* `if (Input.GetMouseButton(0) && !UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject())`

and

* Make sure your graphics have the option Raycast target set to true.

---
Tags: unity
---


# Question
Title: How to Propose an Idea as an Indie to a Big Company?
Let's say that we've got a good idea/design for a game, but we can't develop it on our own due to our beginner knowledge and skills, so instead we want to propose/sell/give the idea to one of the big publishing companies like Bandai, Ubisoft and Square Enix. Is it possible for beginners to propose ideas for big companies? and if so then how? please we need a detailed answer if possible. Thanx in advance.

\*Note: we're **NOT** saying that we want to be employees in the company, what we mean it is more like working together with the company in the way that we give them the idea of the game and they develop it and then both sides benefit.

# Answer
> 2 votes
Ideas alone are worthless. `value = idea * execution`. The best idea with 0 execution has a value of 0.

The reason is that nobody can tell if an idea which only exists on paper would be a commercially viable game. Not unless it's something formulaic which guarantees moderate sales if you throw enough budget at it. But everyone can come up with a concept for yet another first person shooter, GTA clone or grindy MMORPG. They don't need you for that.

If you have a novel idea, *you* have to prove that it will work. And the only way to do that is by actually turning it into a game and showing that there is interest.

1. Create a playable prototype. It doesn't need to be pretty, it doesn't need to run well and it doesn't need to have much content. All that matters is that it demonstrates what's new and special about your game idea.
2. Publish it (as early access alpha for money if it is worth it, or for free if you have to)
3. Generate lots of hype and groom a community
4. Make it apparent that people like playing your idea and would be willing to pay for it if turned into a game with proper production values, but that you lack the resources for developing it
5. Get into contact with publishers

There is quite a long list of games with niche game concepts which started as small indie games and then got bought up by larger publishers after they had shown that their wacky idea has market potential.

# Answer
> 6 votes
This can't be done, sorry. Big companies already have a backlog of ideas that might be great. Even small companies do. Additional ideas are pretty much worthless.

You need way more than an idea if you want to sell it. Generally the minimum that's required is a prototype and a business plan. For beginners I'd change the minimum requirement to a **working and playable** prototype and a functional development team, in addition to a business plan.

---
Tags: business
---


title: Steering Behavior Seeking

text:
# Question
Title: Steering Behavior Seeking
I am trying put a seek feature in my code.

Just frame code, not actual code.

```
 Seek(TargetPos)
{
  Vector2D DesiredVelocity = Normalize(TargetPos - currentPos)*MaxSpeed();

  return (DesiredVelocity - currentVelocity}

```

Simply when I press 2, it will change the target, 3 will change the target and so on...

Do I need to make the currentVelocity the old Desired velocity?

# Answer
Yes, you could make `currentVelocity` equal to `DesiredVelocity`.

However, this is going to make your object suddenly change direction in an unrealistic manner. If you want your object to travel more realistically, you should try interpolating from `currentVelocity` to `DesiredVelocity`, and set that to `currentVelocity`.
> 0 votes

# Answer
You do not need to make the `currentVelocity` equal the old `desiredVelocity`.

`desiredVelocity` changes every frame, as the actor changes position in relation to it's target.

Here's an overview of the situation:

You could use the resulting `steeringDirection` to calculate an incremental change to the current velocity (as per Steering Behaviors For Autonomous Characters):

```
steeringDirection = seek (targetPos);

// this limits the steering force to a maximum steering force
// to avoid unnatural quick 180 turns
steeringForce = truncate (steeringDirection, MaxForce);

// we calculate an acceleration using the actor's mass
// so bigger things can be slow and have "more inertia"
// while small seekers can be fast and more maneuverable
acceleration = steeringForce / mass;

// and add it to the current velocity, which we then clamp to
// the maximum speed of the actor
currentVelocity = truncate (currentVelocity + acceleration, MaxSpeed);

// and we update the position
position = position + currentVelocity;

```

Hope I could help shed some light on the situation :)
> 0 votes

---
Tags: steering-behaviors
---


title: When which type of draw mode to use?

text:
# Question
Title: When which type of draw mode to use?
I wrote Opengl ES wrapper, and I want to know, when I should use

> GL\_TRIANGLES, GL\_TRIANGLES\_FAN and GL\_TRINAGLES\_STRIP

I read difference from OpenGL Red Book, but still doesn't understand what kind of them and when I should use them.

# Answer
> 3 votes
First, here's an image to help visualize what we're taking about:

And some explanation:

`GL_TRIANGLES`: You send distinct triangles to draw, with each 3 coordinates representing a corner of the triangle (so (v0,v1,v2) is a triangle and (v3,v4,v5) is a triangle and so on)

`GL_TRIANGLE_STRIP`: You send a connected strip of triangles that each share an edge with the next one (so (v0,v1,v2) is a triangle, and (v2,v1,v3) is a triangle, sharing (v1,v2) edge and so on)

`GL_TIRANGLE_FAN`: You send a connected fan of triangles that each share a common corner (v0 in the image above)

As you can see, triangle fans and triangle strips require less data sent to the GPU (vs if you wanted to draw the same thing using `GL_TRIANGLES`)

# Answer
> 1 votes
You pretty much use triangle strips and fans when you can, they don't require so many data to be sent to the GPU, thus it can improve loading time (a very very slight improvement, but improvement).

---
Tags: opengl, opengl-es2
---


# Question
Title: How many datapoints are there generally in terrain height maps?
I've created my own heightmap with data from USGS. The heightmap is pretty large, but the point density is low, resulting in a low-poly terrain.

While performance is excellent, the physics engine I'm using doesn't particularly like how much distance is between each point, resulting in clipping.

Regardless, what is the point density like for games like H1Z1 or any other game that uses a height map on a large world?

# Answer
> 2 votes
There really isn't a specific standard for point density, for a few good reasons. However, in my experience, a descent density is about 3-7 points per m^2.

The reason that there isn't a standard is because point density varies a lot, based on things like distance and render quality.

For example, the highest quality setting might have 2, 3 or even 4 times as many polygons as the lowest. Also, there is no need to have high point density in a section/chunk of the world that is far away from the player.

---
Tags: terrain, heightmap
---