texts:
Currently I am starting to develop my first serious game. Before the games are all training, and learning how to do things in a good way. Unfortunatly, I've missed a big part in my preparation: Key binding.

Currently I am trying to figure out how I can bind keys to action for each scene in my game.
For example:
If the user presses the JumpButton during the GameScene, the avatar should jump, but pressing the same key in a MenuScene, the currently selected menuitem should be activated.

Which key the JumpButton is, should the user be able to set. But the behaviour should be always the same.

Here is my first, and I think very naviive idea:

I am having a HashMap with HashMap where Key is the key on the Keyboard and ACTION is just an enumValue.
When I am in the scene, and a button is pressed, I will take that button, and ask the HashMap which action is bind to the button. using a switch I can now determine what to do.
In my mind there is a little gap.. I have ONE action per Button, maybe named: ACTION_PLAYER_JUMP as an enumValue, and when I am in a GameScene this is okay, but in a MenuScene this ACTION_PLAYER_JUMP is not a very nice name... I do not want to have all bindings two times, just for better names.

Can someone tell me how to fix this, or a better system? I am sure there is a much better system for handling those bindings.


texts: Getting Model & Movement from Blender to OGRE3D

texts: I just delved myself into game development. I have created a simple character in Blender, together with its walking animation. I am planning to import the model and the movement so that I could use it in OGRE3D. How can I achieve this? Will the import thing have to separate model and movement? Is there any good and comprehensive guide for this?


texts: How can I rotate my picture using Pygame?

texts:
I want to make the Dragon on the picture rotate softly to the left when he flies to the left and rotate to the right when he flies to the right and up and down also.

How can I do that with the WASD keys? The Dragon can fly already up, down, lef, and right....but he doesn't turn...
My Code:
import pygame, sys
from pygame.locals import *

pygame.init()

size = width, height = 1600, 848
speed = [2, 2]
black = (0, 0, 0)

pygame.mouse.set_cursor(*pygame.cursors.broken_x)

screen = pygame.display.set_mode(size)
background = pygame.image.load("background.PNG")
dragon1 = pygame.image.load("dragon1.gif")
x,y=0,0
clock=pygame.time.Clock()
speed=250
movex, movey=0,0

while True:
screen.blit(background, (0,0))
screen.blit(dragon1, (x,y))

for event in pygame.event.get():
    if event.type == QUIT:
        pygame.quit()
        sys.exit()

if event.type==KEYDOWN:
        if event.key==K_a:
            movex=-4
        elif event.key==K_d:
            movex=+4
        elif event.key==K_w:
            movey=-4
        elif event.key==K_s:
            movey=+4
if event.type==KEYUP:
        if event.key==K_a:
            movex=0
        elif event.key==K_d:
            movex=0
        elif event.key==K_w:
            movey=0
        elif event.key==K_s:
            movey=0
x+=movex
y+=movey

pygame.display.flip()


texts: How to do pixel per pixel modeling in unity3d?

texts:
So generally I want to have api like pixels.addPixel3D(new Pixel3D(0xFF0000, 100, 100,100)); (color, position) where pixels is some abstraction on 3d sceen objet.So to say point cloud. It would have grate use in deep space/stars modeling... I want to set each pixel by hand (having no image base or any automatic thing)... So point is modeling something like

Or look at alive flash analog here

How to do such thing in unity?


texts: Ideas to create a Best Move in a match 3 game

texts:
I'm trying to make a match 3 game in C++ and I want to make a best move method to show the player the ideal position to move to get the most amount of points.

The rules of the game are as follows:

Pairs of objects adjacent vertically and horizontally can be swapped.
You can only swap objects when this will result in a match being created.
A match happens when there are 3 or more objects of the same kind adjacent vertically or horizontally.
objects that match are removed from the board. objects above a gap will keep fall down until all gaps are filled. New matches made by objects falling into place will be removed with the process repeating until there are no matches left.
Points are awarded based on the number of objects removed. The best move for a given board is the one that removes the most objects .

However, I'm stumped for ideas on how to implement such a method. Can anyone give me some ideas on how I can do it?

If you've made a match 3 game, and have implemented a similar method; how did you do it?


texts: How do I prevent my umap from being modified at every save?

texts:
I'm using UnrealEngine 4. Every time I save my files, my .umap file seems to be modified. I can basically generate an infinite stream of commits by just clicking Save Current, then committing changes, and clicking Save Current again, without making any actual changes.
To not create any unnecessary merge conflicts in git I would like the file to change only if something actually changed. How do I do this?


texts:
Why do some apps, like Angry Birds, dominate the market while other cool/fun/addicting apps are never heard of?

I'm trying to figure out the best marketing strategy, or best way to sell an app to mass market.

Does anybody have any ideas or things they noticed about the marketing of major blockbuster apps, like Angry Birds, why they get so popular and stay at the top of charts.

Thanks for any ideas, comments ...


texts: I made a game and uploaded it to a game site. I exported the build as windows mac OS and Linux. My thinking was that it supported all of those platforms but i guess not. Someone commented saying that the game didn't support linux. I have no idea why since it said it built for mac and windows and linux. Do i have to change settings? If so were? if its target platform i cant because the only option is windows.


texts:
First of all I'm sorry if my question is a odd thing to ask, but i'm new to Shader things and don't know how to handle this stuffs.
I have a shader that draws grid on a ground plane and it works just fine.
But i wanna do one thing more.
Currently the color of the grid lines are all in same color. I want to set the main grid line's color differently.
for example, like this one :

and this is what i have now :

for example, every 4x4 or 2x2 the line color should be something like red / blue etc.
I'm adding my shader's code below. plz somebody help me figure this out.
Shader "Unlit/Grid"
{
    Properties
    {
         _GridColour("Grid Colour", color) = (1, 1, 1, 1)
        _BaseColour("Base Colour", color) = (1, 1, 1, 0)
        _GridSpacing("Grid Spacing", float) = 0.1
        _LineThickness("Line Thickness", float) = 1
    }
    SubShader
    {
       Tags { "RenderType" = "Transparent" "Queue" = "Transparent"}
        LOD 100

        Blend SrcAlpha OneMinusSrcAlpha
        ZWrite Off

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            fixed4 _GridColour;
            fixed4 _BaseColour;
            float _GridSpacing;
            float _LineThickness;

            v2f vert(appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = mul(unity_ObjectToWorld, v.vertex).xz / _GridSpacing;

                return o;
            }

            fixed4 frag(v2f i) : SV_Target
            {
                float2 wrapped = frac(i.uv) - 0.5f;
                float2 range = abs(wrapped);

                float2 speeds;
                /* // Euclidean norm gives slightly more even thickness on diagonals
                float4 deltas = float4(ddx(i.uv), ddy(i.uv));
                speeds = sqrt(float2(
                            dot(deltas.xz, deltas.xz),
                            dot(deltas.yw, deltas.yw)
                         ));
                */  // Cheaper Manhattan norm in fwidth slightly exaggerates thickness of diagonals
                speeds = fwidth(i.uv);

                float2 pixelRange = range / speeds;
                float lineWeight = saturate(min(pixelRange.x, pixelRange.y) - _LineThickness);

                return lerp(_GridColour, _BaseColour, lineWeight);
            }
            ENDCG
        }
    }
}


texts:
I want to simulate a rope with a weight attached, swinging back and forth like a pendulum. Any actual physics is overkill; it's just endlessly repeating the same motion.

JQuery has a the "swing" ease similar to what I'm looking for. How does it work?

I was thinking of rotating from one angle to another with Math.easeOutExpo, but real pendulums ease differently...


texts: isometric drawing order with larger than single tile images - drawing order algorithm?

texts:
I have an isometric map over which I place various images. Most images will fit over a single tile, but some images are slightly larger. For example, I have a bed of size 2x3 tiles.

This creates a problem when drawing my objects to the screen as I get some tiles erroneously overlapping other tiles.

The two solutions that I know of are either splitting the image into 1x1 tile segments or implementing my own draw order algorithm, for example by assigning each image a number. The image with number 1 is drawn first, then 2, 3 etc.

Does anyone have advice on what I should do?

It seems to me like splitting an isometric image is very non obvious. How do you decide which parts of the image are 'in' a particular tile? I can't afford to split up all of my images manually either.

The draw order algorithm seems like a nicer choice but I am not sure if it's going to be easy to implement. I can't solve, in my head, how to deal with situations whereby you change the index of one image, which causes a knock on effect to many other images. If anyone has an resources/tutorials on this I would be most grateful.


texts: Override the position of bodypart with script on top of animation

texts:
I have a character with an Idle and Move animation.

Now I want to create an Attack animation. Here I want the hand to move towards the mouse position and back, using a script. The other hand should still follow the Idle or Move animation.

When I use a script in FixedUpdate() to do this the position of the hand still follows the animation. If I use LateUpdate() and set hand.transform.position, this seems to represent the local position and not global position.

Is there a proper way to create this Attack animation?

using UnityEngine;

public class Attack : MonoBehaviour
{
    public Camera camera;
    public Transform body;
    public Transform hand;
    public string button;
    public float time = 5f;
    public float begin = 3f;
    public float end = 6f;

    float step = 0f;

    bool pressed = false;
    float currentTime = 0f;
    int direction = 1;

    private void Start()
    {
        step = (end - begin) / time;
    }

    private void Update()
    {
        if (!pressed && Input.GetButtonDown(button))
        {
            pressed = true;
        }
    }

    private void LateUpdate()
    {
        if (pressed)
        {
            setCurrentTime();
            Vector2 mouse = camera.ScreenToWorldPoint(Input.mousePosition);
            Vector2 direction = (mouse - (Vector2)body.position).normalized;
            hand.position = (Vector2)body.position + direction * (begin + (step * currentTime));

        }
    }

    void setCurrentTime()
    {
        currentTime = currentTime +  direction * Time.deltaTime;
        // At End
        if (currentTime > time / 2)
        {
            float overhead = currentTime - (time / 2);
            currentTime = currentTime - overhead;
            direction = -1;
        }
        // Back at Begin
        if (currentTime < 0f)
        {
            pressed = false;
            currentTime = 0f;
            direction = 1;
        }
    }

}


texts: Why would creating a GLFW 3 window return null?

texts:
For some reason after calling 'glfwCreateWindow' I get back NULL as the return value.
I'm initializing GLFW beforehand with 'glfwInit' and while searching for a solution tried setting 'glfwSetErrorCallback' to print if there is an error but it doesn't call my function after returning NULL.

I'm using GLFW 3 with C++ on Visual Studio 2010 x64.


