texts: Javascript canvas check if all recs on the screen overlap a new one

texts:
So I know the AABB collision detection formula, however, this code does not work. Whenever I press space, a new square pops up. But this new square can spawn inside another, something that I do not want to happen. Here is a snippet of the code I think is going wrong:

var xTopsBotsYTopsBotsSquares = [];

//Makes a randint() function.
function randint(min, max) {

    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function checkForOccupiedAlready(left, top, right, bottom) {

    if (xTopsBotsYTopsBotsSquares.length == 0) {
        return true;
    }
    for (var i = 0; i < xTopsBotsYTopsBotsSquares.length; i++) {
        var data = xTopsBotsYTopsBotsSquares[i];

        if (data[0] <= right || data[1] <= bottom ||
            data[2] >= left  || data[3] >= top) {/*Do nothing*/}
        else {

            return false;
        }
    }

    return true;
}

//Makes a new square
function makeNewsquare() {
    var checkingIfRepeatCords = true;
    //DO loop that checks if there is a repeat.
    do {
        //Makes the square x/y positions
        var squareRandomXPos = randint(50, canvas.width - 50);
        var squareRandomYPos = randint(50, canvas.height - 50);

        //Tests if that area is already occupied
        if (checkForOccupiedAlready(squareRandomXPos,
                                    squareRandomYPos,
                                    squareRandomXPos+50,
                                    squareRandomYPos+50) == true) {

            xTopsBotsYTopsBotsSquares.push([squareRandomXPos,
                                            squareRandomYPos,
                                            squareRandomXPos+50,
                                            squareRandomYPos+50]);
            console.log(squareRandomXPos, squareRandomYPos, squareRandomXPos+50, squareRandomYPos+50);
            checkingIfRepeatCords = false;
        }
    }
    while (checkingIfRepeatCords == true);

}


texts:
I am working in Flash and a few things have been brought to my attention. Below is some code I have some questions on:

addEventListener(Event.ENTER_FRAME, function(e:Event):void
{
    if (KEY_RIGHT)
    {
        // Move character right
    }
    // Etc.
});

stage.addEventListener(KeyboardEvent.KEY_DOWN, function(e:KeyboardEvent):void
{
    // Report key which is down
});

stage.addEventListener(KeyboardEvent.KEY_UP, function(e:KeyboardEvent):void
{
    // Report key which is up
});

I have the project configured so that it has a framerate of 60 FPS. The two questions I have on this are:

What happens when it is unable to call that function every 1/60 of a second?
Is this a way of processing events that need to be limited by time (ex: a ball which needs to travel to the right of the screen from the left in X seconds)? Or should it be done a different way?


texts: Is there a way to drain durability from an item instead of a sword, for instance?

texts:
I am modding Minecraft 1.8 using Eclipse with Forge, and I just wondered, is there a way to drain durability from a battery, for instance, instead of a piece of armor when hit.
I have tried things like getting an item from the player's inventory and attempting to reduce its durability, so that would be a possibility, however, I was unable to find a way to do so?


texts: What kind of environment is expected in elevated, hot areas?

texts:
I'm creating an "exploration" game where the overworld map will be randomly generated.
The biomes are generated using the data given by a "temperature map" , a "humidity map", and an elevation map for instance : cold + humidity = snow, hot + humidity = jungle, etc
The problem I'm left with is how to deal with elevated zones in hot climate. Right now it is set to the "bare" biome (the gray areas in the following pic), which I guess is supposed to mean "deserted dry land". On the other hand, elevated zones with colder temperatures is set to snow (in white), which is ok.
So, how should I deal with the elevated zones in cold climate? I have several ideas but I feel that none of them works:
1) set it to snow as well, but I think it would feel weird
2) set it to "bare" but I don't think it actually exists IRL or that i'd have any interesting gameplay perspectives


texts: How to think about 2D scaling/rotation transformations

texts:
This is a kind of embarassing question to me since I'm getting more in-depth with XNA but some times my way of thinking about things in my head contradicts an example and I need to re-think it to make it work.

So let's say I am just working with a sprite that is 10 wide and 10 high.

Scaling:

When I apply a scaling matrix, am I just shifting the points back or scaling the X-axis and Y-axis in the LOCAL coordinate space of that sprite? I ask because on this page:

http://www.riemers.net/eng/Tutorials/XNA/Csharp/Series2D/Coll_Detection_Matrices.php

and

http://www.riemers.net/eng/ExtraReading/matrices_geometrical.php

It shows the X and Y of the local axis the sprite is in being scaled down. So in my head, I think that a scaling means that you scale down the local axis space where the sprite is located which makes it smaller.

Rotation:

When I do a rotation matrix, am I rotating the local x and y axis of the sprite around the world origin or rather do I think about it as rotating the local coordinate space entirely around the world origin?

Translation:

This to me is just moving that scaled image with those smaller x and y axis to some other point in the world.


texts:
First at all, I'm not asking how to handle or detect collision. I already have that.

My actual situation is, I have a system collision and I detect the collisions. Every collision detected is store as a message containing the two entities colliding with some information like type of collision or something. Later, all messages is processed.

I'm trying to figure out how to implement the reaction of the entities in every collision with that message. In the game a collision can trigger an action like talking with another, change the level, kill the character, store an object, not letting go...

I don't want to hard-code the calls and methods if possible (in my ideal world,I can define even the behaviour in an xml an read from that!). My first approach is a class where I store a list of possible actions/callback functions and attach it to the entity as a component. When a collision succed, I go to the entity and depending of the collision, execute the correspond callback.

Still I don't know how to determine the callback to execute or where I must code the behaviour. Any ideas? What you think about this approach?

By the way, I'm building everything from scratch, with c++ and SFML and following the entity system approach, for educational purpose.


texts:
In my 2D Platformer character controller that has both a wall jump and a double jump ability, how would I approach implementing a feature that stops the player from returning to the wall they initiated a wall jump from, while still making sure my controls feel responsive? (like they did in Celeste, apart from the double jump)
So far, I have got a timer that starts when the player initiates the wall jump and stops the player from moving until the timer is over. I'm already not too happy with that approach because it leads to this moment where it feels like player input is basically ignored.
Now in addition, I realised that after the timer is over, while just pressing left won't be enough to return to (a higher part of) the wall, simply doing a second jump will enable the player to easily make their way up the wall.


texts: Why is my light not working as expected in OpenGL 2.0 using GLSL?

texts:
First off, this is a Uni assignment, but the lecturer is stumped too.

The light (attached to the mouse) only works when inside of the object (a sphere in this case). I've tried multiplying the normals of the sphere by -1 and the distance of the light to the sphere by -1 also. I have no idea what the cause of this is.

Here is the fragment shader:

const float     lightWeighting = 0.75;
const float     textureWeighting = 0.25;

const float     PI = 3.14;
const float     lightIntensity = 1.0;
const float     constFudge = 0.025;
const float     linearFudge = 0.025;
const float     quadraticFudge = 0.05;

float rend  = 250.0;
float rstart = 50.0;

uniform float       Intensity;
uniform sampler2D   grabTexture;
//varying   sampler2D   HeatValues

varying vec3        Normal;
varying vec3        Vertex;
varying vec2        texCoord;

void main(void)
{
  vec3 pigPos = Vertex;
  vec3 normPigPos = normalize(pigPos);

  vec3 lightPos = vec3(gl_LightSource[0].position.xyz);

  vec3 normLightPos = normalize(lightPos);

  float effectiveIntesity;

  vec3 normNormal = normalize(vec3(Normal.xyz));

  vec3 t = vec3(pigPos - lightPos);

  float distToLight = length(t); //I belive this is where it is going wrong

  float d = dot(normNormal.xyz, normLightPos.xyz);
  if(d > 0.0)//facing the light
  {

    effectiveIntesity = d*lightIntensity * (1.0/(constFudge + (linearFudge*distToLight) +(quadraticFudge*distToLight*distToLight)));

  }
  else
  {
    effectiveIntesity = 0.0;
  }

  //TODO: change the colour of the pixel
  vec4 lightingColour = vec4(vec4( 1.0 ) * effectiveIntesity); //TODO: improve

  gl_FragColor = lightingColour;

}

Vertex Shader as requested:

//I am surprisingly important

uniform float   Intensity;
varying vec3    Normal;
varying vec3    Vertex;
varying vec2    texCoord;

void main(void)
{
    gl_Position     = ftransform();
    texCoord    = gl_MultiTexCoord0.xy;

    Normal = vec3(gl_Normal.xyz);
    Vertex = vec3(gl_Vertex.xyz);

}

Normals are as loaded from the obj file which was produced with blender


texts: What is the best way to store meshes or 3d models in a class

texts:
I am wondering, how I should store my mesh into memory after loading it from whatever file. I have Questions floating in my head:

Should a mesh could have sub meshes or does the 3d model just store a list of meshes all on the same level
Is there one material assigned to one mesh 1:1?
What do I have to consider, if I want to store skeletal animations?

Btw it's a OpenGL|ES2 iOS game using GLKit.

I came up with some basic struct types:
(But I think they are way to simple and I need to add padding or change the vector3 to vector4.)

typedef union _N3DShortVector2 {
    struct { short x, y; };
    struct { short s, t; };
    short v[2];
} N3DShortVector2;

typedef union _N3DShortVector3 {
    struct { short x, y, z; };
    struct { short r, g, b; };
    struct { short s, t, p; };
    short v[3];
} N3DShortVector3;

typedef GLKVector3 N3DFloatVector3;

typedef struct _N3DMeshRecordSV3 {
    N3DShortVector3 v1, v2, v3;
} N3DMeshRecordSV3;

typedef struct _N3DMeshRecordSV3FN3ST2 {
    N3DShortVector3 v1, v2, v3;
    N3DFloatVector3 n1, n2, n3;
    N3DShortVector2 t1, t2, t3;
} N3DMeshRecordSV3FN3ST2;


texts: Checking for collisions on a 3D heightmap