texts: I am fairly new to OpenGL. I have a 2D game in SDL2 that uses currently works by creating a SDL_Surface from the pixel data, copying it into a SDL_Texture, and rendering it to the screen with SDL_Renderer. But rather than using SDL to render the pixels, I'd like to switch to OpenGL. The reason I'd like to switch is because I need to render some lines on top of the pixel data and SDL_RenderDrawLine() just doesn't have all the features I need (like line thickness or glScissor). At first, I attempted to switch to OpenGL by using glDrawPixels() and I was happy with the results. However, I found out that glDrawPixels() does not seem to be available in OpenGL-ES (mobile devices). I have looked through some tutorials, but they all use shaders and other fancy stuff that I don't think I really need. Is there a simple way (like glDrawPixels()) to just draw pixel data to the screen for a 2D game? The pixel data is in the format GL_UNSIGNED_BYTE and it contains everything that I want to draw on the screen (except for several 2D line segments that I plan on using GL to render on top).


texts:
I'm trying to create an Augmented Reality app. I'm using OpenCV to get 4 points from a checkerboard pattern that represent the four corners of the pattern. This should be used to create a plane in my app, but the points are in 2D.

Anyone here have an idea how one is to use these 4 points to create a plane and/or map a 3D object to the pattern


texts: Why UI isn't instantiate when I create a new object that has Canvas as a child component?

texts:
I have this object called Treant and I instantiated him from another Object called spawn. The spawn only instantiates a new Treant every second or not.

My problem is that the Treant has a Health bar but that same health bar isn't instantiated in the other Treant that I clone. The health bar will only appear in the next Treant the is created after I destroy the one that has the Health bar.

How can I made all Treants have the Health Bar on top of them?

This is my Spawn class:

 // Start is called before the first frame update
public Component Enemies;
public Component Target;
private float lastSpawn = 5;
private float waited = 0f;
private int spawnPerWave = 1;
private int spawned = 0;
private List<int> fibonacci = new List<int>
{
    1, 1
};

// Update is called once per frame
void Update()
{
    CreateNewWave();
    Spawn();
}

private void Spawn()
{
    waited += Time.deltaTime;

    if (lastSpawn < waited && spawned < spawnPerWave)
    {
        Debug.Log("Spawned");
        waited = 0;
        spawned += 1;
        var enemy = Instantiate(Enemies);
        enemy.GetComponent<EnemyAI>().target = Target;
    }
}

private void CreateNewWave()
{
    if(spawned == spawnPerWave && fibonacci.Count < 4)
    {
        spawned = 0;
        spawnPerWave = fibonacci[fibonacci.Count - 1] + fibonacci[fibonacci.Count - 2];
        fibonacci.Add(spawnPerWave);
    }
}

The Canvas config:

The Slider config:

The code from FollowTransform:

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

public class FollowTransform : MonoBehaviour
{
    public Transform m_objectToFollow;
    private RectTransform m_rect;

    void Start()
    {
        m_rect = GetComponent<RectTransform>();
    }

    void Update()
    {
        this.m_rect.anchoredPosition = CanvasManager.Instance.WorldToCanvasPoint(m_objectToFollow.position);
    }
}

Canvas Manager Script:

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

public class CanvasManager : MonoBehaviour
{
    private Rect m_canvasRect;
    // Start is called before the first frame update
    private static CanvasManager canvasManager;
    public static CanvasManager Instance
    {
        get
        {
            return canvasManager;
        }
    }

    void Start()
    {
        if(canvasManager != null && canvasManager != this)
        {
            Destroy(this.gameObject);
        }
        else
        {
            canvasManager = this;
        }

        m_canvasRect = GetComponentInParent<Canvas>().GetComponent<RectTransform>().rect;
    }

    public Vector2 WorldToCanvasPoint(Vector3 a_position)
    {

        Vector2 viewport = Camera.main.WorldToViewportPoint(a_position);
        return Vector2.right * (viewport.x - 0.5f) * m_canvasRect.width + Vector2.up * (viewport.y - 0.5f) * m_canvasRect.height;
    }
}


texts: How do you create a funky moving background?

texts: I'm trying to create something similar to what you would see if you loaded a song in Windows Media Player (the cool abstract background that moves and produces various colors). I have no idea how this can be accomplished in libgdx. I've seen other games, such as puzzle games, on the Android store that having moving backgrounds to add visual effect so that the background isn't so static/boring. How can I achieve a similar effect without consuming a ton of RAM or without high CPU usage?


texts: Unity: Drag and drop for tower of hanoi type game

texts:
I'm a complete noob with Unity, and I want to make myself a small Tower Of Hanoi type game.

I could use some advice on how to do this, but for now, I've settled for a drag and drop system - the player can just drag the discs (or in this case, a panda) sideways from one tower (bamboo) to another.

I looked up some resources online, and also came across the video from qull18creates, but I wasn't sure if using a canvas was the way to go, so I eventually settled on this video by K2niceStudio

Since there will be multiple pandas, I thought it best to put the script in the camera. Here's what I have so far:

using UnityEngine;
using System.Collections;

 public class DraggingScript : MonoBehaviour
 {
     public GameObject objectToDrag;
     public Vector3 objectCenterOriginal, objectCenterNew, objectMouseOffset, mousePosition;

     RaycastHit hit;

     public bool isDragging = false;

     // Use this for initialization
     void Start()
     {
     }

     // Update is called once per frame
     void Update()
     {
         // Click to Drag
         if (Input.GetMouseButtonDown(0))
         {
             Debug.Log("Button Down");
             Debug.Log(Input.mousePosition);
             // If left mouse button is clicked

             Ray lookForObject = Camera.main.ScreenPointToRay(Input.mousePosition);

             if (Physics.Raycast(lookForObject, out hit))
             {
                 Debug.Log("hit!");   // <------ I've never seen this printed out
                 objectToDrag = hit.collider.gameObject;
                 objectCenterOriginal = objectToDrag.transform.position;
                 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
                 objectMouseOffset = mousePosition - objectCenterOriginal;
                 isDragging = true;
             }

             if (isDragging)
             {
                 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
                 objectCenterNew = mousePosition;
                 objectToDrag.transform.position = new Vector3(objectCenterNew.x, objectCenterNew.y, objectCenterOriginal.z);
             }
         }

         if (Input.GetMouseButtonUp(0))
         {
             Debug.Log("Button Up");
             isDragging = false;
         }
     }
 }

Unless I made a mistake somewhere, I think it's mostly identical to the video's, with the only exception (AFAIK) being there's already three images in my scene (background, foreground, panda), whereas the video only has one.

However, the video's code works. Mine doesn't. Putting debug logs in the code makes me believe the panda is not being fetched, even if I click on it directly.

Where did I go wrong?
I'm also open to advice, if there's a better way to do this overall.
Thanks.

Here's a shot of my sprites in the Scene:

EDIT:

Apparently, having the camera set back to -10 Z position messed with the selection. I can now select the panda, though it doesn't move at all.


texts: Is it possible to make a randomly rotating terrain texture painting brush in Unity?

texts:
I wanted to make a terrain in unity with a dirt texture painted onto the original grass texture to make a path, but when I tried, the dirt (and grass) looked repetitive and full of patterns.

My question is, is there any way I can make a texture's tiles randomly rotate when being applied or painted onto an object?


texts: How do I derive an appropriate acceleration value for my game?

texts:
I am creating a Flappy Bird clone from this tutorial.

I have a question about acceleration in libgdx. The author assigned the bird a constant acceleration vector in the constructor of the bird

        acceleration = new Vector2(0, 460);

and later updated the velocity vector from the accleration vector with

        velocity.add(acceleration.cpy().scl(delta));

I understand generally why acceleration is constant - like the author mentioned, acceleration due to gravity is 9.81m/s^2, meaning that the speed of an object falling will increase by 9.81m/s every second. It seems the author somehow got from 9.81 real world value to 460 in the actual code. How does one go about deriving this value? Is this a standard derivation or something the author just made up?


texts: How to calculate the inverse of a 4*4 opengl transform matrix

texts:
I am transforming my camera like any other object. I would like to set the view model matrix to the inverse of this so that I can draw the rest of the objects relative to the camera.

How do i calculate the inverse transformation?

I construct this matrix from a quaternion and a position vector, if it is easier to find the inverse of these then feel free to post.


texts: How to change the transparency of an object in Unity c# scripting?

texts:
I have laser-object in my scene, which I want to be seen only when I press the 'E' button on the key board(just an example of a key).
I have seen many ways to change the transparency , however, none of them worked.
one of them was -

gameObject.renderer.material.color.a = 0.0f ;

I get an Error -  UnityEngine.renderer does not contain color and material sub-functions.

I don't know how to do it, and I tried many ways.
Does someone have an easy way to make an object transparent and visible in C# script ?
Thank you


texts:
I'd like the button style to only change when it is checked and not change when it is pressed down, and/or have only the font color change. I'm using the built in Skin function with a .json file, however, that only allows for the up, down, and checked states, along with font color. Is this possibly? If yes, how? If not, then I'll just extend the Button class to add that functionality.

EDIT
I have currently just decided to go with a neutral "down" state, but I would still like to know if what I asked is possible.


texts: Drawing and scrolling very large zoomed tilemaps

texts:
I've been working on my game editor and doing some performance tests. In the meantime I realized that my editors performance goes significant down if I draw a large map and zoom it.

100% zoom = 112 tiles on the screen

50% zoom = 364 tiles on the screen

25% zoom = 1350 tiles on the screen

12.5% zoom = 5247 tiles on the screen

5247 is a much of it. But that are only these tiles which are need to draw.

for (var layerX = minTileX; layerX < maxTileX; layerX++)
for (var layerY = minTileY; layerY < maxTileY; layerY++)

I decided to render areas of the map to rendertargets and draw only these. The framerate goes up. But if I want to scroll it goes down again, because it have to recreate and render all rendertargets.

Maybe I could draw the whole map on rendertargets (256*256 pixel per rendertarget => 63 rendertargets on a 500*500 large tilemap with 32px tiles)?
But I dont think thats is the right way to do it.


texts: Unit turning in navmesh-based pathfinding

texts:
I'm working on an RTS game, and I'm using navmeshes for unit pathfinding. I do know how to find a general path within a navmesh, but how do you determine if the unit have enough space to turn?

I have units of different shapes (mostly rectangles with different dimensions), and with different turn radii. Additionally some of units can turn in place, and some can move in reverse.

So, how to find a path which unit can follow, considering that it can not rotate easily?


texts: openGL Camera setup for Zoom in/out centered at point under cursor

texts:
I am trying to implement a zoom in/out navigation mode in a openGL 3dViewer. I was able to implement zoom functionality centered at screen center just by moving eye towards the center in perspective mode.

Now i am trying to do the zoom centered at arbitrary position under the cursor. I am unable to figure out how should i move my camera forward and backward such that point under cursor remains at the same screen coordinates after zoom in/out. Any help would be appreciated.

Below are the images which show the desired effect. Just to mention, I am working in a perspective mode with eye target and up vectors to control camera.

Same effect i found in google sketchup and 'zoom to mouse position' setting in blender.


texts:
I was playing with raymarching using distance fields in GLSL sandbox and got stuck with a strange problem with artifacts.

Click here and take a look at the spheres generated in corners, they have strange artifacts plus they "flicker".

Is the mod operator, for domain repetition the culprit here?


texts: When and how often does Epic charge me royalties on my game?

texts:
I want to know about that 5% royalties that Epic charges for the Unreal Engine if I sell games above $3000.

What about if my game just made $300? Do I still need to pay 5% royalties to them? And how many times should I pay? For example, I made a game that was sold for above $3000 so I paid 5% royalties but do I still need to pay it again for the same game?


texts:
I have tried many things but I could not make interstitial ads display in Unity. I want to show interstitial ads after users select a wrong answer and before the score page ("Notice" scene) displays. Here is my code, I just copied relevant parts:

 using UnityEngine;
 using UnityEngine.UI;
 using System.Text;
 using System.Xml;
 using System.Collections;
 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Xml.Serialization;
 using System.IO;
 using GoogleMobileAds;
 using GoogleMobileAds.Api;

 public class responder : MonoBehaviour
 {
     private InterstitialAd interstitial;

     private int gecis;

     public Text questionsorular;
     public Text responseA;
     public Text responseB;
     public Text responseC;
     public Text responseD;
     public Text infoResponses;
     public Text infoResponses1;
     public Text example;
     public Text dogrusayisi;

     private float corrects;
     private float questoesquestions;
     private float media;
     private int Notice;
 }

 void Start()
 {
     RequestInterstitial();
 }

 public void response(string alternative)
 {

     RequestInterstitial();

     if (alternative == "A")
     {
         if (responseA.text == infoResponses.text)
         {
             corrects += 1;
             nextQuestion();
         }
         else
         {
             Invoke("wrong", 1);
         }
     }

     else if (alternative == "B")
     {
         if (responseB.text == infoResponses.text)
         {
             corrects += 1;
             nextQuestion();
         }
         else
         {
             Invoke("wrong", 1);
         }
     }

     else if (alternative == "C")
     {
         if (responseC.text == infoResponses.text)
         {
             corrects += 1;
             nextQuestion();
         }
         else
         {
             Invoke("wrong", 1);
         }
     }

     else if (alternative == "D")
     {
         if (responseD.text == infoResponses.text)
         {
             corrects += 1;
             nextQuestion();
         }
         else
         {
             Invoke("wrong", 1);
         }
     }
 }

 void wrong()
 {
     ShowInterstitial();
     Application.LoadLevel("Notice");
 }

 private void RequestInterstitial()
 {
 #if UNITY_EDITOR
     string adUnitId = "unused";
 #elif UNITY_ANDROID
             string adUnitId = "MY ADS ID";
 #elif UNITY_IPHONE
             string adUnitId = "INSERT_IOS_INTERSTITIAL_AD_UNIT_ID_HERE";
 #else
             string adUnitId = "unexpected_platform";
 #endif

     // Create an interstitial.
     interstitial = new InterstitialAd(adUnitId);
     // Load an interstitial ad.
     interstitial.LoadAd(createAdRequest());
 }

 private AdRequest createAdRequest()
 {
     return new AdRequest.Builder()
             .AddTestDevice(AdRequest.TestDeviceSimulator)
             .AddTestDevice("0123456789ABCDEF0123456789ABCDEF")
             .AddKeyword("game")
             .SetGender(Gender.Male)
             .SetBirthday(new DateTime(1985, 1, 1))
             .TagForChildDirectedTreatment(false)
             .AddExtra("color_bg", "9B30FF")
             .Build();
 }

 private void ShowInterstitial()
 {
     if (interstitial.IsLoaded())
     {
         interstitial.Show();
     }
 }

Following code works perfectly for banner ads when I attached it to camera:

 using UnityEngine;
 using GoogleMobileAds.Api;

 public class Ads : MonoBehaviour
 {
     void Start()
     {
         BannerView adsObject = new BannerView(
                 "MY ADS ID", AdSize.SmartBanner, AdPosition.Bottom);
         AdRequest getAds = new AdRequest.Builder().Build();
         adsObject.LoadAd(getAds);
         }
 }


texts: Twin stick shooter turning and animation using Vector3.Angle() in Unity

texts:
I am trying to smoothly transition between running, strafing, and running backwards by calculating the angle between the left thumb stick (move) and the right thumb stick (rotate).

It is my understanding that Vector3.Angle() calculates angles to the left as negative and angles to the right as positive. This doesn't seem to be working for me. I am able to use Vector3.Angle () make my character do the following actions:

if(-25 <= angle <= 25) // then run forward

if(25 < angle < 155) //then strafe left

if(-25 > angle > -155) //then strafe right

if(-155 < angle > 155) //then run backwards

Why is Vector3.Angle() behaving like this?


texts: Why cant I use slick-util with image IO and bufferedImage

texts:
My problem is that I get errors when I use

texture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("TEXTURE PATH HERE"));

it gives me these errors:

Exception in thread "main" java.lang.RuntimeException: No OpenGL context found in the current thread.
    at org.lwjgl.opengl.GLContext.getCapabilities(GLContext.java:124)
    at org.lwjgl.opengl.GL11.glGetError(GL11.java:1277)
    at org.newdawn.slick.opengl.InternalTextureLoader.getTexture(InternalTextureLoader.java:226)
    at org.newdawn.slick.opengl.InternalTextureLoader.getTexture(InternalTextureLoader.java:184)
    at org.newdawn.slick.opengl.TextureLoader.getTexture(TextureLoader.java:64)
    at org.newdawn.slick.opengl.TextureLoader.getTexture(TextureLoader.java:24)
    at game.Map.Init(Map.java:34)
    at game.Game.start(Game.java:17)
    at game.Game.main(Game.java:63)

My code uses ImageIO, Buffered Image and image.getRGB();
But it also uses the Slick-Util library for loading textures to render.

The full code for the Map.java class is:

`
package game;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import org.newdawn.slick.Color;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;
import org.newdawn.slick.util.ResourceLoader;

public class Map {

    int mapSize=100;
    int[] Tiles = new int[mapSize+1];
    int Tile;

    public Texture texture;

    public void Init()
    {
        try {
            // load texture from PNG file
            texture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("res/Tiles/Grass.png"));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

     public void LoadMap()
        {

            File file= new File("res/map.png");
              BufferedImage image = null;
            try {
                image = ImageIO.read(file);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            for(int Y = 0;Y<image.getHeight();Y++){
                for(int X = 0;X<image.getWidth();X++){

              int clr=  image.getRGB(X,Y);
              int  red   = (clr & 0x00ff0000) >> 16;
              int  green = (clr & 0x0000ff00) >> 8;
              int  blue  =  clr & 0x000000ff;
              if(red==0&&green==0&&blue==0){
                  Tiles[Tile]=0;
              }
              if(red==255&&green==0&&blue==0){
                  Tiles[Tile]=1;
              }
              if(red==0&&green==255&&blue==0){
                  Tiles[Tile]=2;
              }
              if(red==0&&green==0&&blue==255){
                  Tiles[Tile]=3;
              }
              Tile++;
            }
            }
            for(int i = 0;i<mapSize;i++)
            {
                System.out.println(Tiles[i]);
            }

        }
     public void RenderMap()
     {

     }

}
`

So all I want to know is how can I fix this error and draw the textures down in the

 void Render()
    {

    }

method.

Thanks, Griffin.


texts: Advice on playtester recruiting strategy for closed beta?

texts:
I am the lead programmer for a small game company working on our first release. A top down turn based historical WWII strategy game. Because our game appeals to WWII buffs and players who enjoy ‘simulation’ levels of detail we started by posting discussions of the game and invitations to the beta on WWII related sites like (WW2 Talk, The Wargamer, Axis History Forum etc.) However, we have had comparatively little response or willingness to participate in a beta from these communities.

What are some successful strategies that others in our position (small houses working on first projects) have used, or would suggest to attract and recruit beta testers?


texts:
I have followed the tutorial at http://www.david-amador.com/2009/10/xna-camera-2d-with-zoom-and-rotation/ to implement my 2D camera and everything works just fine. However this leaves me confused. From that implementation i see that first there is the translation applied, then rotation, then scale and then again translation to "offset" the camera.

However, in every book i read, there is one core principle to keep in mind when working with matrix translations, and that is the order of the application of transformations. And it is different: Scale, Rotation, Translate.

What am i not getting?


texts: How to render polygons of arbitrary shape?

texts:
I am trying to render a plane with nodes.

FYI : Nodes know what other nodes it is being attached to.

I can think of a way to render them as long as they are aligned in a circular pattern; have a center and draw triangles. However I want the shape to be not necessarily circular.

I have a picture below to enhance my description. Attempting to draw such a vertices with my previously stated method will result into an undesired shape, like the third picture.


texts:
I've searched all over the web for an answer to this, and there are simular topics but nothing works for me, and I have no Idea why. I just want to move my sprite using a joystick, since I'm useless at math when it comes to angles etc I used an example, Ill post the code here:

    public float initx = 50; //og 425;
public float inity = 300; //og 267;
public Point _touchingPoint = new Point(50, 300);  //og(425, 267);
public Point _pointerPosition = new Point(100, 170);
private Boolean _dragging = false;
private MotionEvent lastEvent;

    @Override
public boolean onTouchEvent(MotionEvent event) {

    if (event == null && lastEvent == null) {
        return _dragging;
    } else if (event == null && lastEvent != null) {
        event = lastEvent;
    } else {
        lastEvent = event;
    }
    // drag drop
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        _dragging = true;

    } else if (event.getAction() == MotionEvent.ACTION_UP) {
        _dragging = false;
    }

    if (_dragging) {
        // get the pos
        _touchingPoint.x = (int) event.getX();
        _touchingPoint.y = (int) event.getY();

        // bound to a box
        if (_touchingPoint.x < 25) {
            _touchingPoint.x = 25; //og 400
        }
        if (_touchingPoint.x > 75) {
            _touchingPoint.x = 75; //og 450
        }
        if (_touchingPoint.y < 275) {
            _touchingPoint.y = 275; //og 240
        }
        if (_touchingPoint.y > 325) {
            _touchingPoint.y = 325; //og 290
        }

        // get the angle
        double angle = Math.atan2(_touchingPoint.y - inity,
                _touchingPoint.x - initx) / (Math.PI / 180);

        // Move the beetle in proportion to how far
        // the joystick is dragged from its center
        _pointerPosition.y += Math.sin(angle * (Math.PI / 180))
                * (_touchingPoint.x / 70);
        _pointerPosition.x += Math.cos(angle * (Math.PI / 180))
                * (_touchingPoint.x / 70);

        // stop the sprite from goin thru
        if (_pointerPosition.x + happy.getWidth() >= getWidth()) {
            _pointerPosition.x = getWidth() - happy.getWidth();
        }

        if (_pointerPosition.x < 0) {
            _pointerPosition.x = 0;
        }

        if (_pointerPosition.y + happy.getHeight() >= getHeight()) {
            _pointerPosition.y = getHeight() - happy.getHeight();
        }

        if (_pointerPosition.y < 0) {
            _pointerPosition.y = 0;
        }
    }
    public void render(Canvas canvas) {
    canvas.drawColor(Color.BLUE);
    canvas.drawBitmap(joystick.get_joystickBg(), initx-45, inity-45, null);
    canvas.drawBitmap(happy, _pointerPosition.x, _pointerPosition.y, null);
    canvas.drawBitmap(joystick.get_joystick(), _touchingPoint.x - 26,
            _touchingPoint.y - 26, null);
}

    public void update() {
    this.onTouchEvent(null);
}