texts:
I have a 3D heightmap drawn using OpenGL (which isn't important). It's represented by a 2D array of height data. To draw this I go through the array using each point as a vertex. Three vertices are wound together to form a triangle, two triangles to make a quad. To stop the whole mesh being tiny I scale this by a certain amount called 'gridsize'.

This produces a fairly nice and lumpy, angular terrain kind of similar to something you'd see in old Atari/Amiga or DOS '3D' games (think Virus/Zarch on the Atari ST).

I'm now trying to work out how to do collision with the terrain, testing to see if the player is about to collide with a piece of scenery sticking upwards or fall into a hole.

At the moment I am simply dividing the player's co-ordinates by the gridsize to find which vertex the player is on top of and it works well when the player is exactly over the corner of a triangle piece of terrain.

However...

How can I make it more accurate for the bits between the vertices? I get confused since they don't exist in my heightmap data, they're a product of the GPU trying to draw a triangle between three points. I can calculate the height of the point closest to the player, but not the space between them.

I.e if the player is hovering over the centre of one of these 'quads', rather than over the corner vertex of one, how do I work out the height of the terrain below them? Later on I may want the player to slide down the slopes in the terrain.


texts: Moving directional light cause huge fps drop: why?

texts:
I've implemented a simple script to simulate Sun Rotation (day/night cycle).

In my "Update" i Rotate main Directional Light (the sun).
What i've noticed is that my FPS dropped from 60 to 20-25 fps.

I can understand why: recalculate all light each frame can be (euphemism) cpu-consuming.

So i switched approach using an InvokeRepeating with a repeating time of 0.25f seconds (4 "movement" per second).

Also with this approach my frame rate drop from 60 to 50 (unacceptable).

So my question is : is there a way to move/rotate a light (simulating a day/night cycle for instance) without meet a so big fps-dropping but mantaining realism ?

Thanks


texts: Unity free look camera on two axes. How do I do it?

texts:
I'm new to Unity and c# but have programming experience...  I have a a simple "game" in Unity that shows one sphere orbiting another.  How do I allow the camera to be moved by the user in a "free look" dynamic?  I want to be able to press the right mouse button and adjust the camera on two axes. I'm using Unity 5.0. Whenever I run the following Unity freezes when I press the right mouse button.

Here's the camera control script:

using UnityEngine;
using System.Collections;

public class CameraControl : MonoBehaviour
{
     private float horizontalSpeed;
     private float verticalSpeed;

     void Update ()
     {
           while (Input.GetMouseButtonDown(1))
           {
                 horizontalSpeed = Input.GetAxis ("Mouse Y");
                 verticalSpeed = Input.GetAxis ("Mouse X");
                 transform.Translate(verticalSpeed,horizontalSpeed,0.0f);
           }
     }
}


texts: Unity LoadLevelAdditive and baked light scene settings

texts:
I am a programmer for a small game.
For our levels, I separated the UI from the level data, so one scene is a scene which contains only the UI, the other scene has all the gameobjects and models and ... the light.

So when loading a level, I first load the UI scene (LoadLevel), then the actual play scene (LoadLevelAdditive).

Now that our graphics guy wants to bake some lights, he is telling me it doesn't work, because whatever his settings in the play scene, Unity ignores them and uses the settings of the UI scene.
He also tells me we cannot just ignore the light settings of the UI scene ...

So my question is, how do I make Unity ignore the light settings of a certain scene (UI scene in my case) or how can I enable a settings override?

Thanks.


texts:
I am trying to make simple rain drop effect on screen.Something like this
http://fc00.deviantart.net/fs20/f/2007/302/5/6/Rain_drops_by_rockraikar.png

My idea is to:

Create small drop shaped normal textures, randomly put few on screen, apply texture perturbation and mix with current frame pixels.

Here are my questions:

Does this idea even have sense? How professionals do this effect? Everything from text to code will be appreciated
How to pass pixels to shader of already rendered frame?


texts:
I am having some trouble understanding how openGL blend modes work. At first I was using
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
and it all looked fine except that I couldn't use any additive glowing effects simultaneously without changing blend modes all the time. So I was advised to use
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA) and textures with premultiplied alpha and now both additive and "normal" textures appear fine except that for some reason some textures have slightly jagged/thick outlines. I found that this only happens to images that have semi-transparent pixels but I'm not sure why.

This is an example of anti-aliased text with this kind of outline. The first is how it used to look and how I want it to look and the second is how it looks with the mode I'm trying to use. I don't want its color blended with the background. Is what I'm asking possible?


texts: Get return of asynchronous callback since module export- Nodejs

texts:
Server:

require('./MovimientoJugador')();
var camino4=MoverJugador(startX,startY,endX,endY,mapa2);
console.log("Camino: " + camino4);

MovimientoJugador:

module.exports = function() {
  var Camino="uno";
 this.MoverJugador = function(startX,startY,endX,endY,mapa) {
easystar.findPath(startX, startY, endX, endY,function( path ) {
Camino=JSON.stringify(path);
 console.log("C:" + Camino)
 return Camino;
}}

Console:

Camino= uno
C=(X:1,Y1)(X2:Y2) etc...

The variable Camino has the value of one when declared.
At the time that the server shows it, it does not give you time to show the last return value.

How could I turn this into a promise or make a wait of x seconds?


texts:
I'm using LWJGL, however I'm a bit confused on what to do.

I'm trying to write an AI simulation, however I'm stuck at this problem. I have one camera, and I plan to move the camera to the mob position and then save it to the screen, then I will then use that to input into the neural network, then it does its action, then I move onto the next mob and repeat. Then, finally I move the camera to the player position so I can see what is happening.

The problem is that I just want to see out of the player eyes and not the mob eyes. However, I'm confused on how to do it. http://www.lwjgl.org/wiki/index.php?title=Taking_Screen_Shots the only way I can think of getting the information for what the mobs see is to take a screen shot if I render it to the screen. But, then if I do this all I will see is everything jump around a lot.

The code will look something like this

public class Game() {
  public Game() {
      camera = new Camera();
      player = new Player();
      ArrayList<Mobs> mobs = new ArrayList<Mobs>();
  }

  public void update() {
  player.update();
    for(int i=0; i<mobs.length; i++) {
      camera.setPos(mobs.get(i).getPos();
      mobs.get(i).render;
      saveScreen();
      mobs.get(i).logic();
    }
  }

   public void render() {
     player.render();
   }
}

There must be a better way. For example, maybe it possible to not render to the screen to input the data into the mob. Or maybe, I don't need to save it to say .png to then put into the neural network.


texts: How can I calculate a terrain's normals?

texts:
Im trying to implement basic lighting in Opengl 3+ (a sun) with this tutorial :

http://www.mbsoftworks.sk/index.php?page=tutorials&series=1&tutorial=11

Im building a basic terrain and its working well. Now im trying to add normals, and I think its not working well :

Terrain in wireframe

As you can see I dont think my normals are good.

This is how I get them :

for(x = 0; x < this.m_size.width - 1 ; x++)
    {
        for(y = 0; y < this.m_size.height - 1 ; y++)
        {
            immutable uint indice1 = y * this.m_size.width + x;
            immutable uint indice2 = y * this.m_size.width + (x + 1);
            immutable uint indice3 = (y + 1) * this.m_size.width + x;
            immutable uint indice4 = (y + 1) * this.m_size.width + x;
            immutable uint indice5 = y * this.m_size.width + (x + 1);
            immutable uint indice6 = (y + 1) * this.m_size.width + (x + 1);

            Vector3 v1 = vertexes[indice3] - vertexes[indice1];
            Vector3 v2 = vertexes[indice2] - vertexes[indice1];
            Vector3 normal = v1.cross(v2);
            normal.normalize();

            normals[indice1] = normal;

            indices ~= [indice1,
                        indice2,
                        indice3,
                        indice4,
                        indice5,
                        indice6];
        }
    }

I use this basic shader : http://ogldev.atspace.co.uk/www/tutorial18/tutorial18.html   or in the link I posted at the top.

Thanks.


texts: Why does my Java game loop randomly jump to 62 FPS and crash?

texts:
I've been working on a Java game, but I couldn't keep it from stuttering. I did some research, and found out that I was using a bad game loop. I've been working on a new game loop, which works a little better, but my framerate often jumps from 60 FPS to 62 FPS, and sometimes even crashes. This is the loop I'm using;

import java.applet.Applet;
import java.awt.Color;
import java.awt.Frame;

@SuppressWarnings("serial")
public class GameLoop extends Applet implements Runnable {

    final int FRAMERATE = 60;

    @Override
    public void init() {
        setSize(1280, 720);
        setBackground(Color.WHITE);
        setFocusable(true);
        Frame frame = (Frame) this.getParent().getParent();
        frame.setTitle("Game Loop");
    }

    @Override
    public void start() {
        Thread thread = new Thread(this);
        thread.start();
    }

    @Override
    public void stop() {

    }

    @Override
    public void destroy() {

    }

    @Override
    public void run() {
        int framerate = 0;
        long counter = 0;

        long lastTime = System.nanoTime();
        long frameTime = 1000000000 / FRAMERATE;

        while (true) {
            long currentTime = System.nanoTime();
            long updateTime = currentTime - lastTime;
            lastTime = currentTime;

            counter += updateTime;
            framerate++;

            if (counter >= 1000000000) {
                System.out.println(framerate + " fps");
                counter = 0;
                framerate = 0;
            }

            try {
                Thread.sleep((frameTime * 2 - updateTime) / 1000000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

I've walked it through a couple of times, but I can't find out what's wrong. This is the console output I get;

60 fps
60 fps
60 fps
60 fps
62 fps
60 fps
62 fps
60 fps
60 fps
60 fps
...
Exception in thread "Thread-3" java.lang.IllegalArgumentException: timeout value is negative
    at java.lang.Thread.sleep(Native Method)
    at GameLoop.run(GameLoop.java:58)
    at java.lang.Thread.run(Unknown Source)

As far as I can understand, the loop crashes because Thread.sleep((frameTime * 2 - updateTime) / 1000000); has a negative input, but I don't know why it is negative.

I've added;

if (updateTime < 0)
    updateTime = 0;

After;

long currentTime = System.nanoTime();
long updateTime = currentTime - lastTime;
lastTime = currentTime;

To prevent getting a negative input, but the problem still occurs. Also, I've tried to implement the loop into my game, but it's even laggier than before. The player seems to be shaking back and forth while moving.

Could anyone tell me what I'm doing wrong and how I can fix this?


texts: Is there a way to create multi-resolution graphics for game with createjs?

texts:
I'm on a advanced development for a game made with createjs framework. However it's time to export it to some platforms. The graphics are made for the iPad 3 resolution.

I would like to export them to devices with less processing power, like iPhone 4 or low end Androids. But hi-definition assets drains the little processor of them.

Resizing all the files is not a solution. There must be some "scale factor" on image loader or another mechanism to get images in correct sizes.

If my game canvas has virtual 1000px wide, and my asset has 1000px wide, the canvas will be filled by the asset. If I resize it to half size, it will be 500px wide, and the canvas will be just half filled. There should be a scale factor that should get the displayObject (not the asset) and set its sizeX and sizeY to double size to fill the screen again. I can be done manually for every one, but I'm looking for a better solution.


texts:
I'm making a platformer in Pygame. One of the sprites I'm using is a flag, and I want to detect if the player collides with the flagpole (just like in Super Mario Bros). The problem is that the image is wider than the flagpole, because of the flag itself. I build the Rect for every sprite based on their image, just like so:

def initialize_rect(self, pos, correction = 0):
    self.rect = self.image.get_rect(topleft = pos)

Doing this, a collision is detected when the player touches the leftmost part of the image, which is a long way from the pole, so it looks terribly wrong.

I'm trying to figure out a way to change the collision box of the sprite, but nothing I try seems to work properly. I've tried the Rect.inflate() method, but that yielded no success. It shrinks the Rect from right to left, and if I then try to change the location of the Rect, the image changes its position too.

I could just make another sprite to detect collisions and somehow link it to the flag, but that would force me to change my design.

Is there a way to change the collision boxes of sprites directly in Pygame?


texts: How to make the player slide smoothly against terrain

texts:
I'm making an isometric game. When the player tries to walk diagonally into a wall I want them to slide smoothly across it, so whatever portion of the movement would be legal is used, and anything in the direction of the normal is thrown away. Walls can be any angle, not just vertical or horizontal, and the player has 360 motion.

I feel like I'm almost there but I can't put the last piece into place.

Update: great news everyone! I have it working. But... I'm a bit confused what I should be normalising and what not. The normal just needs to be a unit vector, right? but then I'm mixing that with my input so I'm normalising that - am I wrong?

By the way, I have also found that I need to push the player 1 pixel in the direction of the normal, so that they don't get stuck on things - works well.


texts: Different types of smooth object movement

texts:
In a game I have a specific object and two positions the object will move from and to.
I already have the function for calculating current position in specific time.

It works like this:

Inputting 0 will move the object to Position 1.

Inputting 1 will move the object to Position 2.

Inputting 0.5 will move the object in the middle of the two positions.

etc...

(In the examples below, time is varying from 0 to 1)
When I want to start the object slowly and stop it when it is moving fast, I use:

MoveObject(sin(time * 90))

When I want to start the object fast and stop it as it is getting slower, I use:

MoveObject(1 - cos(time * 90))

Without the effects, it's:

MoveObject(time)

How do I make the object start moving slowly, move fast in the center of two positions and then get slower while reaching the second position?


texts: How do I play background music in Slick/LWJGL?

texts: I'm trying to play music in the background for my opening menu, but cant seem to find a tutorial specifically on how to play a music file. Does anyone know how this can be accomplished?


texts: Best way to do a strategic map for a 4X space game on a web page?

texts:
I'm currently looking at the options regarding how to do a strategic map for a web application.

My goals here are :

a synthethic view of what's happening in a stelar system
the ability to management movements (through displaying trajectories of some ships and planets/star(s))
the development should'nt take years, since we're few on the project

The usability challenges at hands are IMHO:

scale issues: both in terms of ships/planets/stars volumes and distance. In the end, I guess markers/symbols are the way to go
density of information: there could be much there
frequent updates of the map needed (every 30 seconds or so, would be better if partial reload/refresh possible)

Options I'm aware of:

use of a table, through the background image and cells images

 + easy to do on my own
+ partial refresh possible (ajax on a per cell basis)
 - very low resolution => looks poor

JavaScript map drawing

 + looks very powerful
 - big work needed (I haven't found pre existing plugin/library/framework doing this, whereas I'm not a JavaScript guru)
 - way to go unclear: canvas or dom manipulation?

use of svg pictures

+ resolution amazing
+ http://raphaeljs.com/ to the rescue
- I don't know much about svg

CSS3

I'm rather clueless about it, what about performance/cross browser support and the like...

As a side note, I don't want to bother too much for IE.

Did I miss something obvious? What would you suggest?

thanks in advance
best

BTW, a related topic but more focused on svg: Is SVG a viable technology choice for web-based game?


texts:
Background
I'm building a simple game where two ships are launching missiles at each other in space.
Stuff got complicated when the ships started moving in a frictionless environment and the missiles naturally needed to do the same thing.
Premises

A missile has a constant acceleration and is trying to hit a moving target in a frictionless environment.
Target is also constantly accelerating in the same frictionless environment.
The frictionless environment is only 2 dimensional
There is no gravitation affecting the missile

Question
What math should I use to determine the direction the missile should jolt in?
What i have right now
I've implemented this answer which works quite alright. I am not 100% sure of what a, b, c etc means and not sure which math is actually implemented here.
I modified above linked answer by making the missile mimmic its targets jolts and adding its own on top of those. It is an ugly solution to say the least.
Problem with current solution
The current solution requires to know the speed of the missile.
The missile is constantly accelerating, and it has no top speed.
Unless I know how far the missile will travel, I cannot know the average speed.
Above solution requires that I know the speed of the projectile.


texts:
Possible Duplicate:
  How do you create a single/internal pre-loader for a Flash game written using Flex?

Hi guys, Im trying to make a preloader in a Flash game.

Thing is, I need some advices on this since I never made one, I have the game almost complete, but when, i.e, I upload the game to a website I get a white screen for a few seconds, and then I see the game.

Is there a simple way, maybe using an a API or something like that, to make a preloader screen?

Im using Flash Builder fyi.

Thx!


texts: Ray-plane intersection to find the Z of the intersecting point

texts:
I have a rectangle in 3d space (p1, p2, p3, p4) and when the mouse rolls over it I need to calculate the exact Z of the point on the rect, given the mouse coordinates (x, y).

Would a Ray-plane intersection find the Z of the intersecting point?

Edit: Would this one-liner work? .. it returns the t value for the intersection, apparently the Z value.

 float rayPlane(vector3D planepoint, vector3D normal, vector3D origin, vector3D direction){

     return -((origin-planepoint).dot(normal))/(direction.dot(normal));
 }


texts:
The problem: I can't fit all my 2d animation sprites for all units and environment in 1 spritesheet.

Everything batches fine until I use two spritesheets... I noticed the following : all units from spritesheet A batch fine until something needs to be rendered fom spritesheet B. so lets say from back to camera : 50units - tree -50 units - camera will result in 3 drawcalls... Not that bad but if you have: unit- tree - unit -tree -unit -tree ... like it's probably most of the time... this wil result in 100+ drawcalls even though you have only two spritesheets...

How can you solve this? Or better, how can i use two spritesheets and have only two drawcalls even though the sprites are at different distances to the camera

Hope this image helps to understand the problem:

1 : the trees are on spritesheet B and batch fine
2: the batching is broken as the unitsprite sits on spritesheet A and is put in between the trees...


texts: What is the easiest genre of game to make?

texts:
Before you down vote let me give some restrictions.

I like RPG but they seem long and hard to make but after you make the framework the rest sort of falls into place where as platformers never get faster as each map starts from scratch.

So under these conditions what is the easiest genre of game to develop as a hobby project.

I am on my own.
The style of graphics must be available. Can be ripped (not publishing).
Not bothered about commercial quality.
Must be real size game, multiple levels and stuff.

Thanks

Edit:

I build games in C++ and Direct x 9.c


texts: Can I animate render targets or the swap chain?

texts:
I want to animate some synthetic video bits to fullscreen w/o tearing. Can I set up D3D 9/10/11 in exclusive mode, and have it present a series of buffers that I'm writing to?

I know how to copy system memory bits into a texture, then draw that texture as a fullscreen quad, but it seems like overkill. Why should I use the triangle rasterizer when I want to do something so simple?

All I want to do is set up a long (4-8 buffer) swapchain and set the bits of the back buffer that is about to be displayed. Or, I want to allocate 4-8 RenderTargets, and on each frame, copy the bits from system memory to the RenderTarget, then set it as the next thing to display. I've never seen or heard about anybody doing this, but it seems so dead simple!


texts: isometric background that covers the viewport

texts:
The technique I use now is a loop with an innerloop that draws images on a canvas element, but it looks like a rotated square.

This is a nice example that covers the whole viewport.

I have read something vague about clickthrough maps? What kind of techniques are there that are most efficient with mobile devices and javascript?

Edit

I other words, howto create a grid, in HTML5 that looks like the picture above, where you can place elements on. ( in the picture, it is the garden ) If it's not isometric, what is it and can it be created in html5. What I use now, creates a repititive background.

function draw() {

    c.clearRect(0, 0, canvas.width, canvas.height);

    for (var row = 0; row < 10; row++) {
        for (var col = 0; col < 10; col++) {

            var tilePositionX = (row - col) * tile.height;

            // Center the grid horizontally
            tilePositionX += (canvas.width / 2) - (tile.width / 2);

            var tilePositionY = (row + col) * (tile.height / 2);

            if (tileMap[row] != null && tileMap[row][col] != null) {
                tilePositionY -= tileMap[row][col].height - tile.height;
                tilePositionX -= (tileMap[row][col].width / 2) - (tile.width / 2);

                if (!(tileMap[row][col] instanceof BuildingPortion)) {
                    c.drawImage(tileMap[row][col].texture, Math.round(tilePositionX), Math.round(tilePositionY), tileMap[row][col].width, tileMap[row][col].height);
                }
            } else {
                c.drawImage(tile, Math.round(tilePositionX), Math.round(tilePositionY), tile.width, tile.height);
            }
        }
    }
}
}

thanks


texts: How can I apply an outline effect in Unity?

texts:
I want to apply an outline effect for several objects on the scene. Nope, the standard outline shader from the toon-shader package don't met my criteria.
I want to create an effect like this:

To implement this effect I want to:

1) Render all my selected objects into a texture, taking the depth into attention. So if my selected object is occluded by another objects it must be displayed in my render texture, like this:

2) Render the scene.

3) Blur my render texture and then copy all non-null (null is empty scene) and non-one (1 is the object itself) to the screen to make it look like this:

So, I have the question: How can I render the separate objects to the texture, taking care about occluders (depth)? Yep, I know about Graphics.SetRenderTarget Graphics.DrawMeshNow, but I also need to take care about the depth, because without it, it will look like this:

Please help, I feel stuck.


texts:
I'm starting to develop an Android game. I've already installed jBox2D but I can't find complete code to develop a simple application from scratch using this framework.
Thanks in advance!


texts: Unity UI Mask is not working in samsung SM-G610f

texts:
I am using unity 2018.3.13f1 and getting the issue that unity ui mask is not working in a specific device like Samsung SM-G610f.
The masking work in other android devices. But(Samsung SM-G610f) the mask became rectangle.
Below is the reference image link.
https://drive.google.com/file/d/1aTvKIxFh0HhNXgTYg5FOqvTsCy0aqr4e/view?usp=sharing
Please help.
Thanks.


texts:
So I've been trying to get started with game development for Android using Unity3D. For my first project I've made a simple cube that you can spin using touch. For that I have the following code:

using UnityEngine;
using System.Collections;

public class TouchScript : MonoBehaviour {

float speed = 0.4f;
bool canRotate = false;
Transform cachedTransform;

public bool CanRotate {
    get { return canRotate; }
    private set { canRotate = value; }
}

void Start () {
    // Make reference to transform
    cachedTransform = transform;
}

// Update is called once per frame
void Update () {
    if (Input.touchCount > 0) {
        Touch touch = Input.GetTouch (0);

        // Switch through touch events
        switch (Input.GetTouch (0).phase) {
        case TouchPhase.Began:
            if (VerifyTouch (touch))
                CanRotate = true;
            break;
        case TouchPhase.Moved:
            if (CanRotate)
                RotateObject (touch);
            break;
        case TouchPhase.Ended:
            CanRotate = false;
            break;
        }
    }
}

bool VerifyTouch (Touch touch) {
    Ray ray = Camera.main.ScreenPointToRay (touch.position);
    RaycastHit hit;

    // Check if there is a collider attached already, otherwise add one on the fly
    if (collider == null) gameObject.AddComponent (typeof(BoxCollider));

    if (Physics.Raycast (ray, out hit)) {
        if (hit.collider.gameObject == this.gameObject)
            return true;
    }
    return false;
}

void RotateObject (Touch touch) {
    cachedTransform.Rotate (new Vector3 (touch.deltaPosition.y, -touch.deltaPosition.x, 0) * speed, Space.World);
}

}

The above code works fine. However, I'm wondering how I can keep the cube spinning after the user lifts his finger. The user should be able to "fling" the cube, which would keep spinning and after a while would slowly come to a stop due to drag.

Should I do this using AddForce or something? I'm really new to this stuff so I'd like it if you guys could point me in the right direction here :) .


texts: Should I use an abstract class or function pointer to implement component notifications?

texts:
I want to create a component-based game engine with subsystems which do the work, entities which are simply a list of components (plus position and rotation, because every object will have that), and data.

In addition I want the subsystem to create the components for the entity (the entity has a list of component types and the subsystem creates them). The subsystem has to be notified if an entity is added to the world. I think the best way is the observer pattern: my scene manager notify every subsystem.

This is where I got stuck. When the scene manager notifies, should this be a function pointer or a abstract system class with handle message? In the first case, how can I get this work with a variable count of parameters?

This approach with an abstract class is not my favorite, I think function pointers may be better. Consider this case: my position component will be edited from the position system, so my system or my component have to notify the render system.

Given my above requirements, what should I do to deal with these notifications?


texts:
I'm a bit confused on how to implement an allocator for my game engine. I'm currently trying to implement PhysX for the physics in my game and it requires an implementation of an abstract allocator class that they defined. I've only heard of allocators spoken about in a general and abstract way so I'm not sure about how they are precisely implemented.

Now what I'm not so certain is that should a game engine contain multiple different allocators for different aspects of the engine i.e a separate allocator for shaders, textures, physics engine, meshes, etc... and if so, how do you know what asset requires an allocator class for it?

Or do you have one allocator class that allocates memory for any type of object? and if so, how do you know how much memory you'd need for the runtime of your program?

In this gamasutra post: https://gamasutra.com/blogs/MichaelKissner/20151104/258271/Writing_a_Game_Engine_from_Scratch__Part_2_Memory.php

He chooses an arbitrary value of 64 objects to allocate memory for. If you have different types of objects, surely 1 type of object will take more memory than another type so why the arbitrary 64? I'm sure he was using 64 just as a replacement for N. But how do we define N here?


texts: LibGDX Textfield has no pointer cursor or blinking on hover / focus

texts:
stage = new Stage(new FitViewport(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()));
    Gdx.input.setInputProcessor(stage);
    TextField.TextFieldStyle style = new TextField.TextFieldStyle();
    style.font = font;
    style.fontColor = Color.BLACK;
    style.cursor =
    style.selection = new Image(new Texture("core/assets/skin/textfield-big.png")).getDrawable();
    style.background = new Image(new Texture("core/assets/skin/textfield-big.png")).getDrawable();
    text = new TextField("Name", style);
    text.setWidth(500);
    text.setHeight(37);
    text.setPosition(50, 50);
    stage.addActor(text);

When I draw my stage, I can see my textfield, but when I hover it, my cursor doesn't change, and when I focus I can't see that blinking " | " at all, like normal textfields have.

What did I do wrong? Is it because style.cursor is null? If yes, how can I set it to the default cursor that libgdx uses?


texts: Validate single player game packet on a server

texts:
I am building a game in Unity and store data on a .NET server.  I was wonder what the best approach to validating the game data before posting the scores to the .NET server.

The game is somewhat deterministic and I know I have to simulate the game on the server to some extent to properly validate the game.  This simulated game would have to run extremely quick as well.

This is where I am having trouble.  In unity I have various colliders that are used to determine things like range and when to take damage and I have no idea how to "simulate" this in a .NET enviroment.  I was wondering if there are any resources out there or tutorials out there.  I have tried to find one but I don't think I am using the right keywords.

I am guessing this would be similar to how games like Clash of Clans validates their attacks.


texts: low FPS when battery is low ( unity android )

texts:
i make a simple 2d scene in unity 2017.3.1f1 (only 5 sprite renderer).
I realized that when my Android device's battery is under 20 %, the frame rate will be 60 to 30.
I did all the optimizations I heard, like:

DynamicBatching, Sprite Atlas , Quality Setting , sprite Texture Comprestion Override for Android And
I emphasize that my scene contains only 5 sprite (one background and several buttons)

i use Application.targetFrameRate = 60; because if don't , all time The motions are stuttering Whether the battery is over 20% or not.

And when the vsync is off, the frame is locked to 30 and when it's turned on, it changes for about half a second between 30 and 60

according to profiler (on my android device) Gfx.WaitForPresent start growing!!!
(if you want to say it is GPU bound , i think render time don't grow And scence is very simple)

In all these modes, The motions are stuttering.

I tested two kinds of moves

1: Moving camera in the update method by the following code:

void Update () {
    if(startMvCm){
        if (cam.position.y > EndCm ) {
            cam.Translate(0f,(speedCm*Time.fixedDeltaTime),0);
        } else {
            cam.position = new Vector2(0,EndCm);
            startMvCm = false;
        }
    }
}

2: An animation of moving an image in canvas (simple UI menu with 5 button) using Animator.

And this low FPS see more in low Battery on my Huawei Mate 10 Lite


texts: Using Unity's `transform.translate()` to translate relative to an object but only using two axis

texts:
I'm using transform.translate() to move an object around the world space, relative to the camera that is following it. The camera has an angle of 23 degrees on the X axis.

The problem is that when I move forward the object tries to go into the ground and when going backward the object starts jumping because of the angle of the camera. What I want to do is freeze the Y axis of the object However if I did this the object would no longer be able to jump.

The other solution to this would be to write a method which rests the object to the ground when not jumping but them if the object was jumping and going backwards it would go flying backwards again.

How do I solve this issue?


texts: What methods do game hacks use to counter anti hack systems?

texts:
In popular multiplayer first person shooter games, there are often hacks such as Aimbot, Noclip, Speed, and other similar hacks which I know game developers deploy anti hack features to combat, but, wanting to know why some of these hacks are able to get past these systems, I looked up a hack for the game I'm currently playing and they claim to deploy "counter measures" against the anti hack systems.

My question is, when everything happening is being seen by the game server, how can hacks avoid the anti-hack system? Movement that's too fast for example seems impossible to hide. Moving through walls also seems impossible to hide. Finally aimbot is a difficult one, maybe there's no very good solution to detecting it, if the hack developer, for example, purposely makes it imperfect.

My question to game developers is: How can anti hack systems fundamentally detect speed, noclip, and aimbot hacks, and how can hack developers fundamentally deploy counter measures against systems to detect those three types of hacks?


texts: There's been many times where I've seen people use this tile grid. It's the one with the base pink background with deep purple bands around each section. Is this available online or will I have to make it myself?


texts: Adding an extra Pass to the Unity Standard Shader

texts:
I'm experimenting with adding some procedural textures to the unity standard shader. I'd like to add an extra pass (with vert and frag functions), but am unsure about where in the sequence this should go, and how to properly integrate it with the other passes (I want to keep all the standard shader lighting features etc.).

To keep things simple, I'd like to start with adding an extra pass which simply paints the mesh one color. Where should this go (in Standard.shader)?

Note : I've tried adding a pass between passes #1 ("FORWARD"), and #2 ("FORWARD_DELTA"). This works, and casts shadows, but does not recieve shadows.

Thank you!


texts: AI does not stop walking like it is supposed to, instead spins in place and lags game

texts:
I've got this very simple enemy AI that follows the player and is supposed to stop and shoot at the player when he enters a trigger, however it doesn't seem to do that it doesn't stop or shoot. This is one of my first scripts so it isn't really good. Any and all help will be appreciated.

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

public class EnemyAI : MonoBehaviour

{
    public GameObject Destination;
    NavMeshAgent agent;
    public Collider TriggerCollider;
    public GameObject Enemy;
    public GameObject bullet;
    public float EjectionForce;
    public float firingrate = 20f;
    private float NextFire = 0f;
    public GameObject GunArea;

    // Start is called before the first frame update
    void Start()
    {
        agent = GetComponent<NavMeshAgent>();
        agent.SetDestination(Destination.transform.position);

    }

    // Update is called once per frame
    void Update()
    {

    }
    void OnTriggerStay(Collider other)
    {
        if (other.transform.tag == "Player" && Time.time >= NextFire)
        {
            agent.isStopped = true;
            AimAndShoot();
            NextFire = Time.time + 1f / firingrate;
        }
        else agent.isStopped = false;
        agent.SetDestination(Destination.transform.position);
    }
    void AimAndShoot()
    {
        Enemy.transform.LookAt(Destination.transform.position);
        GameObject enemybullet = Instantiate(bullet, GunArea.transform.position, GunArea.transform.rotation) as GameObject;
        enemybullet.GetComponent<Rigidbody>().AddForce(enemybullet.transform.forward * EjectionForce);
        Destroy(enemybullet, 1f);
    }
}


texts: How i can play movie in unity by script(android platform)?

texts:
my script is correct in pc platform but when i switch on android platform i have compiler error cs0246, why i can not export my apk file.
how i can play movie in unity android platform by other way?

     public class NewBehaviourScript : MonoBehaviour {
     public MovieTexture myMovie;

     void Start()
     {
         myMovie.Play();
     }

     void OnGUI()
     {
         GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), myMovie);
     }
 }


texts:
I'm making a game for Android using Android Studio with Libgdx in Java.
In my game there are main object like Screen, ObjectFactory, SoundPlayer, Painter (Responsible for drawing) and a few more. 'til now I passed them to each GameObject that uses them but then I realized I could just make them static and every GameObject who needs them will just call them statically.
I wonder if I make these main objects static, would it hurt the performance? Because it seems like such a comfortable solution...
Thanks in advance.


texts: Why are my cached (in an array) gameobjects disappearing?

texts:
First, some context: I am developing a chunk loading system for unity. I load all the chunks as prefabs from disk to an array as a cache. When I need to load a chunk, I instantiate it from the cache into the world.
The problem is that when deleting gameobjects from the world (using the destroy method) to unload them, it also destroys the cached copy meaning that I can't instantiate it back later.
I've done some of my own research and I have found that some time after I initially cached the gameobjects and instantiated them into the scene for the first time, the hash codes of both the cached and world gameobjects change to become the same thing. This occurs while the editor isn't playing and no other scripts are running.

Here is some code:

 void ImportChunks ()
{
    //Reset All Chunks
    //prefabs = new List<GameObject>();
    prefabs.Clear ();

    prefSorted = new List<List<List<GameObject>>> ();

    //Fill the list
    prefSorted = Enumerable.Range (0, Layers).Select (l =>
        Enumerable.Range (0, GridXSize).Select (h =>
            Enumerable.Range (0, GridYSize).Select (w =>
                new GameObject ()).ToList ()).ToList ()).ToList ();

    Debug.Log (prefSorted.Count + " layers");
    Debug.Log (prefSorted [0].Count + " x");
    Debug.Log (prefSorted [0] [0].Count + " y");

    //Load Chunks From Disk
    string[] pref = AssetDatabase.FindAssets ("@", new string[]{ PrefabDir });
    int d = 0;
    foreach (string prefa in pref)
    {
        //Load chunk from disk
        GameObject n = ((GameObject)AssetDatabase.LoadAssetAtPath (AssetDatabase.GUIDToAssetPath (prefa), typeof(GameObject)));

        //Put it into the cache array
        int[] pos = GetPos (n.name);
        prefSorted [pos [0]] [pos [1]] [pos [2]] = n;

        d++;
    }

    //Add all of our children to the loaded array
    HashSet<GameObject> children = new HashSet<GameObject> ();

    for (int i = 0; i < this.transform.childCount; i++)
    {
        children.Add (this.transform.GetChild (i).gameObject);
    }

    loaded = children;
}

public GameObject LoadChunk (int l, int x, int y)
{
    //We have an array containing a reference to all the currently loaded chunks.
    //Here we find the chunk which is already at the coordinates where we want to load the new chunk.
    //BTW naming convention is x-y@l-lv
    GameObject old = loaded.FirstOrDefault (i => i.name.Split ("@" [0]) [0] == x + "-" + y);
    if (old != null)
    {
        if (old.name.Split ("@" [0]) [1].Split ("-" [0]) [0] == l.ToString ())
            return null;

        //Destroy the object and remove it from the array of REFERENCED objects
        Destroy (old);
        loaded.Remove (old);
    }

    //Make the new chunk
    //prefSorted is a cache of all chunks so they can be instantiated
    GameObject newChunk = Instantiate (prefSorted [l] [x] [y]);

    newChunk.transform.SetParent (this.transform);
    loaded.Add (newChunk);
    newChunk.transform.localPosition = new Vector3 (x * GridScale.x, 0, y * GridScale.y);

    return newChunk;
}

Thanks for everybody's help in advance. If you have any questions, leave a comment and I'll update the post.
Thanks,
       -Thomas


texts: Dynamic Sort order For walking in front and behind stuff

texts:
I'm using tile maps, and I'm having a difficult time with the concept of walking both in front of things, and behind things and having the layers sort order show properly. Take the image below, I need it to behave like #1 AND #2, so that if you walk behind it, you get that nice layering. However, I also need it to act like #2 when infront of it without looking like #3. Is there some sort of way to make the top of the barrels sort order change depending on if the player is in front of it, or behind it?
I was looking at rule tiles, but that's something else, unless there is some feature about it I do not know of.


texts: How can I encourage players to "talk to" to each other in team-based games?

texts:
With the goal of attracting a certain kind (highly sociable, that is) of players, I have wondered what game mechanics require, or at least encourage, players to verbally (I'm assuming an advanced text chat system, with team and private channels, maybe even chat-bots) communicate with each other, if they want to succeed as a team, or at least get the best possible results, within a game.

I'm interested in anything that requires discussion; before, during or after a "match".

If it matters, it would be (mostly) a team-vs-environment game, but also allow some tasks to be achieved by players alone (team is offline), or the occasional PvP/GvG (I'm bored with the grunts).

Getting team players to talk (rather than argue!) to each other increases their "closeness", and so plays an important role as a long-term "retention mechanism".


texts: Monogames Most efficient way of checking intersections between multiple objects

texts:
I've created a top-down shooter with multiple objects such as enemy AI (tanks), walls, power-ups etc.

At first I was able to create about 300 AI units which aims to move the player character, checks for collision and shoot a bullet. This bullet also checks for collision on each frame until it encounters an intersection to be destroyed.

I wasn't long after I encountered massive performance issues. I immediately identified that the main performance drop was caused by the collision detection.

Each object's bounds is represented by a rectangle. If this rectangle intersects with any other rectangle the collision event is raised.

I'm currently unsuccessful in deciding what to do to reduce performance, but still maintain all the characters' capabilities. I want to check if the player or AI will collide with any object before it moves to the given location. I also want to check when the bullet collides with any other object.

I'm currently flagging all my objects by using different interfaces. I then created a Dictionary>> (GroupedObjects) Dictionary that filters the objects into different flags where the first type represents the interfaces the object inherited and the second type identifies the object's type. For e.g. I check only the Hostile tanks of type AITank for collision with the bullet. GroupObjects[Hostile][AITank].

I've read that I need to create trees where collision is only checked with all the objects in the current tree.

After a few benchmarks I identified that checking collision between 1 million rectangles uses 38ms on the CPU and checking the distance from a fixed point to 1 million other points take 136ms.

QUESTION

With the benchmarks above in mind, how would I group objects by their range (for e.g. within the screen size) if calculating the distance takes more processing than checking the intersection with a rectangle representing the screen?
What will be the most efficient way to check for collision between objects, meaning the player checks for collision AND the AI tank checks for collision since both of them can't move through the walls? Keep in mind that the AI isn't static and moves on each frame. Also, object A checks for collision between itself and object B and object B checks for collision between itself and object A.
I created an object called CollisionMap that contains points, that represent collision, generated by an image with a specified colour as collision. These points need to be updated every time an object moves and an other object needs to check for collision with this object's CollisionMap (that can contain hundreds of points). I've created this CollisionMap to represent shapes that isn't rectangular or circular so that colliding object will treat each intersection according the shape of the shape. Does this sound possible to process if you have hundreds of objects with hundreds of points representing collision?

I'm new to game dev and I have no idea on what's the most efficient way to check for collision between multiple objects. And for all the algorithms (AABB, Rays) I've seen: it's only for one object or it's still too inefficient...

P.S. I know I typed allot, but I'm trying to explain my problem so that I don't get referenced back to sources I already examined and show what I've tried.

Thanks in advance!


texts: How can I debug my game on mobile device?

texts:
I've been creating this game on my computer for months and everything works fine. But when I built the project and installed it into my android device, it doesn't run as smoothly. I don't wanna use the word "lag" as I don't think that's the correct term in this case. To be more specific, my game involves as series of platforms moving continuously from one end of the screen to another. When I play it on my mobile device, the platforms look a bit "shaky", as if the speed of the platform isn't exactly constant.

It's possible that this is happening due to my computer having a more powerful processor than my phone and hence, the performance isn't on par. But I don't see why that should be the case given that my scene isn't very complex. I've released an earlier version of this game on android before with roughly the same number of objects in my scene. It ran as smoothly on my phone as on my computer. Hence, I was expecting this version to be just as smooth.

To find out the problem, I made my game less complex by removing more objects from my scene and running it on my phone. But the performance was no different. The platforms still look quite "shaky" and their movement don't feel very smooth.

How can I isolate the cause of this behaviour?


texts:
guys, I got a question on how to use multiple shaders in my app. The app is simple: I have a 3D scene, say, simple game and I want to show some 2D GUI in the scene. I was following this tutorial on how to add font rendering to my scene. One difference is that I am using Java and lwjgl, but everything is implemented as in the tutorial.

So I have 2 sets of shaders (2 programs). 1st that handles the 3D models and scene at all. I added the second set of shaders, I just copied them from the tutorial. Here are they:

vertex:

#version 330
in vec2 position;
in vec2 texcoord;
out vec2 TexCoords;
uniform mat4 projection;

void main() {
    gl_Position = projection * vec4(position, 0.0, 1.0);
    TexCoords = texcoord;
}

and fragment:

#version 330
in vec2 TexCoords;
out vec4 color;

uniform sampler2D text;
uniform vec3 textColor;

void main() {
    vec4 sampled = vec4(1.0, 1.0, 1.0, texture(text, TexCoords).r);
    color = vec4(textColor, 1.0) * sampled;
}

I compile shaders, link them into a separate programs. (so I have modelProgram and fontProgram). However, when I run my application, I see errors in the console (however, the application runs fine):

WARNING: Output of vertex shader 'TexCoords' not read by fragment shader
ERROR: Input of fragment shader 'vNormal' not written by vertex shader
ERROR: Input of fragment shader 'vTexCoord' not written by vertex shader
ERROR: Input of fragment shader 'vPosition' not written by vertex shader

As you can see TexCoords is an out variable in font.vs.glsl and the other 3 are in variables in model.fs.glsl. So they belong to the other set of shaders, other program.

My question is why this happen? It looks like the pipeline tries to combine one program with another, although the application runs smoothly.

The other problem I have is that I do not see any text rendered. I don't know whether this is caused by this or it happens because something else. Any help will be appreciated!

Thank you


texts: Why does the order matter in multiplication of matrixes?

texts:
I stumbled on this question because I had the same problem with my camera, and changing the multiplication order worked.

I ran into a similar problem when scaling a model. This code produced the wrong result:

// world is an existing Matrix
var scale = world * Matrix.CreateScale(3.2f);

whereas this worked perfectly (scaled a model to 3.2x it's size):

var scale = Matrix.CreateScale(3.2f) * world;

I don't understand why the order matters though - in "normal" math (that is, 5*3 vs 3*5), swapping the factors yields the same result. I understand differences if there are more than 2 factors (like in this question), but I don't see the issue here?

I don't know much about how Matrices really work and so I don't know if that's an XNA quirk or if it would happen in OpenGL as well?


texts:
I am developing a game like word search. I have used AndEngine for this and for displayig grid of words I have used TiledMap. In this game, we need to join letters to make a word as we drag our fingure it will draw line on tiles and make connection between letters. I am able to draw lines vertically and horizontally accurately but as I try to draw line diagonally it goes to the nearby tile and draw line from last touched tile to nearby tile. But as I carefully move to the diagonal tiles it draws line accurately.

Can any one help me to solve this issue?

e.g.
----------------
|1   2   3   4 |
|5   6   7   8 |
|9  10  11  12 |
----------------

as shown in above e.g.

I am able to draw line for "1234" & "159", It means all horizontal and vertical positions works accurately.
But for "963" its not as accurate as i draw for horizontal and vertical.

I want to draw line on one board as shown above. There will be letters below lines and need to connect correct words.


texts: How do I find the angle required to point to another object?

texts:
I am making an air combat game, where you can fly a ship in a 3D space. There is an opponent that flies around as well. When the opponent is not on screen, I want to display an arrow pointing in the direction the user should turn, as such:

The arrow will be on the HUD. It will not actually turn to the opponent. I want it to indicate which direction a user should turn to see the enemy ship. This arrow will circle around the cross-hairs (radius 60 pixels).

So, I took the camera location and the opponent location and did this:

double newDirection =
   atan2(activeCamera.location.y-ship_wrap.location.y,
   activeCamera.location.x-ship_wrap.location.x);

After which, I get the position on the circumferance of a circle which surrounds my crosshairs, like such:

trackingArrow.position = point((60*sin(angle)+240),60*cos(angle)+160);

It all works fine, except it's the wrong angle! I assume my calculation for the new direction is incorrect. Can anyone help?


texts: Algorithm for creating adjacent triangles

texts:
I have a system where you can click once to place a node in a scene. When you place 3 nodes, it forms a triangle. When you place any future nodes, it creates a new triangle by joining that node to the 2 nearest existing nodes.

This works fine most of the time but is flawed when used near triangles with very acute angles, because one of the 2 nearest nodes is often not one that should be used.

For example, see the image below. The magenta triangle is the first one placed. If I then click at the position marked X, what I get is a new triangle where the blue overlay is. What I want is a new triangle where the green overlay is. (ie. symmetrical to the magenta one, in this example. Clarification: The green and magenta triangles don't overlap - the green one extends under the blue one to the left-most node)

How can I determine which 2 existing vertices to use when creating new triangles so that triangles are not superimposed like this?

EDIT: Searching for the nearest edge gives better results, but not perfect ones. Consider this situation:

The 'nearest edge' test is ambiguous, and can return AB or AC (as the nearest point to X for both is at A). The desired result would be AC, to form the ACX triangle with no edges overlapping. How could I ensure this result? (I'd rather not have to perform individual edge overlap tests as a tie-breaker if possible as I'm concerned that the nearest edge test won't necessarily spot the 2 are exactly equidistant, given floating point precision issues.)


texts: Unity - Material changes to "material (instance)" on Start

texts:
Not sure why my materials started doing this, byt when I press play, all materials on my models change to "materialsName (instance)".

I use the same material for several objects, and for some it adds (instance), and for some it does not.

Turns out that since I wanted to modify the material at runtime, it created an instance, which makes a lot of sense. So then my questions is, what are the downsides of this? does it effect performance?

I only have 1 material for my entire game, so I batch probably 95% of my draw calls, will this effect that?


texts: Adding a delay into the middle of a function in Unity

texts:
In the spot //wait 1.5 seconds what would I say to make it wait 1.5 seconds then complete the code after?
Here is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class OnclickHeal : MonoBehaviour
{
    public PlayerHealth playerHealth;
    public PlayerMovement playerMovement;
    public Inventory Inventory;

    public Button healButton;

    void Start()
    {
        Button btn = healButton.GetComponent<Button>();
        btn.onClick.AddListener(TaskOnClick);
    }

    void TaskOnClick()
    {
        playerMovement.moveSpeed = 3;
        //wait 1.5 seconds
        playerMovement.moveSpeed = 4;
        playerHealth.currentHealth = 100;
    }
}

Also, the line public Button healButton; throws an error:

error CS0246: The type or namespace name 'Button' could not be found (are you missing a using directive or an assembly reference?)


texts: Calculate a random position inside a 2D area excluding a subset

texts:
Given this area

- - - -
- X X -
- X X -
- - - -

I have a GameObject size 4x4 and inside another GameObject size 2x2.

I know how to calculate a random position inside the 4x4 zone (using GameObject position and collider size), but I do not know calculate a random position evading the 2x2 zone.

What I am using right now is:

Calculate position inside 4x4.
If that position is inside 2x2 go back to step 1.

But it is not a good way to do this.
Do you know can I calculate a random position inside 4x4 area evading a 2x2 area?

I though generating small GameObjects, 1x1 instead if 4x4. So first select a random of the 4x4 tagged,  for examble, as "IsWalkable", and then calculate a random position insided the selected small square.


texts:
I want to create a very simple 2d multiplayer browsergame in html5. Something like Scalatron
I mainly want to do this to improve my scala skills, the problem is I would have to code the clientside code in javascript and the serverside code in scala. This would result in duplicated code.
Another option would be to ignore the html5 part and write it in opengl. But I would still prefer to have a html5 game.
I could do this is in javascript, but then it would destroy the whole purpose of learning scala.
Is there a way to use scala with html5?
Or what would you recommend me to do?


texts: Debug.DrawRay() does not draw rays in game view

texts:
Here is the relevant code:

protected override void Update()
{
    base.Update();

    Debug.DrawRay(this.transform.position, this.transform.forward * 100f, Color.red, duration: 2f);
}

When running the game, I can see the ray being drawn in Scene View.

However, in Game View, no ray is displayed.

As you can see from the screenshot below, I have already enabled gizmos in Game View.

What should I do to ensure that rays are being drawn in Game View when debugging?


texts: Default with SDL_RendererFlip Horizontal (SDL, C ++)

texts:
When I execute my sprite sheet animation and apply renderer_flip_horizontal, a line appears in the sprite.

Without the flip render, everything works fine.

Example image:

Note: The sprites are correctly aligned. The flip is by sprite (not to the full sheet).
I also use SDL_Renderer SetLogicalSize(256, 224), and the size of the window is 800 x 600.

Could you explain why this happens?

Thanks in advance.


texts: Scene graphs and spatial partitioning structures: What do you really need?

texts:
I've been fiddling with 2D games for awhile and I'm trying to go into 3D game development.
I thought I should get my basics right first.

From what I read scene graphs hold your game objects/entities and their relation to each other like 'a tire' would be the child of 'a vehicle'.
It's mainly used for frustum/occlusion culling and minimizing the collision checks between the objects.

Spatial partitioning structures on the other hand are used to divide a big game object (like the map) to smaller parts so that you can gain performance by only drawing the relevant polygons and again minimizing the collision checks to those polygons only. Also a spatial partitioning data structure can be used as a node in a scene graph.

But... I've been reading about both subjects and I've seen a lot of "scene graphs are useless" and "BSP performance gain is irrelevant with modern hardware" kind of articles.

Also some of the game engines I've checked like gameplay3d and jmonkeyengine are only using a scene graph (That also may be because they don't want to limit the developers).
Whereas games like Quake and Half-Life only use spatial partitioning.

I'm aware that the usage of these structures very much depend on the type of the game you're developing so for the sake of clarity let's assume the game is a FPS like Counter-Strike with some better outdoor environment capabilities (like a terrain).

The obvious question is which one is needed and why (considering the modern hardware capabilities).

Thank you.


texts: Well, I'm sort of a beginner to SDL, and I was wondering how one would go about deleting an image from the screen and replacing it with another? I attempted to do this, but it didn't seem to change it, how would someone with more experience than me go about doing it?


texts: Developing addons for xbox one controller

texts:
I want to develop an addon that plugs to the bottom of the controller for the xbox one. Can I legally make addons to the xbox one controllers without Microsoft's blessing?

If so, has anyone done anything like this? Cursory search looks like it has not been done.


texts: OnMouseOver() alternative for iPhone (Unity3D/Unity2D)

texts:
I am currently developing a game that uses the OnMouseOver() function of a MonoBehaviour object.

Is there a true alternative for iPhone? Would I be better of coding my own?

Thanks in advance


texts: Can you achieve a non-square look with tiles or a similar technique?

texts:
Just to explain the kind of look that is refered to in the question, it is apparent in the game Toejam and Earl 2.

Not asking how this was made but would like to know how you could efficiently blit a level design that isn't made or doesn't appear to look like easily identifiable square tiles. Another example for a "non-blocky" world would be worms but that looked more like a bitmap which sounds like it would require a lot of memory and could potentially limit the game world size.


texts: Last Row of the perspective projection matrix

texts: Could you explain to me what is the purpose of -1 in the last row of the gl_projection matrix? And how it affects the perspective division step ?


texts: Image splitting / tiling software for Mac

texts:
I have been programming for a bit and for 2D games and other applications I frequently make large images for the levels / the maps. Before I place these into the games I split the large images down into smaller equally sized squares, but I do this manually in 'the Gimp' and it takes ages sometimes! Is there some software which can do this much quicker for me, where I can select how I want  the image split down etc? And for Mac as well?

Thanks


texts: What does pressing CTRL do when editing a sprite sheet?

texts:
I have a multi-sprite sprite sheet.  When I have a blue box selected, and I hold CTRL, the box turns green.  I have played with it, but cannot figure out what it does.  I checked the documentation, but I don't see anything about turning the boxes green.

What does holding CTRL when editing a sprite within a multi-sprite sprite sheet do?


texts:
I'd like to introduce a way to turn off/on debug messages and in-game tooling (tweak menus, for example) without non-game related branches, e.g:

if(DEBUG_MODE) {
    // show tweak menu

    // some message
    console.log("In this function");
}

Is there a more reusable approach to this problem?


texts: How to programmatically disable sprite renderer and mesh renderer in Unity3D?

texts: In my game, I have an empty GameObject that has a sprite and a TextMesh as child. I want to access the child (sprite and the text mesh) and turn off the sprite renderer and mesh renderer of the sprite and the text mesh programmatically and be able to then turn it back on, but I don't know how. Some help and/or sample code would be much appreciated. Thanks.


texts: How can I set a property for the upper limit for another property's range

texts:
I have two properties, I would like to set one property as the upper limit of another property, hence making the upper rely on a property. As below:

public int fullLength;

[Range(0, fullLength)]
public int segmentLength;

Is there a way to do this, possibly with a custom editor? If yes, how can it be done?


texts: How Would I Design Realistic Fluid Handling?

texts: I'm making a game that is like a mix of many other games (Minecraft, Factorio, Don't Starve, Terraria, etc). I want to make pipes and fluid handling like it works in Factorio. I can't seem to find much information on it. I thought about making fluid even out across all connect pipes with less fluid than this pipe, but the order in which I processed pipes would matter a lot. So, how exactly does Factorio work? I also want pumps, if that changes anything.


texts:
In Godot v2, it seems that AnimatedSprite had a method set_frame() see here.
But in v3, this method does not seem to exist anymore. Only 3 methods are available see here:
bool is_playing ()

void play (String anim="", bool backwards=false )

void stop ()

What is the way to reset an animation in Godot 3?


texts: Unity 2D - scale sprite according to screen width

texts:
So I have a square sprite (width == height) and I want to scale it so that both width and height are exactly one fifth of the width screen. To find the desired pixel width I do:
float desiredWidthPixels = Screen.width * 0.2f;
float desiredHeightPixels = Screen.width * 0.2f;

How do I apply these values to the sprite?


texts:
I am trying to use an accessor, as it seems to me that that is the only way to accomplish what I want to do. Here is my code:

Game1.cs

public class GroundTexture
{
    private Texture2D dirt;
    public Texture2D Dirt
    {
        get
        {
            return dirt;
        }

        set
        {
            dirt = value;
        }
    }
}

public class Main : Game
{
    public static Texture2D texture = tile.Texture;
    GroundTexture groundTexture = new GroundTexture();
    public static Texture2D dirt;

    protected override void LoadContent()
    {
        Tile tile = (Tile)currentLevel.GetTile(20, 20);

        dirt = Content.Load<Texture2D>("Dirt");
        groundTexture.Dirt = dirt;

        Texture2D texture = tile.Texture;
    }

    protected override void Update(GameTime gameTime)
    {
        if (texture == groundTexture.Dirt)
        {
            player.TileCollision(groundBounds);
        }

        base.Update(gameTime);
    }

}

I removed irrelevant information from the LoadContent and Update functions.

On the following line:

if (texture == groundTexture.Dirt)

I am getting the error

Operator '==' cannot be applied to operands of type 'Microsoft.Xna.Framework.Graphics.Texture2D' and 'Game1.GroundTexture'

Am I using the accessor correctly? And why do I get this error? "Dirt" is Texture2D, so they should be comparable.

This using a few functions from a program called Realm Factory, which is a tile editor. The numbers "20, 20" are just a sample of the level I made below:

tile.Texture returns the sprite, which here is the content item Dirt.png


texts: Pause and Re-Enter Game Component Update (XNA)

texts:
I'm currently working on a (trading) card game in XNA and I'm having some trouble with returning results from a popup and immediately using them.

I'm able to make a popup screen (see this tutorial) and get a return value from the Yes/No selection while preventing further updates to the "battle" game component, but I'd like to do this while maintaining my location within one update cycle of the game component Update method as I want the popup in question to happen only once: namely when a particular card is played.

The ideal solution would be a way to pause the Update of one game component, continue updating the rest of the game to get my input data from the popup, and then return to the same spot in the paused game component's Update with my new input data.

Any ideas?

EDIT:
This method is an effect called from the game component Update method. As a similar effect could be called in the middle of a process (effect before/after an attack), preserving the location within the game component Update is important.

public void Cow(Card c)
    {
        bool temp = YesOrNo("Sacrifice Cow for 300 LP?");
        if (temp)
        {
            if (c.ownerP1) { lp1 = lp1 + 300; }
            else { lp2 = lp2 + 300; }

            Discard(c);
        }
    }

Also within the game component.

public bool YesOrNo(string message)
    {
        game.StartYesNoScreen(message);
        bool val = Convert.ToBoolean(game.yesNoScreen.result);
        return val;
    }

This is within the Game1 class itself. The Show method enables the activeScreen component and makes it visible.

public void StartYesNoScreen(string text)
    {
        activeScreen.Enabled = false;
        activeScreen = yesNoScreen;
        yesNoScreen.text = text;
        activeScreen.Show();
    }

The Game1 Update method.

protected override void Update(GameTime gameTime)
    {
        this.gameTime = gameTime;
        keyboardState = Keyboard.GetState();

        if (activeScreen == startScreen) { HandleStartScreen(); }
        else if (activeScreen == actionScreen) { HandleActionScreen(); }
        else if (activeScreen == quitScreen) { HandleQuitScreen(); }
        else if (activeScreen == yesNoScreen) { HandleYesNoScreen(); }

        base.Update(gameTime);
        oldKeyboardState = keyboardState;
    }

Another method in the Game1 class.

private void HandleYesNoScreen()
    {
        if (KeyPress(Keys.Enter))
        {
            if (quitScreen.SelectedIndex == 0)
            {
                activeScreen.Hide();
                activeScreen = actionScreen;
                activeScreen.Show();
                yesNoScreen.SelectedIndex = 0;
                yesNoScreen.result = 1;
            }
            else
            {
                activeScreen.Hide();
                activeScreen = actionScreen;
                activeScreen.Show();
                yesNoScreen.SelectedIndex = 0;
                yesNoScreen.result = 0;
            }
        }
    }


texts: Unity 5.. How to Block interaction below panel?

texts: New to Unity...Is there an easy way to block all interaction underneath a panel that I would have stationary at top of my game. There will be a pause button in that panel and some game info. Just don't want the mouse input or clicks to go through the panel and interacting with game below.


texts: Writing a Master's Thesis on evaluating visual scripting systems

texts:
I am thinking to write my Master's thesis around theorizing, and then implementing a PlayMaker or Kismet-like (building game logic by visually arranging FSMs) tool in Unity. The only thing I am still concerned about is the actual research question that I should pose.

I was kinda hoping that the more experienced game designers out there might know.

Update:
What about reducing the use of visual programming to graphically designing FSM-Action-Transition flows, which can then be attached to game entities (very much like http://playmaker.com does it)?

Update 2:
Regarding the evaluation of the approach: I was thinking that it would not be so practical to try to quantitatively prove that my tool is better than the competition. This is in fact not the essence of the thesis. The problem that I see myself trying to solve is more of the type of "how do we prove that the approach is easy to pickup and learn from people without specific programming knowledge"
I could build a "test sandbox" - an unfinished puzzle level that each of the test subjects is supposed to complete by following a number of certain tasks. The taks will vary from simply  adding a missing transition between two states, through correcting intentional mistakes in the logic, to designing entire state machines on one'e own. The evaluation will then be done based on the completion of the tasks.


texts:
EDIT: There aren't sufficient enough tutorials for what I'm trying to do in Python, so I'm going to take my time and slowly build up my skills in C++. It's hard to trip and not land in a book of C++ tutorials on game development and 3D programming.

Once I get passed the basic syntax for classes in multiple files with preprocessor declarations, what is the next step in 3D?

Do I use DirectX or OpenGL? If I use DirectX, are there sufficient enough books on the subject for a BEGINNER? Same question for OpenGL. I love programming books, I just feel that most of them are way below par - they either have good general explanations and terrible source code, or vice versa.

Thanks for your time. I'll do my best to turn this into an active discussion on the matter.


texts: Presumably a development machine for sure, but would it contain any sort of editor (of any kind)? Or are there any editors in existence that work with the SDK that are commercially available?


texts: Performance problems with scrolling html5 canvas for large tile-based game

texts:
I try programming a splix.io clone as an electron app and do the visualization via the html5 canvas. The movement across the tiles should look fluent like the original, so I target 60 frames a second. The programm worked fine till I tried to replace the tiles created through fillRectangle() with svg images using drawImage(). This resulted in a huge performance drop, which I now try to fix. To mention here is that, like splix.io, I have a quite large playfield with a targeted size of 500x500 tiles and a fullscreen viewport, so basically the canvas has to draw the whole screen each frame.

Known performance improvements, that I implemented are:

Separating the logic calculations and "rendering" into their own
windows, separated from the main process.
Only drawing the area visible to the player
Foreach tileType hold a offscreen canvas, so that I can copy the
ImageData to the onscreen canvas.
Draw tiles and the players on separate canvases.

A drawing loop with requestAnimationFrame() instead of setTimeout() seemed to be impractical because the ultimate goal is to let AIs, which will run in their own child-process, play against each other. Therefore I can't rely on requestAnimationFrame which throttles performance when the window loses focus or is minimzed.

What further performance improvements can you recommend? Is the scale of my game maybe too large for the canvas and would a switch to OpenFL / WebGL may be the better solution?


texts:
I only superficially understand the idea and I can't find any thorough explanation (partially because I can't find very good keywords to Google - English is not my first language):

Although I partially understand some things (next paragraph), my question is what data structure would you use to store a body's position and rotation and how does everything come together? I want to be able to translate that object to a (x, y) position, rotate it about the origin or about its centre (then fetch these things and draw a sprite using that position and rotation). Very similar to Unity's Transform object.

From my understanding I will need (at least) a 2/3-dimensional vector and a quaternion and then I should be able to generate a model matrix from them. How? Multiply what to what and in what order? I certainly have no idea how to get a 4 x 4 matrix from a 2/3-dimensional vector and a quaternion. Then if I change the position, I should probably update the model matrix again.

I'm using OpenGL ES 2 on Android, but I wouldn't mind an agnostic answer.


texts: Creating unfilled circle shapes using Farseer

texts: I have a project idea that I need to create a sphere and use it's interior for collision detection. I can only find information in Farseer that creates a filled circle. Is there a way to do it with CircleShape or do I need to create the sphere using vertices? Or if anyone knows of another physics engine that can do this. Thanks


texts: Playtesting Own Game - How To Be Objective?

texts:
I am currently working on an iPhone game and am having trouble playtesting to find out which parts of the game are fun and which need to be reworked.  As I sit down to play the various iterations, my feeling towards the gameplay and mechanics shift as I work through the same parts of the game over and over... and over.  Some parts that I think are super fun might be tedious to someone new to the game and vice versa.  My goal would be to create a game that maintains good pacing, advancement and skill progression for someone who just picked up the game, but I'm not sure how to test for that.

I try to keep an objective mindset and  I do have one quality assurance technician (my wife), but she is playing the game almost as much as me and thus loses that "newbie" mindset.  I don't have the resources to find and use third party testers (yet) and I would like to have my game be in a more completed state before I have even a closed beta test.

Does anybody have any tips or ideas on how to find out if my game really is fun or if it's just my mind playing tricks on me after the 1000th round?


texts: How do I get my iOS game to have custom background

texts: Sometimes when you go on the App Store to look at games, some have a custom background, instead of the default white. Does this cost extra money to do? Or do certain conditions for the game have to be met?


texts: DX 11 Specular Highlights in Deferred Renderer

texts:
I am currently implementing a deferred renderer in DX11.1.  Right now I am having a problem that I can't seem to crack with specular highlights when I have multiple light sources.

I keep a vector of lights for each scene and the last light rendered has proper spec, but all lights before it are "bad".  I think the problem is caused by an improper blend state setting, but I'm not sure.  Currently my blend state when rendering lights is

blendDesc.RenderTarget[0].SrcBlend       = D3D11_BLEND_ONE;
blendDesc.RenderTarget[0].DestBlend      = D3D11_BLEND_INV_SRC_ALPHA;
blendDesc.RenderTarget[0].SrcBlendAlpha  = D3D11_BLEND_ONE;
blendDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_DEST_ALPHA;

blendDesc.RenderTarget[0].BlendOp = blendDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;

blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;

In my G buffer generation I write specular to the G buffer's color map's alpha channel.
 In hlsl...

output.color.a = _specEm.Sample(linearClamp, input.texcoord).a;

Then in the light accumulator

float4 diffuse = _diffuse.Sample(pointClamp, input.texcoord);

// Lighting calculations for diffuse and normal, all good
// ...

float speci = diffuse.a;
float specularLight = speci * pow(saturate(dot(reflectionVector, directionToCamera)), specp);

return float4(diffuseLight.rgb, specularLight);

In this scene there are two lights, the first image shows the specular highlight created by the second light rendered

The second image is of the first light rendered in this scene where you can see the spec "badness" (a dim highlight with a darker spot in the middle), in it you can also see the position of the other light

Never mind the light on the boxes, they aren't fully interacting with light at the moment.

Its worth noting that more lights in the scene will have the same effect, all will have the "bad" spec and the last one will have the "good" spec.

I suspect that I am missing something fundamental about how blend states work and losing some of the color that I am writing into the alpha channel, but if anyone out there can see the problem and suggest a fix, I would appreciate it.


texts: How to make a more accurate lap time? get_timer() LIMITATION?

texts:
In the room there are 22 cars. All cars have a different speed.

The cars are numbered from 1 to 22 with the help of the variable carNumber.

CODE - obj_Car / Set car speed (Create Event):

velocity=10-((carNumber-1)*0.01);

Here's how there is a difference in car placement near the end of the lap:

However, even with this difference, the times of many cars are repeated:

The detection of lap time looks like this.

CODE - obj_Car / Time lap (Collision with obj_Finish) :

other.orderLapTime[car]=get_timer()-other.discount;

Discount = this is the exact time when the room starts (cars already start running).

CODE - obj_Finish / Set discount (Create Event):

discount=get_timer();

The display is made with a modifier (multi, to simulate actual track times).

CODE - obj_Finish / Draw time lap (Draw Event):

draw_text(1500,100+(20*(i)),string_format(orderLapTime[i]*obj_Seth.multi/1000000,1,3));

Even taking the multiplication and increasing the number of decimal places, there are still many repeated times:

Some inconsistencies including. Cars with slower speeds marking faster times.

I could slow down the base speed (10) to solve such a problem, but I already think in the long run. The races can't take so long. In addition I intend to give the player the option to set the speed with which the race takes place (a multiplier, more frames, etc).

It could also increase the difference between the speeds (0.01 to 0.05), but I would like a general resolution, so that I can notice through the lap time, if only by one thousandth (0.001).

EDIT 1 - Attempts made based on answers and comments from Bálint and TomTsagk:

That is what I tried to do.

CODE - obj_Car / lap time (Step Event):

unit+=velocity/60*0.001;

Below the results...

Respective code:

draw_text(1500,100+(20*(i)),string_format(orderLapTime[i],1,3));

Respective code:

draw_text(1500,100+(20*(i)),string_format(orderLapTime[i],1,5));

The speed difference between the cars is 0.01.


texts: Why rotating an object only on its local X axis result in sudden 180 degrees changes in Y and Z axis rotation values

texts:
I have an object (cube) in the scene and I want it to continuously rotate on its only local X axis but suddenly while rotating on X axis its Y and Z axis rotation value goes 180 degrees for some frames,  but it looks fine in the game view. Please help me to get out of this problem. It is also noted that this problem doesn't occur while rotating only on Y or Z axis.
Code:-

    void Update () {
         transform.Rotate(new Vector3(1,0,0),
         Space.Self);
    }


texts: Can I use quaternions and do a partial multiplication?

texts:
I have some code that rotates an object around an axis. It does this by creating a quaternion for a rotation and then multiplying by the old orientation:

nextRot = QuaternionRotationAxis( axis, rotSpeed * elapsed )
newOrient = QuaternionMul( oldOrient, nextRot )

This need to create the rotation quaternion each time seems like it may be redundant. Is it possible to somehow create a quaternion and somehow apply elapsed to it? That is I would prefer code like this:

nextRot = SomeOp( fullRotationQuat, elapsed )

In this way I can store fullRotationQuat in my object and simply apply it partially on each time step.

I know that if I apply nextRot twice, it would be like doulbing the ellapsed time. So I'm guessing I might want some kind of quaternion exponentation. Is this a define op? More importantly, is its performance still acceptable (or faster) than creating from an axis/angle each time?


texts: How to adapt my mobile game for different aspect ratios?

texts:
Before I start, I'd like to note that I work in the Unity Engine, but the basic theoretical stuff should be similar just about anywhere.

It's not really hard to get the game's camera/World view or UI to scale to many types of devices with different pixel counts as long as they have the same aspect ratio. But devices in general, and especially mobile phones, have all sorts of variables, aspect ratios can be anywhere from 16:9 to 20:9, and there are all sorts of different types of notches too. For this question I'm primarily going to ask about the aspect ratio and not touch on notches for now to stay on topic, but if you could explain how I can handle notches, that would be a good bonus.

So, how do I make a game for a mobile device, that can be played in portrait and horizontal mode, on anything from small 16:9 screens like the Samsung Galaxy S5, to larger 19:9 aspect ratio (A notch) in the Google Pixel 4?

Unfortunately due to IP restrictions, I can't show art, and I can't reveal the core mechanic of the game. but I have created a general mock up of what the ideal world/UI scaling would look like:

The UI needs to be able to scale to the edges of the display like any other game. But the edges of the world need to be the edges of the screen (There needs to be walls that appear at on all 4 edges of the screen), however because the game is physics based, the walls can't actually move else it would cause inconsistencies between in the game from device to device.

I know what I'm talking about here is primarily theoretical, but as someone who doesn't know much about aspect ratios (or notches), how can I ensure my game works consistently on this range of devices?


texts: How should game objects with fixed positions in the world be positioned?

texts:
I have some game objects that are always at the same position in my game world as they make up some of the scenery of my puzzle game. At the moment, their positions are sort of hard coded in and some of their positions are calculated relative to the hard coded positions of other objects at the time of game initialization. This has been hard to maintain because whenever I've decided to change the position of these scenery objects as the game design evolved, I have to go and rewrite parts of the code that place the created objects and calculate their positions in the world.

Is there a more maintainable way of handling the positioning of fixed game objects?


texts:
Lets say we have a laser beam emitter that has a position and an angle (in a 2D world to simplify things). The laser emitted from that emitter will start at that position, and continue heading in the direction of the angle until it intersects with an object (some arbitrary polygon). If that object is reflective, the laser should bounce off the surface that it first intersects. This continues until the laser hits a non-reflective surface.

I guess the problem here can be divided into two problems: finding the first intersection and calculating the new angle from that intersection. I'm not exactly sure how to solve the first problem, but I figure the second one can be solved by finding the angle between the laser and the normal vector (i think that's what it's called) and calculating the new angle using that.


texts:
I'm trying to do it so when I have an instantiated an item upon the game starting, it is random as to whether it actually instantiates or not. Here's the code I have so far:

public GameObject anyItem;
void Start()
{
    Instantiate(anyItem, new Vector3(0, 0, 0), Quaternion.identity);
    Instantiate(anyItem, new Vector3(11, 0, 0), Quaternion.identity);
}

How can I do it so these items (individually, not both together) are decided randomly as to whether they will actually be instantiated or not?


texts: Has anyone ever made a shader that produces something similar to pixel art?

texts:
I find that pixel art is really pleasing to look at; it has this kind of crisp, satisfying perfection to it.

I've been following some beginner pixel art tutorials, when I got an idea: what if someone made a shader (in GLSL for example) that took 3D scenes and did the best possible job at making it look like it was drawn by a pixel artist? The concepts of anti-aliasing and shading should be relatively easy to perform. Constraining your colour palette would be very simple as well.

Of course, no computer program could outdo the manual work of a great pixel artist, but has anyone ever tried this before?

Is this idea at all possible?
Are there any games that use it?
Have there been (documented) failed attempts?