og= original position.
as you can see Im trying to move the joystick, but when I do it stops working correctly, I mean it still works like a joystick but the sprite dosnt move accordingly, if I for example push the joystick down, the sprite moves up, and if I push it up it moves left.

can anyone PLEASE help me, I've been stuck here for sooo long and its really frustrating.


texts:
I am looking for an experience ladder that 'starts' off relatively quickly like a bit of geometric series, then quickly grows like an exponential curve, and then a slow exponetial curve for later levels, in the range of levels 1-5000.

How would I do this mathematically? I am assuming I might just have three sets of equations, but then what is the correct math for getting the level (based on XP), and vice-versa, XP based on level?

I.e., I am thinking something like:

lvl 1 - 10 exp
lvl 2 - 12 exp
lvl 3 - 15 exp
lvl 4 - 18 exp
lvl 5 - 22 exp (not quite fibacconi)
lvl 6 - 26 exp
lvl 7 - 32 exp
...
then maybe around level 150 or so it starts growing quickly, like
lvl 150  -1000 exp
lvl 151 - 1200 exp
...
lvl 3000 - 30000 exp
lvl 3100 - 40000 exp
lvl 4000 - 75000 exp
lvl 5000 - 100000 exp

If it's been done, a link would be great (since I am not exactly sure what I am looking for, not quite sure how to find it). Or if it is easy for you to just write the math, please do that too, thanks for your help!


texts: Why does everything appear backwards when using orthographic projection?

texts:
I may not be calculating my orthographic projection matrix properly. What can I do to ensure that my scene renders correctly when using orthographic projection?

The rendering order appears to be backwards too (note the grid and how it appears half ontop, as if the z-buffer from the correct direction was being used). Disabling culling fixes things, but the view is still backwards.

Perspective:

Orthographic:

Matrix code for reference:

    Matrix4.createFrustum = function(left, right, bottom, top, near, far, result) {
        if (typeof result === 'undefined') {
            result = new Matrix4();
        }

        var re = result.elements;
        var x = 2 * near / (right - left);
        var y = 2 * near / (top - bottom);

        var a = (right + left) / (right - left);
        var b = (top + bottom) / (top - bottom);
        var c = - (far + near) / (far - near);
        var d = - 2 * far * near / (far - near);

        re[0] = x; re[4] = 0; re[8]  = a; re[12] = 0;
        re[1] = 0; re[5] = y; re[9]  = b; re[13] = 0;
        re[2] = 0; re[6] = 0; re[10] = c; re[14] = d;
        re[3] = 0; re[7] = 0; re[11] =-1; re[15] = 0;

        return result;
    };

    Matrix4.createPerspective = function(fov, aspect, near, far, result) {
        if (typeof result === 'undefined') {
            result = new Matrix4();
        }

        var ymax = near * Math.tan(fov * Math.PI / 360);
        var ymin = - ymax;
        var xmin = ymin * aspect;
        var xmax = ymax * aspect;

        Matrix4.createFrustum(xmin, xmax, ymin, ymax, near, far, /*out*/ result);

        return result;
    };

    Matrix4.createOrthographic = function(left, right, top, bottom, near, far, result) {
        if (typeof result === 'undefined') {
            result = new Matrix4();
        }

        var re = result.elements;
        var w = right - left;
        var h = top - bottom;
        var p = far - near;

        var x = ( right + left ) / w;
        var y = ( top + bottom ) / h;
        var z = ( far + near ) / p;

        re[0] =2/w;  re[4] = 0;   re[8]  = 0;   re[12] =-x;
        re[1] = 0;   re[5] =2/h;  re[9]  = 0;   re[13] =-y;
        re[2] = 0;   re[6] = 0;   re[10] =-2/p; re[14] =-z;
        re[3] = 0;   re[7] = 0;   re[11] = 0;   re[15] = 1;

        return result;
    };


texts: GameObject not destroyed in ExecuteInEditMode and spooky Instantiating

texts:
I was trying to get familiar with Unity's ExecuteInEditMode

Everything is fine it keeps the old object although I have deleted them.

And one more thing, although every-thing (cube) is instantiated is set as child of GameObject script is attached to, they where the other cubes come from?

I have this code:

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

[ExecuteInEditMode]
public class Road : MonoBehaviour
{
    public List<Vector3> points = new List<Vector3>();
    public List<GameObject> gameObjects = new List<GameObject>();
    private int count = 0;
    void Start()
    {}
    void Update()
    {
        if(count!=points.Count)
        {
            count = points.Count;
            foreach(GameObject g in gameObjects)
            {
                DestroyImmediate(g);
            }
            gameObjects.Clear();
            int i = 0;
            foreach (Vector3 point in points)
            {
                Debug.Log(++i + "  " + point);
                GameObject tem = Instantiate(GameObject.CreatePrimitive(PrimitiveType.Cube), point, Quaternion.identity);
                tem.transform.parent = gameObject.transform;
                gameObjects.Add(tem);
            }
        }
    }
}

Here is a snap:


texts: Intersection points of plane set forming convex hull

texts:
Mostly looking for a nudge in the right direction here. Given a set of planes (defined as a normal and distance from origin) that form a convex hull, I would like to find the intersection points that form the corners of that hull. More directly, I'm looking for a way to generate a point cloud appropriate to provide to Bullet.

Bonus points if someone knows of a way I could give bullet the plane list directly, since I somewhat suspect that's what it's building on the backend anyway.


texts:
I am creating a 3D ray tracer and want to add textured planes.

My planes are stored using a position vector and a normal vector.

I want to use a square texture and map it repetitively onto the plane.

How do I figure out a transformation from points (3D vectors) on the plane and points (2D vectors) on a texture? Once I know how to do this transformation, I don't think making it repetitive will be hard, as we can just apply modulo arithmetic.

I thought I could make a basis on the plane by calculating a vector B1 perpendicular to the normal, and then another one, B2, perpendicular to the normal and B1. But once I have these two vectors, I still don't know how to express the point (which is the argument for the function below) in this basis.

Vector3 position, normal;
Bitmap texture;

public override Vector3 GetColor(Vector3 point) {
    int u = ?
    int v = ?

    return texture.GetPixel(u, v);
}


texts: Character bouncing off ground due to gravity

texts:
Implementing gravity in the game, the character keeps bouncing up and down slightly when he hits the ground, upon debugging the character is essentially bouncing on and off the ground. Not quite sure how to iron out the issue any help here would be greatly appreciated.

The constant value

private float gravity = 0.09f;

adding to the velocity if the character is on the ground

if (!isOnGround)
 velocity.Y += gravity;

adding the characters overall velocity to the overall position.

position += velocity * (float)gameTime.ElapsedGameTime.TotalSeconds;

Part of the collision method which determines if the character is on the ground or not.

for (int y = topTile; y <= bottomTile; ++y)
            {
                for (int x = leftTile; x <= rightTile; ++x)
                {
                    // If this tile is collidable,
                    TileCollision collision = Level.GetCollision(x, y, tileMap);
                    if (collision != TileCollision.Passable)
                    {
                        // Determine collision depth (with direction) and magnitude.
                        Rectangle tileBounds = Level.GetBounds(x, y);
                        Vector2 depth = RectangleExtensions.GetIntersectionDepth(bounds, tileBounds);
                        float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

                        if (depth != Vector2.Zero)
                        {
                            float absDepthX = Math.Abs(depth.X);
                            float absDepthY = Math.Abs(depth.Y);

                            // Resolve the collision along the shallow axis.
                            if (absDepthY <= absDepthX || collision == TileCollision.Platform)
                            {
                                // If we crossed the top of a tile, we are on the ground.
                                if (previousBottom <= tileBounds.Top)
                                    isOnGround = true;


texts: OpenGL : Keeping alpha in a render buffer

texts:
In my current task, i need to render a texture into a render buffer, in order to work on it (apply special filters) there. The result is then considered a "new texture", which is later displayed.

This works fine, except when the texture contains some transparent/semi-transparent parts.

My current guess it that, within the render buffer, the texture is "merged" with a kind of "grey background". In this case, it obviously impacts the R,G,B color components of transparent pixels.
I've yet to find a way around this.

Even manually assigning alpha after the rendering process doesn't save the day for semi-transparent pixels, which RGB are "tainted" by the grey background.


texts: How to use OOP to handle different requirements

texts:
I've been trying to make games for a while now, but even when making a very simple one, I've always run into a problem - Because different subclasses have different functionality, therefore needing different requirements, I can't properly use OOP concepts in my code.

For example, I have a Projectile class in my code, which serves as a superclass for a Bullet class and Missile class. All of my projectiles are stored in a List, and I would like to be able to loop through the List and update all projectiles. However, I would like the Missiles class to follow the player, which means I need to supply the player's position to update it.

I could also store a pointer to the player in the Missile class, but this quickly becomes messy, and since the game is very simple, I wouldn't want to use ECS's. What solutions are available for this?


texts:
I am trying to understand the logic and functionality behind Scriptable Objects. I 've watched the provided video 2 times and I keep getting lost. I tried to follow the code as well but with no luck.

Can someone please explain to me what the Scriptable Objects are and how they work in a few lines?

[EDIT:] This Video as well as the following answers helped me understand Scriptable Objects and even better incorporate them in my own game.


texts: How to make attention grabbing notifications?

texts:
A lot of my play-testers miss the tutorial notifications in my game. The notifications fade into the screen and fade out after the player progresses away from where the tutorial was relevant. I've tried adding a moving gif (the little orange thing in picture below) but it still doesn't draw enough attention. Could someone please recommend me some options for how I can catch the user's attention better?
In the example below, the player is given their first "key item" in the game and I want to direct them to click on the "Special" items tab. About 60% of my play-testers open it up, while the other 40% skip past it by clicking the "Search" button to progress to the next part of the tutorial. Then some time later, when the player needs to check their "Special" items, they don't know where they are.

I'm a little unsure if I should prevent the player from progressing until they perform certain actions the tutorial asks. I feel it makes the game feel rigid, but as my game is more turn-based with decision buttons, its like I can teach them they can push blocks to make a staircase to get over a tall hill as one would in a simple platformer.


texts: Running two simultaneous animations on a model?

texts:
I am just looking for a broad answer to this question. I am more curious about the general information rather than the specific. Also, I tried to search for this, but I think it's hard to word it so you get the right question. Anyway:

One common thing I see in a lot of games is multiple animations on the same model.

i.e.

A character runs, but also raises his arms an shoots.

A character has a walking animation, but can also be carrying resources as he walks.

I am curious if the first model has a "run" animation and a "run while shooting" animation. Or if they have a "run" animation and a "shoot" animation and run them at the same time. Obviously the first is possible, but I am wondering how the second one is done.

Do they use two models for upper and lower body or is there a way to ignore certain parts of a model when animating?

I know this depends a lot on the model, the programmer, language and the way the animation is done.

But broadly, if you were making a model with the intent of it doing multiple animations at once, what would be the best way to go about it?

Again, not after detailed specifics, just an overview :)

Thanks!


texts: How do you account for zoom in a top down viewport?

texts:
I've been stumped on this for days so please forgive me if this question is in bad-form. I have a generic top-down RPG structure, and I want to create a zoomable Canvas viewport for it. I've read several tutorials and I guess I keep messing it up somewhere.

Current Codepen project here.

Relevant code from the project:

Camera:

function Camera(PARENT, CANVAS, SUBJECT, ZOOM)
{
  this.draw = function()
  {
    var refs = [];

    Rect.call(this, SUBJECT.x, SUBJECT.y, CANVAS.width*ZOOM, CANVAS.height*ZOOM, "cen");

    for(o in PARENT.objects)
    {
      if(this.overlapping(PARENT.objects[o]))
        refs.push(o);
    }

    while(refs.length>=1)
    {
      var obj = PARENT.objects[refs.shift()];

      if(obj.draw)
        obj.draw(
          this.context, //Drawing ctx
          this.left, //Offset left
          this.top, //Offset top
          ZOOM //Scale factor
        );
    }
  };
}

Drawing function called by the Camera:

this.draw = function(context, offsetX, offsetY, scale)
{
  context.fillStyle = this.color;
  context.fillRect((this.left-offsetX)*scale, (this.top-offsetY)*scale, this.width*scale, this.height*scale);
};

How can I resolve the math here so that the zoom is correctly figured in to the drawing offsets?


texts:
I'm developing a Pokémon/classic Final Fantasy inspired game, in the sense that game play consists in many creatures, possessing many moves with different effects (attacking, healing, buffing, debuffing, etc) taking turns fighting each other.

I'm having some doubts on how to implement the movement system, especially the part of how to organize the code responsible for the effects of the move.

Some important characteristics of the system:

Creatures should be able to learn and forget moves
All moves can be learned by more than one creature

I have come up with some ideas, but none seem very good. Is there any known standard in the industry for doing this, or any known optimal solutions?

Here are the ideas I had:

Every move inherits from an abstract class Move, overriding an execute() method.
A MoveProcessor class, containing a method executeMove(), called every time any move is made, receiving the move id code. Something like:

switch(moveCode){
     case 1: //Attack code
     break;
     case 2: //Heal code
     break;
     //...
}

I am developing in Unity and C#, but answers need not be specific to said platform and language.

Please note that this is not a duplicate of Modeling what moves a pokemon can learn or Storing data for a pokemon-like game, since those questions ask about storing move information, not implementation.


texts: What is next to interpolate camera position with smooth speed changes?

texts:
I am working on a path camera to be used in demo playback. (3d game) The spline math used is catmull rom. I am on my second attempt to get constant position speed :( (someone else is doing rotation). The path cam keyframes are position@time.

I have a step now when the path is recalculated, it also generates the arc distance/time lookup table which I have normalized. I have the duration of each segment(k through k+1)as well as each segments linear velocity calculated from that data.

I am not very good at reading anything except basic equations. I could use an explanation or psuedo code of what is needed next in order to get the camera to smoothly accelerate or decelerate depending on the velocity of the next segment. Right now it's instant changes and no good. I tried googling for hours and was going in circles.


texts:
How can we generate the wave-like texture like this

The author(RujiK) says in reply he used the texture generator(http://www.kitfox.com/projects/perlinNoiseMaker/index.html), but no matter how I tweak the parameters, it looks quite different from the original version


texts: Using an Entity System Architecture with Task Based Parallelism

texts:
Background

I have been working on creating a multithreaded game engine in my spare time and I currently trying to decide the best way to work an entity sytem into what I have already created. So far, I have used this article from Intel for a starting point for my engine. Thus far I have implemented the normal game loop using tasks, and I am now moving on to getting some of the systems and/or entity-systems incorporated. I have used something similar to Artemis in the past, but the parallelism is throwing me off.

The article from Intel seems to advocate having multiple copies of entity data, and a having changes made to each entity internally being distributed at the end of a complete update. This means that rendering will always be one frame behind, but that seems like an acceptable compromise given the performance benefits that should be gained. When it comes to an entity system like Artemis, though, having each entity being duplicated for each system means that each component will also need to be duplicated. This is doable but to me it seems like it would use up a lot of memory. The portions of the Intel document that discus this are 2.2 and 3.2.2 mainly. I have done some searching to see if I could find any good references for integrating the architectures I am going for, but I have not yet been able to turn up anything useful.

Note: I am using C++11 for this project, but I imagine most of what I am asking should be pretty language agnostic.

Possible Solution

Have a global EntityManager that is used for creating and managing Entities and EntityAttributes. Allow read access to them only during the update phase, and store all changes in a queue per thread. Once all tasks are completed the queues are combined and the changes in each are applied. This would possibly have problems with multiple writes to the same fields but I am sure there could be a priority system or timestamp to sort that out. This seems like a good approach to me because systems can be notified of changes to entities pretty naturally during the change distribution stage.

Question

I am looking for some feedback on my solution to see if it even makes sense. I won't lie and claim to be an expert on multithreading, and I am doing this largely for practice. I can forsee some complicated messes rising from my solution where multiple systems are reading/writing multiple values. The change queue I mentioned could also be hard to format in a way that any possible change could easily be communicated when I am not working with POD.

Any feedback/advice would be much appreciated! Thanks!

Links

http://software.intel.com/en-us/articles/designing-the-framework-of-a-parallel-game-engine
http://gamadu.com/artemis/
http://www.gamedev.net/topic/560083-rendering-in-a-task-based-multithreaded-environment/ (not mentioned in post this post but similar solution mentioned)


texts:
I don't know if this question is too broad but I am finally working on a game I want to release and I find that questions like: "can I really add another 10 frames?", "Do I really need that animation?", "Can I add more background effects?" etc. are always on my mind and limit my creativity.

I am trying to find an answer online without success, and as a hobby developer with no real training it is hard to know what is considered "too many" resources.

I suppose it differs depending on what you plan to release it for etc, but is there a general rule of thumb? I want to release for Android and ios.

For example I have a main character, and right now he has these animations:

 atlas = Assets.manager.get(Assets.runner, TextureAtlas.class);
        tallAnim = new Animation(1/10f, atlas.findRegion("runner1"), atlas.findRegion("runner2"), atlas.findRegion("runner3"), atlas.findRegion("runner4"));
        shortAnim = new Animation(1/10f, atlas.findRegion("short_runner1"), atlas.findRegion("short_runner2"), atlas.findRegion("short_runner3"), atlas.findRegion("short_runner4"));
        hitAnim = new Animation(1/10f, atlas.findRegion("runner_hit1"), atlas.findRegion("runner_hit2"));
        flyAnim = new Animation(1/10f, atlas.findRegion("runner_fly1"), atlas.findRegion("runner_fly2"));
        animation = tallAnim;

I want to add more but I am stopping my self because I don't know if this is too much. Right now he has 12 frames, and I am rendering a scrolling background and 2 different enemies (each with 3 frames) and a few other objects. Do I need to start limiting my game or is it hard to reach a point of "too much"?


texts: Direct3D9 application won't write to depth buffer

texts:
I've got an application written in D3D9 which will not write any values to the depth buffer, resulting in incorrect values for the depth test. Things I've checked so far:

D3DRS_ZENABLE, set to TRUE
D3DRS_ZWRITEENABLE, set to TRUE
D3DRS_ZFUNC, set to D3DCMP_LESSEQUAL
The depth buffer is definitely bound to the pipeline at the relevant time
The depth buffer was correctly cleared before use.

I've used PIX to confirm that all of these things occurred as expected. For example, if I clear the depth buffer to 0 instead of 1, then correctly nothing is drawn, and PIX confirms that all the pixels failed the depth test. But I've also used PIX to confirm that my submitted geometry does not write to the depth buffer and so is not correctly rendered.

Any other suggestions?


texts: HUD and score have gone missing in UnrealScript

texts:
I am a student at Full Sail so I don't want just the solution; I want to understand the problem. I am working from tutorial videos where we are supposed to have a HUD, a score, and a timer. When I first started, my player had a gun and a HUD. As I worked through the videos, the HUD changed, the score showed up but the HUD disappeared. Now the score disappeared as well as well as the HUD and I only have a gun. When I playtest it from Visual Studio, nothing shows up at all but when I load editor only the gun shows up.

This is the code setting up my game type

// Credit: Christopher Maxwell GameType W1 Video

class EricsMapGameType extends UTGame; //Sets game type as Unreal Tournament Game

var int myScore; // Sets myScore as a Variable Integer

defaultproperties // Sets the properties to default

{
    HUDType =class 'EricsMapInterfaceHud'  // Sets the interfacehud class to the Hudtype variable

    PlayerControllerClass = class' EricsMapInterfacePlayerController' // Sets the player controllers class into the the player class Variable

    DefaultPawnClass = class' EricsMapPawn' //Sets the maps custom pawn class to the default pawn variable

    bUseClassicHUD = true // Turns off the Flash Hud and allows use of custom Hud

}

//This is the code for my score, timer, and HUD
class EricsMapInterfaceHUD extends HUD; // EricsMapInterface class extends from Hud

var bool showCursor;

var const Texture2D CursorTexture;

var const Color CursorColor;

var Font m_HUDFont;

var Texture2D m_textureEX;

//------------------------------------------------
function DrawHUD()

{
    super.DrawHUD();
    drawMyScore();
    drawHUDText( "Hello!", 8);
    ericTexture();
}

//------------------------------------------------
function ericTexture()
{
    Canvas.SetPos(300,100);
    Canvas.SetDrawColor(255,255,255);
    Canvas.DrawTile(m_textureEX, 64, 64, 0, 16,  32, 16);
}

//------------------------------------------------
function drawHUDText(string _hudString, int _aNumber)
{
    local float textSizeX;
    local float textSizeY;
    local string ericText;

    ericText=_hudString @ _aNumber;

    Canvas.Font = m_HUDFont;
    Canvas.TextSize(ericText, textSizeX, textSizeY, 0.1, 0.1);
    Canvas.SetPos((Canvas.SizeX/2) - (textSizeX/2),(Canvas.SizeY/2) - (textSizeY/2));

    Canvas.SetDrawColor (255,0,0);
    Canvas.DrawText(ericText,,0.1,0.1);

}

//------------------------------------------------
function DrawMyScore()

{
    local WorldInfo rWorldInfo;
    local EricsMapGameType rGame;
    local int nScore;

    rWorldInfo = class 'WorldInfo' .static.GetWorldInfo();
    if(rGame != none)
    {
        rGame=EricsMapGameType(rWorldInfo.Game); // Turns the generic game into the custom game
        if(rGame!=none) //If not custome game goes back to original map
        {
        nScore = rGame.myScore;
        }
    }

    Canvas.SetPos(10,10);
    Canvas.Font = class 'Engine' .static.GetMediumFont();
    Canvas.SetDrawColor(255,0,0);

    Canvas.DrawText("Score:" @nScore);
}

//------------------------------------------------
event PostRender()
{
//  Canvas.SetPos(MouseInterfacePlayerInput.MousePosition.X,MouseInterfacePlayerInput.MousePosition.Y); //Gives me a bad or missing expression call to SetPos
    Canvas.DrawColor = CursorColor; //Draws cursor color
    Canvas.DrawTile(CursorTexture, CursorTexture.SizeX, CursorTexture.SizeY,0.f,0.f,CursorTexture.SizeX, CursorTexture.SizeY,, true);

}

defaultproperties
{
    CursorColor=(255,0,0,);
    CursorTexture=Texture2D'EngineResources.Cursors.Arrow';
    showCursor=true;
    m_HUDFont = Font'UI_Fonts.Fonts.UI_Fonts_Positec14';
    m_textureEX = Texture2D'UDKHUD.skull'

}

Please don't just tell me the answer; help me understand the answer.


texts: Visual Studio not recognizing Unity's new Input system

texts: I'm attempting to learn Unity's new input system, but when I try to add using UnityEngine.InputSystem; to my code  it gets a red squiggly line under it. It doesn't cause any compiler errors, but it's very annoying.  How do I get Visual Studio to recognize this so Intellisense will work again?


texts:
As you can see above, I have an image of a game I've been working on using Java. Using AWT I added the following:

public static void drawImageRotated(
        Graphics2D g2d, BufferedImage img, double x, double y, int scale, double angle) {

    BufferedImage image = new BufferedImage(
                                     (int)(img.getWidth() * 1.5D),
                                     (int)(img.getHeight() * 1.5D),
                                     2);
    Graphics2D g = (Graphics2D)image.getGraphics();
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g.rotate(Math.toRadians(angle), image.getWidth() / 2, image.getHeight() / 2);
    g.drawImage(img,
                image.getWidth()  / 2 - img.getWidth() / 2,
                image.getHeight() / 2 - image.getHeight() / 2,
                null);
    g2d.drawImage(image,
                 (int)x-(image.getWidth()*scale/2),
                 (int)y-(image.getHeight()*scale/2),
                 image.getWidth()*scale,
                 image.getHeight()*scale,
                 null);
    g.dispose();
}

This is the code which draws the ships onto the screen. As you can see there is a blue and a cyan ship on the screen, the blue ship's rotation being 0 and the cyan having a rotation of just over 270 degrees. The cyan ship is distorted and that's what I want to get rid of. Is there an anti-aliasing for small images like that one (16x16)?


texts: Kepler orbit : get position on the orbit over time

texts:
I'm developing a space-simulation related game, and I am having some trouble implementing the movement of binary stars, like this:

The two stars orbit their centroid, and their trajectories are ellipses.

I basically know how to determine the angular velocity at any position, but not the angular velocity over time. So, for a given angle, I can very easily compute the stars position (cf. http://en.wikipedia.org/wiki/Orbit_equation).

I'd want to get the stars position over time. The parametric equations of the ellipse works but doesn't give the correct speed :
{ X(t) = a×cos(t) ; Y(t) = b×sin(t) }.

Is it possible, and how can it be done?


texts: XNA 4: GetData from Texture2D and Set it into Texture3D with specific order

texts:
I am trying to convert my color grading 2d lookup texture into 3d LUT. When I simply use:

ColorAtlas.GetData(data);
ColorAtlas3D.SetData(data);

I get this:

I tried building my 2d atlass horizontally but it did not helped - the data was messed up in a different way.

So my question is how can I influence the order of the data I get from the 2d atlas and how can I properly pass it into my 3d atlas?

Update: I know that I can GetData from a specific Rectangular area and put it into several arrays, but the result is still the same. This is what I tried:

        Color[] data2D = new Color[0];

        for (int i = 0; i < 32; i++)
        {
            Color[] data = new Color[32 * 32];
            GraphicsDevice.SetRenderTarget(null);

            ColorAtlas.GetData(0, new Rectangle(0, i*32, 32, 32), data, 0, data.Length);

            int oldLength = data2D.Length;

            Array.Resize<Color>(ref data2D, oldLength + data.Length);
            Array.Copy(data, 0, data2D, oldLength, data.Length);
        }
        ColorAtlas3D.SetData(data2D);


texts: I am using CCParticleSystemQuad to create particle effects. But I want my sprites to be able to collide with particles. Say your character is a dragon, the dragon breath is a particle effect emitting fire. When the breath hits objects (sprites), I should be able to know it collided with some sprites. How can it be done? Unfortunately google search on this subject doesn't give very good output.


texts: Using Windows 10 Multi-Touch Functionality In Gamemaker: Studio

texts:
I have a multi-touch monitor that I am using in Windows 10. I am getting visual feedback on the monitor itself that multiple touches are being recognised. However, within my Gamemaker game, I cannot seem to recognise any other touch than the very first one. From the documentation, it seems that I should be able to just use the device_mouse functions, using 0,1,2,3 and 4 to stand for the different 'mice' that each press represents. However, this does not seem to work at all, for example in the following code:

if device_mouse_check_button(0,mb_left) {
Number = 1
}

else if device_mouse_check_button(0,mb_left) and device_mouse_check_button(1,mb_left) {
Number = 2
}

Can anybody shed some light on this problem? I cannot work out why this doesn't seem to be working. It recognises the first 'mouse' press, but as soon as I add the second finger it stops working.


texts: Fast self collision/intersection detection algorithm for tetrahedral meshes

texts:
I want to play with deformation of tetrahedral mesh (soft-body simulation) but I need help with self-collision detection stuff.
I found SOFA collision detection but I'm not sure that it fits for self-intersection of a tetrahedral mesh.
Can anyone suggest me good algorithm for self-collision detection? As far as I can understand, something like BVH of tetrahedra can help me, but it would be great if somebody with expertise shows me right direction.


texts:
I am using an event-based input handling system with events and delegates. An example:

InputHander.AddEvent(Keys.LeftArrow, player.MoveLeft); //Very simplified code

However, I started wondering about how to deal with 'nested' input. For example in Half-Life 2 (or any Source game, really), you can pick up items with E. When you've picked up an item, you cannot fire with Left Mouse, but instead you throw the object. You can still jump with Space.

(I am saying nested input is where you press a certain key, and the actions you can do change. Not a menu.)

The three cases are:

Being able to do the same action as before (like jumping)
Not being able to do the same action (like firing)
Doing a different action entirely (like in NetHack, where pressing the open door key means you do not move, but select a direction to open the door in)

My original idea was to just change it after the input had been received:

Register input 'A' to function 'Activate Secret Cloak Mode'

In 'Secret Cloak Mode' function:
Unregister input 'Fire'
Unregister input 'Sprint'
...
Register input 'Uncloak'
...

This suffers from large amounts of coupling, repetitive code, and other bad design signs.

I guess the other option is to maintain some kind of input state system - perhaps another delegate on the register function to refactor out those numerous register/deregister into a cleaner place (with some kind of stack on the input system) or maybe arrays of what to keep and what not to.

I'm sure someone here must've encountered this problem. How have you solved it?

tl;dr How can I deal with specific input received after another specific input in an event system?


texts: Viewport not matching Window size when fullscreen

texts:
I am using:

GraphicsDevice.Viewport.Bounds

to determine the size of the canvas / stage for my window. This works well if I am in Windowed mode, but if I launched into fullscreen, it does not update to the new fullscreen size.

public HelloWorld()
{
    graphics = new GraphicsDeviceManager(this);

    int height = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height;
    int width = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width;
    graphics.PreferredBackBufferHeight = height;
    graphics.PreferredBackBufferWidth = width;

    graphics.IsFullScreen = true;
    graphics.ApplyChanges();

    Content.RootDirectory = "Content";
}

Basically, I am setting the window to fullscreen in the constructor, but the Viewport does not get set to the new size (I also tried just setting to fullscreen without explicitly setting PreferredBackBuffer settings). I have tried manually setting the viewport size, but it appears to be null in the constructor.

So, is there a way to get the stage / screen bounds that I can draw to in a way that is consistent in both Windowed mode and fullscreen mode?

When I run, here is what I get:

(i.e. the viewport doesnt match the entire screensize).

Debugging this a bit more and the issue isnt that the viewport isnt being updated to the correct size (it is), but that it seems to render in a smaller space (see attached image). If I print out with the width / height of the viewport, it matches the full screen window, but when I draw at 0,0, it doesnt place it at the top left of the window).

Note, if I just set the window size to the dimensions of the screen, and DONT set it to fullscreen, then things work (i.e. the balls fill the screen)(see image below).

I can get it to work if I move the fullscreen call from the Constructor, and to Initialize. This works, but I am trying to figure out why it doesnt work when I call full screen in the constructor (and if that is the right place for me to make that call).


texts: Is this a reasonable method of detecting JS memory hacks?

texts:
I'm working on a single-player browser-based RPG in my free time. I do allow for saving the user's game on the server, but the game is largely going to run locally and I therefore acknowledge that it is impossible to outright prevent a user from cheating in a myriad of ways.

I'm just looking at the idea of a "dookie" achievement for editing the game data, and was wondering if this solution is in any way viable?

if (Reflect.set.toString() !== 'function set() { [native code] }') {
  throw new TypeError('Missing native Reflect.set');
}
if (Error.constructor.toString() !== 'function Function() { [native code] }') {
  throw new TypeError('Missing native Error constructor');
}
if (Proxy.constructor.toString() !== 'function Function() { [native code] }') {
  throw new TypeError('Missing native Proxy constructor');
}

function setTrap(target, _1, _2, receiver) {
  const res = Reflect.set(...arguments);
  const stack = new Error().stack.split('\n');
  if (stack.length >= 2 && stack[1].indexOf('<anonymous>') >= 0) {
    Reflect.set(target, 'cheated', true, receiver);
  }
  return res;
}

const myData = new Proxy({
  data1: valueA,
  data2: valueB,
  data3: valueC,
  // ...
}, {set: setTrap});

If the user edits myData in the browser console, their changes will remain, but myData will also get cheated: true after whatever change they make. Assuming setTrap is defined in a local scope, circumventing this would require editing the actual code loaded by the browser rather than simply editing a value in the console, and minified & packed JS would make that a more frustrating task than most would bother with, I think.

This would let someone who derives enjoyment from cheating do so without additional difficulties on their part, while letting me offer them a mild rebuke with a dookie achievement for cheating.

Of course, a determined cheater could prevent the game from sending the cheating marker to the server when saving the game. Even trying to alert the server from within the setTrap function could be easily defeated by simply cutting off the web connection while cheating, but this idea is more of a wagging finger than an attempt at preventing any cheating from occurring.

But my question is this: have I missed anything obvious with this idea? Is there a better way to write my conditional (I admit, I came up with it after just a few minutes messing around in Chrome, so it may not work the same in Firefox or something)?


texts: Trying to make a button in Unity which spawns a character each time it's clicked

texts:
I have a simple 2D game, I want a UI button to respawn the character (if it's not already present). The first problem I encountered is that the button only works once. I can't go any further before I solve this, so for now it doesn't spawn anything, I just want it to print debug text every time it's clicked.
It only does that once, unfortunately. How do I make it call the function each time I click it?

using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;

public class Button_Restart : MonoBehaviour
{
    public Canvas Canvas;

    void Awake()
    {

    }

    public void Restart()
    {
        Debug.Log("Restart button was clicked");
        EventSystem.current.SetSelectedGameObject(null);
    }
}


texts:
I'm developing scenario in the Virtual Battlespace 2 Virtual Tool Kit. In my scenario I need to use dialog mode for satisfying some requirements. I've successfully created dialog, and I need movement in the dialog, so that is also done.

The problem is that, if the player gets shot by a terrorist in the scenario, then the player body reacts to that impact. This causes the player head to lock in the upward and downward direction. From this position, the player can no longer look up or down. I need to close the dialog, reset ther player position and start the dialog, again.

How do I enable "look up/down" in the dialog mode?


texts: Algorithm for spending x points on y things divided by n people

texts:
I'm trying to devise an algorithm to spend a given amount of points on a randomly generated list of items each with their own cost in a way that results in having a number of items that is divisible by a given value (the number of points given is always divisible by this). Each item must be represented as equally as possible.

Points: 12
Divisor: 6
Items: Foo (1) & Bar (3)

The optimal result would be 3 Foo and 3 Bar (12 total points and 6 items).

That could be achieved by filling the space alternately starting with the smallest item but that algorithm won't work for other permutations of the starting values or if there are more items to spend points on, some of which may have the same value as other items but must be represented equally in the final result.

The algorithm can result in spending less points than are available but never more. There may not always be a 1 cost item to fill in any remainders.

Another example I can't solve...

Points: 24
Divisor: 8
Items: Foo (1), Nacho (1) , Pizza(2), Bar (3), Cake (4)

Just spending all of the points is easy but spending it in such a way that you end with a specific number of items that can be divided between the divisor has had me scratching my head all day.


texts: One draw call with one big mesh VS many draw calls with many little meshes

texts: I have read that in order to optimize WebGL application, one should reduce an amount of draw calls. But does it mean that computing a one big mesh from all single meshes on CPU by modifying vertices position (which I heard is much slower than GPU while talking about matrix multiplications) and calling the draw call once would be faster than drawing every single mesh using model matrix inside GPU, calling the draw call for each one of them?


texts:
I need to use vibration for my java game, which is only available through xinput since I use xbox controllers. How can I achieve this with jna? I've never worked with dlls before so any help is appreciated. I looked at some tutorials but I haven't found anything about using structures (specifically XINPUT_VIBRATION vibration;) and such.

This is what I want to do in the DLL:

XINPUT_VIBRATION vibration;
ZeroMemory( &vibration, sizeof(XINPUT_VIBRATION) );
vibration.wLeftMotorSpeed = 32000; // use any value between 0-65535 here
vibration.wRightMotorSpeed = 16000; // use any value between 0-65535 here
XInputSetState( i, &vibration );

The above is taken from http://msdn.microsoft.com/en-us/library/windows/desktop/ee417001(v=vs.85).aspx#setting_vibration_effects

Thanks!


texts: How can I achieve this lighting with OpenGL?

texts:
I'm currently trying to implement a type of "smooth" lighting. How can I achieve lighting which looks like this:

http://dl.dropbox.com/u/1668516/concept/warp3.png

Using OpenGl. I've attempted to use blending modes and have come very close to making it work but it came out like this:
https://pbs.twimg.com/media/A1071viCEAAlFmJ.png

Edit:
The technique usedis drawing the lighting image (a white gradient) then drawing all my images using the blending effect glBlendFunc(GL_DIST_COLOR,GL_ZERO)
however the images come out slightly transparent as shown previously I also have no control of how dark the black background is.

and I also wasn't able to change the alpha of the black background which I want to be able to do.

Could I get a few pointers in the right direction?


texts: I want to create a Windows Form-based adventure game where the player clicks a hex on a static map to bring up their next encounter. I have the map already and plan to scan it and convert it to a .bmp file. My problem is that I'm not sure how to tie the map image in with the game code. Unless I'm mistaken, I think I need to use some kind of imagemap control. If that's the case, do I need to plot each hex individually, or is there a way to plot the whole map in bulk? I found this article, but I'm not sure if it's relevant to what I want to do or not. I'm just looking for general information or links to relevant articles. Thanks.


texts:
I am trying to do some physics calculations from scratch, and as a result am creating a small bouncing ball example. However, I have some issues getting correct results from my impact physics when the ball bounces on the floor. I have attempted to follow the simple guide on Gamasutra (as referenced by my lecturer) that does impact physics between two balls. This is elastic collisions meaning the energy should be preserved (the ball should keep bouncing). I can cheat but I do want the proper physics calculations of the impact working as I need to use this for more complicated things later.

My current problem is that the ball bounces to a much higher position than it's starting point. I.e the ball starts at a specific position, with a velocity of 0,0,0 and is being effected by gravity. When it hits the floor however, the velocity calculated is much too high, so it bounces much higher (out of the screen) than the point at where it was dropped. It should, I believe, bounce back to the starting position. Here's a small gif showing what's happening.

Here's my current code. Could anyone point me in the right direction? Thanks!

// create sphere radius 3, color red
my_sphere = new Sphere(3, Vector(0.0,0.0,1.0) );
// set position
my_sphere->setDisplacement( Vector(0,50,0) );
// add gravity acceleration
my_sphere->addAcc( Vector(0.0, -9.82, 0.0) );

Physics foce calculation

// changes the objects velocity and position according to acceleration and time
void PhysicsObject::forceStep(float dt) {

    this->vel = this->vel + this->acc*dt;

    Vector s = this->vel*dt  + ( this->acc * (1/2.0f)  * pow(dt,2) );
    this->displacement = this->displacement + s;
}

Impact physics:

if ( my_sphere->floor_collision() ) {
        // floor properties
        Vector floor_vel = Vector(1,1,1);
        Vector floor_pos = Vector(0,0,0);
        // the floor is immovable e.g. mass=infinite
        float floor_mass = std::numeric_limits<float>::max();
        // Ball properties
        Vector ball_vel = my_sphere->getVel();
        Vector ball_pos = my_sphere->getDisplacement();
        float ball_mass = 1;
        Vector n = ball_pos - floor_pos;
        n = n.normalize();

        float a1 = ball_vel.dotProduct(n);
        float a2 = floor_vel.dotProduct(n);

        float optimizedP = (2.0 * (a1 - a2)) / (ball_mass + floor_mass);

        Vector new_ball_vel = v1-n*optimizedP * floor_mass;

        my_sphere->setVel( new_ball_vel );
}


texts: LibGDX Shader works fine on desktop but does not work at all on Android device

texts:
I made a very basic shader that works perfectly fine on Desktop, but when I try it with an AVD the sprite affected by the shader is not drawn. I have tried with WQVGA API 16 and Nexus S API 23. I have also tried putting this in my shaders but then it doesn't work on Desktop nor android :

#ifdef GL_ES
    "#version 300"
    precision mediump float;
#else
    "#version 130"
#endif

My vertex shader is simply a "passthrough" :

#version 130
attribute vec4 a_color;
attribute vec3 a_position;
attribute vec2 a_texCoord0;

uniform mat4 u_projTrans;

varying vec4 v_color;
varying vec2 v_texCoord0;

void main() {
    v_color = a_color;
    v_texCoord0 = a_texCoord0;
    gl_Position =  u_projTrans * vec4(a_position, 1.0);
}

My Fragment Shader :

#version 130
precision mediump float;
varying vec4 v_color;
varying vec2 v_texCoord0;

uniform sampler2D u_sampler2D;
uniform vec4 color1;
uniform vec4 color2;

void main()
{
    vec4 actualColor = v_color * texture2D( u_sampler2D, v_texCoord0 );

    if(actualColor.g > actualColor.r)
        actualColor = color1;
    else if(actualColor.r > actualColor.g)
        actualColor = color2;

    gl_FragColor = actualColor;
}

Edit :
I changed gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); in my fragment shader in order to test if a red rectangle would appear, but it failed. The red rectangle being the desktop version and on top being Android.

If it helps I also get this error in my Android console :

libpng warning: iCCP: known incorrect sRGB profile
libpng warning: iCCP: known incorrect sRGB profile
libpng warning: iCCP: known incorrect sRGB profile
libpng warning: iCCP: known incorrect sRGB profile
libpng warning: iCCP: known incorrect sRGB profile
emulator: Listening for console connections on port: 5554
emulator: Serial number of this emulator (for ADB): emulator-5554
emulator: emulator window was out of view and was recentered
distrib/android-emugl/host/libs/Translator/GLES_V2/GLESv2Imp.cpp:glGetUniformLocation:1628 error 0x501
distrib/android-emugl/host/libs/Translator/GLES_V2/GLESv2Imp.cpp:glGetUniformLocation:1628 error 0x501
distrib/android-emugl/host/libs/Translator/GLES_V2/GLESv2Imp.cpp:glGetUniformLocation:1628 error 0x501
distrib/android-emugl/host/libs/Translator/GLES_V2/GLESv2Imp.cpp:glGetUniformLocation:1628 error 0x501
distrib/android-emugl/host/libs/Translator/GLES_V2/GLESv2Imp.cpp:glGetAttribLocation:988 error 0x501
distrib/android-emugl/host/libs/Translator/GLES_V2/GLESv2Imp.cpp:glGetAttribLocation:988 error 0x501
distrib/android-emugl/host/libs/Translator/GLES_V2/GLESv2Imp.cpp:glGetAttribLocation:988 error 0x501


texts: How do I swap two objects in C# (specifically Mono) without triggering GC?

texts:
I have two array lists. that I want to swap each frame. My question is, does the variable 'temp' need to be a member variable to avoid triggering GC, assuming this method is called on dozens of objects each frame? I'm not creating a new object, just a new reference to an object.

public void LateUpdate(){
    ArrayList<int> temp = previousFrameCollisions;
    previousFrameCollisions = currentFrameCollisions;
    currentFrameCollisions = temp;
    currentFrameCollisions.clear();
}

I've been told there's no reason to make a primitive into a member variable just to avoid GC, so my best guess is that this also applies to object references.


texts: AABB of a sphere's screen space projection

texts: What is a nice, neat way to get the AABB of a sphere's projection onto the screen? This is to determine simplified geometry for lights in deferred shading.


texts: Tangents face the same direction on opposite sides of mesh

texts:
I have noticed that the tangent vectors that I am calculating are not always facing the correct direction. The tangents on the left and right of the mesh both face the same direction. Here is a screenshot showing this:

I've mapped the XYZ value of the tangent vectors to RGB values in the fragment shader. +Z is towards the camera. As you can see, both sides of the teapot have tangents facing towards the camera instead of only the left as I'd excepted.

Also, the UVs for the mesh are correct and increase smoothly across the surface (I used blender's default sphere mapping to generate the UV coordinates):

The tangents are correct even over the seams.

I am using the following piece of code to compute my tangents:

for (size_t i = 0; i < mesh.face_list.size(); ++i)
{
    const Face& face = mesh.face_list[i];

    const size_t& i1 = face.vertex_indices[0];
    const size_t& i2 = face.vertex_indices[1];
    const size_t& i3 = face.vertex_indices[2];

    const Vec3& p1 = mesh.vertex_list[i1-1];
    const Vec3& p2 = mesh.vertex_list[i2-1];
    const Vec3& p3 = mesh.vertex_list[i3-1];

    // Compute edges.
    Vec3 e1 = p2 - p1;
    Vec3 e2 = p3 - p1;

    const size_t& txi1 = face.texcoord_indices[0];
    const size_t& txi2 = face.texcoord_indices[1];
    const size_t& txi3 = face.texcoord_indices[2];

    Vec2 texcoordDelta1 = mesh.texcoord_list[txi2-1] - mesh.texcoord_list[txi1-1];
    Vec2 texcoordDelta2 = mesh.texcoord_list[txi3-1] - mesh.texcoord_list[txi1-1];

    float coefficient = 1.0f / (texcoordDelta1.x * texcoordDelta2.y - texcoordDelta2.x * texcoordDelta1.y);
    Vec3 faceTangent = coefficient * (texcoordDelta2.y * e1 - texcoordDelta1.y * e2);

    const size_t& ti1 = face.normal_indices[0];
    const size_t& ti2 = face.normal_indices[1];
    const size_t& ti3 = face.normal_indices[2];

    // Add tangent to all vertices making up the face.
    mesh.tangent_list[ti1-1] += faceTangent;
    mesh.tangent_list[ti2-1] += faceTangent;
    mesh.tangent_list[ti3-1] += faceTangent;
}

// Normalise and orthogonalise all tangents.
for (size_t i = 0; i < mesh.tangent_list.size(); ++i)
{
    mesh.tangent_list[i] = normalise(mesh.tangent_list[i] - (mesh.normal_list[i] * dot(mesh.normal_list[i], mesh.tangent_list[i])));
}

As far as I can tell, the main part of the calculation seems correct compared to things I've found online:

float coefficient = 1.0f / (texcoordDelta1.x * texcoordDelta2.y - texcoordDelta2.x * texcoordDelta1.y);
Vec3 faceTangent = coefficient * (texcoordDelta2.y * e1 - texcoordDelta1.y * e2);

Generally, normal mapping works great, but there are subtle lighting errors on parts of the mesh after the incorrect tangent space transformation. Hopefully this is all of the information needed to get to the bottom of this.


texts: How to create opacity mask from colored bitmap?

texts:
For the image (bitmap) below,

if I do:

Create a spite with the image in unreal engine.

Create a opacity mask on the spite.

Use this image, choose a specific color, such as blue, make its corresponding region the only opacity region on the mask.

My question is about the implementation of part 2 and part 3 in Unreal engine, they are quite confusing.

If anyone know how to implement it in unity, it would also be helpful.

Thanks a lot.


texts:
I'm looking how to implement simple movement for an airplane in 3D in godot, i couldn't find any tutorial or any hints on how to do this, mostly theoric information on a more real flight movement.
Any ideas on how to implement this?
I'm not looking for realistic physics, just a more arcade type of movement


texts: A way to create a variable that includes a modifier that should be checked every step [Gamemaker]

texts:
I can't tell if I am being stupid, but I am looking for a way in Gamemaker to have a variable include a modifier which has the potential to change every step.

This variable is called mTiredness, and I would like it to include the TimeOfDayModifier which needs to be checked frequently.

However, I obviously can't put

mTiredness = mTiredness + TimeOfDayModifier

in a Step event, as this would add the modifier, in my case, 60 times a second, which I do not want!

Instead, I want a consistent variable comprised of the base amount and the modifier, while allowing that modifier to change.

Can anybody help me? I cannot think of an easy way to do this.


texts: How can I get the Launch dynamic link in Unity?

texts:
I have integrated firebase dynamic link sdk in my app and it is working perfectly fine,

I can generate dynamic links, and when clicked on them if the app is not installed it redirects me to the playstore and if installed open up the link in app.

My question is how can I get that generated link when I open the app through it, I just could not able to find anything in docs

the code I am using to listen for link clicks is as follows

void Start()
{
    DynamicLinks.DynamicLinkReceived += OnDynamicLink;
}

// Display the dynamic link received by the application.
private void OnDynamicLink(object sender, EventArgs args)
{
    var dynamicLinkEventArgs = args as ReceivedDynamicLinkEventArgs;
    Debug.LogFormat("Received dynamic link {0}", dynamicLinkEventArgs.ReceivedDynamicLink.Url.OriginalString);
    // Above line gets me the original base link,
    // But I want the link which I clicked
}


texts: Position Reconstruction from Depth by inverting Perspective Projection

texts:
I had some trouble reconstructing position from depth sampled from the depth buffer. I use the equivalent of gluPerspective in GLM. The code in GLM is:

template
GLM_FUNC_QUALIFIER detail::tmat4x4 perspective
(
    valType const & fovy,
    valType const & aspect,
    valType const & zNear,
    valType const & zFar
)
{
    valType range = tan(radians(fovy / valType(2))) * zNear;
    valType left = -range * aspect;
    valType right = range * aspect;
    valType bottom = -range;
    valType top = range;

    detail::tmat4x4 Result(valType(0));
    Result[0][0] = (valType(2) * zNear) / (right - left);
    Result[1][2] = (valType(2) * zNear) / (top - bottom);
    Result[2][3] = - (zFar + zNear) / (zFar - zNear);
    Result[2][4] = - valType(1);
    Result[3][5] = - (valType(2) * zFar * zNear) / (zFar - zNear);
    return Result;
}

There doesn't seem to be any errors in the code. So I tried to invert the projection, the formula for the z and w coordinates after projection are:

and dividing z' with w' gives the post-projective depth (which lies in the depth buffer), so I need to solve for z, which finally gives:

Now, the problem is I don't get the correct position (I have compared the one reconstructed with a rendered position).
I then tried using the respective formula I get by doing the same for this Matrix.
The corresponding formula is:

For some reason, using the above formula gives me the correct position. I really don't understand why this is the case. Have I done something wrong? Could someone enlighten me please?


texts: How do I use tiles and sprites together in an isometric scene?

texts:
I'm trying to write a 2D isometric scene. Rendering order is complex, since both tilemaps and sprites are different concepts. Rendering one of the 2 before the other will draw the scene incorrectly.

Tiles and Sprites both have some common data that can be used as render information. I thought of creating an extra object which simply holds the coordinates and texture data. However, this also meant having to couple a tile or sprite to a render info object. (something I haven't figured out). This adds complexity. However, I thought this way I could abstract over any renderable object.

This tutorial defines tiles as any other sprite and then uses a topology algorithm to sort the scene every frame.

I was actually thinking of using the pigeon hole algorithm by sorting the render info objects on their depth property.

How is this usually done? I can't wrap my head around it.

Bear in mind that I have no actual z-depth to work with. Everything relies on the artificial depth from the x and y coordinates.


texts: Shader authoring/editing tools for GLSL ES

texts:
Since Render Monkey has been discontinued (perhaps due to the complexity of today's shading languages), there are few successors that can match its functionality. Is there any useful tool for material editing aimed at developers and artists alike, but concentrated (or with substantial support for) on embedded GLSL shaders?

Render Monkey itself wasn't that flexible (I'm not aware if it allowed the usage of several textures, each with its own set of texture coordinates - plus, it didn't seem to be that intuitive either).  Apart from complete engines, is there such a stand-alone tool that can be used together with a stand-alone engine (able to interface with a custom application)?


texts: libgdx intersection problem between rectangle and circle

texts:
My collision detection in libgdx is somehow buggy.
player.png is 20*80px and ball.png 25*25px.

Code:

@Override
public void create() {
    // ...
    batch = new SpriteBatch();
    playerTex = new Texture(Gdx.files.internal("data/player.png"));
    ballTex = new Texture(Gdx.files.internal("data/ball.png"));

    player = new Rectangle();
    player.width = 20;
    player.height = 80;
    player.x =  Gdx.graphics.getWidth() - player.width - 10;
    player.y = 300;

    ball = new Circle();
    ball.x = Gdx.graphics.getWidth() / 2;
    ball.y = Gdx.graphics.getHeight() / 2;
    ball.radius = ballTex.getWidth() / 2;
}

@Override
public void render() {
    Gdx.gl.glClearColor(1, 1, 1, 1);
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

    camera.update();

    // draw player, ball
    batch.setProjectionMatrix(camera.combined);
    batch.begin();
    batch.draw(ballTex, ball.x, ball.y);
    batch.draw(playerTex, player.x, player.y);

    batch.end();

    // update player position
    if(Gdx.input.isKeyPressed(Keys.DOWN)) player.y -= 250 * Gdx.graphics.getDeltaTime();
    if(Gdx.input.isKeyPressed(Keys.UP)) player.y += 250 * Gdx.graphics.getDeltaTime();
    if(Gdx.input.isKeyPressed(Keys.LEFT)) player.x -= 250 * Gdx.graphics.getDeltaTime();
    if(Gdx.input.isKeyPressed(Keys.RIGHT)) player.x += 250 * Gdx.graphics.getDeltaTime();

     // don't let the player leave the field
     if(player.y < 0) player.y = 0;
     if(player.y > 600 - 80) player.y = 600 - 80;

     // check collision
     if (Intersector.overlaps(ball, player))
         Gdx.app.log("overlaps", "yes");
}