texts:
I'm new to python and pygame and am trying to build a very simple "game" (it's more of a test for me to figure things out) in which you move a character around the screen and he can collide with walls and things. Everything is broken up into 32x32 tiles and the player is 32x64. This means that when his head hits a wall his feet are 2 tiles away and I've been trying to get it so that he's only 1 away, ie. I'm after a 32x32 hitbox starting at x=0, y=32 on the player image.

Do I need to create a separate rect to deal with this and if so how would I go about implementing it? Any help would be greatly appreciated.

Here's the code for my player class so far, hopefully it's not too messy:

class Player(pygame.sprite.Sprite):
'''The Main Player Class'''
def __init__(self, x, y):
    pygame.sprite.Sprite.__init__(self) #Call sprite initialiser
    self.image, self.rect = load_image("char.png")
    screen = pygame.display.get_surface()
    self.area = screen.get_rect()
    self.rect.x, self.rect.y = x, y
    self.x, self.y = x, y
    self.vx, self.vy = 0, 0
    self.movespeed = 2

def update(self):
    self._walk()

def _walk(self):
    if self.vx != 0:
        self._walk_single_axis(self.vx, 0)
    if self.vy != 0:
        self._walk_single_axis(0, self.vy)

def _walk_single_axis(self, vx, vy):
    "normalise for diagonal movement if necessary"
    if self.vx != 0 and self.vy !=0:
        norm = 1/(2**0.5)
    else:
        norm = 1
    "set new x and y positions"
    self.x += vx * self.movespeed * norm
    self.y += vy * self.movespeed * norm
    self.rect.x, self.rect.y = self.x, self.y

    "check for collisions with any walls"
    for wall in walls:
        if self.rect.colliderect(wall.rect):
            if vx > 0: #collide with the left side of the wall
                self.rect.right = wall.rect.left
                self.x = self.rect.x
            if vx < 0:
                self.rect.left = wall.rect.right
                self.x = self.rect.x
            if vy > 0:
                self.rect.bottom = wall.rect.top
                self.y = self.rect.y
            if vy < 0:
                self.rect.top = wall.rect.bottom
                self.y = self.rect.y

    "bound the player within the screen edges"
    if self.rect.x < self.area.left:
        self.rect.x = 0
    if self.rect.x > self.area.right-32:
        self.rect.x = self.area.right-32
    if self.rect.y < self.area.top:
        self.rect.y = 0
    if self.rect.y > self.area.bottom-64:
        self.rect.y = self.area.bottom-64

self.x and self.y are there because applying the movement directly to self.rect.x and self.rect.y caused the character to move at different speeds depending on which diagonal direction he was travelling in. self.vx and self.vy just return either +1 or -1 depending on the direction of travel.


texts: How to make a drawing action run in an left released event in Game Maker?

texts:
At first I tried to make the progress bar update using only one object that would command everything (obj_Control), linking to the global left released event a script containing the draw_rectangle function, but I got no results.

The Game Maker did not acknowledge any errors, but the progress bar did not update when I clicked on the created rectangles.

obj_Control (already without the draw_rectangle event):

Because of this I decided to create 3 new objects (obj_Vida, obj_Fome, obj_Energia), each containing a sprite and when each was clicked it would perform the action to update the progress bar:

obj_Vida:

scpt 1 => obj_Control.vida+=10; (applies to self)

scpt 2 => draw_healthbar(120,100,240,120,vida,c_black,c_red,c_green,0,true,true); (applies to obj_Control)

obj_Fome:

script 1 => obj_Control.fome+=10; (applies to self)

script 2 => draw_healthbar(120,150,240,170,fome,c_black,c_red,c_green,0,true,true); (applies to obj_Control)

obj_Energia:

script 1 => obj_Control.energia+=10; (applies to self)

script 2 => draw_healthbar(120,200,240,220,energia,c_black,c_red,c_green,0,true,true); (applies to obj_Control)

Room:

Room size => 360x640

Translate => vida/life, fome/hungry, energia/energy

What happens is that even dying of clicking on objects (obj_Vida, obj_Fome, obj_Energia) nothing happens to the progress bar. I discovered that it is because of the event, it would have to be a draw event. I added one below the left released event, but it did not work.

I apologize for any typing errors. I am not an English speaker and I had to translate everything. If something was not clear, please signal.

Thanks for everything.


texts: Using a web service for multiplayer games?

texts:
I've been looking into web services for making multiplayer games and was just wondering how feasible would it be?

What I would like to do is make a simple MMORPG that uses a turn based fighting system, are there any inherent limitations with web services which would make this difficult and not worth my time?

Also out of curiosity would a faster paced multiplayer game be workable using web services? Something like a top/down shooter similar in pace to games like asteroid?


texts: Google Play Services: Google ladder - How can I customize the share button?

texts:
To increase the feeling of competition among users of a small game that I developed, I implemented a google ladder such that players could measure against other players. To do this, I used the google play games plugin for unity, which works quite well.

To increase the visibility of the game, I would like to allow the user to share their scores on social platforms, or even via messages.
Looking at this picture:

Such a button exists, but only when looking at the social ladder (b) (ranking against your friends), and not overall (a). Additionally, the message is not very interesting (c).
My questions:

Is it possible to customize this ladder screen such as to add a button on the "All" page?
Would it be possible to add the share button on the top, rather than bottom?
Would it be possible to add a custom image featuring the game and the score to the share message, such that the message gets more attractive? Additionally posting the score as an image would mean the user can't change it before posting.

This question addresses some of the points I rise here, but not from withing google ladder.


texts: Is using isTouched or justTouched multiple times bad?

texts: Suppose you have justTouched or isTouched method multiple times in your game screen, is that bad? Is it better to create booleans and as few input listeners as possible? or it doesn't matter?


texts: How do I create a tile-based footprint trail?

texts:
Currently I am working on a quick game for some friends, but I don't know the proper name for this type of game, so here is an example of the mechanic in The Lion King II:

To unlock the exit, you need to cover the ground with paw prints and not get caught by enemies.

I am trying to recreate the footprint-path covering part but I don't know if this has a proper name/term or not and can't find any tutorials to get started.

Currently I have created several planes with the footprint texture going in either direction, and my plan is that when the player walks on it, depending on the direction, will make the appropriate texture appear, then something will check when the path is entirely covered, before setting the exit door to inactive.


texts: How to teleport a game object to an empty game object?

texts:
I am trying to make a respawn  system where if the player touches a plane, (the name of the object is tutlvl1_flrdead) they get teleported to an empty object at player spawn named "RESPAWN". But, several tutorials and unity answers threads lead me to nowhere since they were written from back in 2013 or somewhere around there.
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class deathfloor : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        public gameObject myObject; //You can name it whatever you want.
        myObject.transform.position = new Vector3(3.076, 1.74, -3.651);
    }
}

How can I fix this to do what I need for my game?


texts:
For my 2D Unity game, I've implemented A* pathfinding based on waypoints. System already handles building graph from waypoints on scene (which are manually placed objects), as well as finding and caching closest routes.

So, general idea is to select closest waypoint to character, closest waypoint to target position, and use pathfinding algorithm to find closest route (which is pre-cached already).

Yet, I've stumbled into issue - I don't know how to actually get closest waypoint. Well, there are several ways I think of, in the worst case I can just brute-force closest non-blocked waypoint from the collection, but that would be bad performance-wise.

So, are there any proper ways to get start or end points?


texts:
My problem is, whenever I start programming a clone of a game (for practice) or my own game or some other problem I stop somewhere in the middle of the development, because I lost interest in it.

How do you keep up the interest in developing a game, or developing in general?


texts: Managing left and right direction buttons being pressed at the same time

texts:
I am currently programming a Tetris clone. In Tetris, there is a system being used called DAS, or Delayed Auto Shift. It works similarly to the keyboard auto-repeat used in Windows. For example, if you press left, the block immediately jumps one Column to the left. Then a certain amount of time goes by till it jumps a second time, and the following jumps move at a constant rate. I have this implemented as moveHorizontal(boolean moveRight), and can call it with a boolean that determines the direction the movement is going in.

However my main problem is handling the left and right direction buttons at the same time. More specifically, the state where you hold down one button, while pressing another button. The more recently pressed button should overwrite the old one, and the DAS should be reset once it switches directions. I feel like I can't really get a grasp on how to implement this kind of logic.

How do I logically change the state so as to correctly respond to the user input as I have described?

I hope I explained the problem in enough detail. If I didn't, please let me know, so I can provide more information.


texts: Flash: Memory usage is low but framerate keeps dropping

texts: So I'm working on a puzzle game in flash. For all intents and purposes it's like Tetris. I spawn blocks, they move around the screen, then they get destroyed and disappear. I was having some trouble with the memory usage being too high over time so I read up on memory management and I think I have that figured out now. It's definitely climbing slower than it was before, but the framerate is still taking a huge dive after playing for a while. If it's not a memory leak what else could be causing this? Thanks in advance.


texts: Shader - Calculate depth relative to Object

texts:
I am trying to calculate depth relative to the object.Here is a good solution to retrieve depth relative to camera : Depth as distance to camera plane in GLSL

varying float distToCamera;

void main()
{
    vec4 cs_position = glModelViewMatrix * gl_Vertex;
    distToCamera = -cs_position.z;
    gl_Position = gl_ProjectionMatrix * cs_position;
}

With this example the depth is relative to the camera.But I would like get the depth relative to the object. I would like the same depth and value if I am near from the object or if I am far.

Here is an example of what I am trying to achieve. On the left you can see that the depth is relative to the camera. And on the right even if the camera moves back from the object, the depth remains the same because it is dependant to the object.


texts:
I am trying to use mod coder pack (MCP) to create mods of my own. I have downloaded MCP 9.4 version from www.modcoderpack.com. The error that I have encountered is that when I try to run a file called decompile.sh in the mac terminal, the terminal responds with an error: ERROR:root:!! Missing mcp.cfg. I have checked my MCP folder and made sure that it contained the file mcp.cfg. The file is in my folder.

I am currently running on a Macbook Pro with MacOS Mojave Version 10.14.4.


texts: Unity project not communicating with my iPhone 11?

texts:
Connecting to my iPhone 11 with a cool FaceTracking project called FaceCapOSCReceiverExample https://github.com/hizzlehoff/FaceCapOSCReceiverExample works excellent on my laptop, but not on my PC (Windows 10 and ubuntu dual boot. I am using Windows 10 for this project).
On my PC the only AntiVirus/firewall I have is Windows Defender. On the Inbound and Outbound rules, I deleted everything that had the word 'Unity' in it. I then added custom rules, allowing everything, for the program paths of Unity Hub and all Unity Editor installations.
But no luck. The program won't communicate with my iPhone.
I even tried turning the firewall completely off and re-launching Unity as admin. No luck.
I then manually installed the latest drivers for my network adapters (I have both "Killer E2400 Gigabit Ethernet Controller" and "Qualcomm QCA9377 802.11ac Wireless Adapter" in Device Manager).  No luck!
I also connected my PC to a personal hotspot from my iPhone. This was a tethered (purely USB) connection that I had running. But, while the tethered Internet worked great on my PC, it still didn't make the Unity project communicate with my iPhone! ;O;
I then added a rule to my firewall where I created a TCP port number 60001 and set it so private and public could connect. (I'm very newbie about ports) Then I entered that as the Port number within the Unity project. Still no connection was made...
I have no idea what to try from here! Like I said, it works great on my laptop, but my laptop is too dang laggy to use with it, so I would really love to get it running on my PC.


texts: How to detect graphics API at runtime with SDL2?

texts:
Using SDL2, is there a way to determine at runtime whether the application is using OpenGL, OpenGLES, or DirectX?

EDIT: If there is a way to figure it out without using the SDL2 API, I'm willing to throw that code into my project.


texts: How can I create a mesh with Blender which changes mid game?

texts: Take a situation where on the first half the player fights an enemy and after a cutscene, the player cuts off the hand of the enemy. How can I show him without his hand after this moment (when modeling it with the hands in Blender in a single skeletal mesh)? Do I have to make another skeletal mesh but without the hand? Similar to how in Assassin's Creed Origins where at the end of the snake quest after the cutscene Bayek losses his ring finger and remains without it all game. But in my case, the entire hand is removed.


texts: Unity Editor has the usual bunch of standard tools: translate, rotate, and scale. I want add custom tools (to e.g. "paint" metadata onto the ground, or drag-and-drop stuff between gizmos). How?


texts:
I have created a terrain using VertexPositionNormalTexture in XNA 4.0, but now I would like to allow the user changing the opacity of the terrain (from 0%, totally opaque, to 100%, totally transparent), so that user can see through it. Is there a simple way to do that?

I would also like to know how to do that if I use VertexPositionColor instead of VertexPositionNormalTexture (i.e., creating a colored terrain)

Thank you very much in advance.


texts:
I've added some text to a unity UI and set both the achor and pivot to the top right corner as shown here:

When I start this in debug in unity the text looks fine:

What's weird is that when I build the app and run it as an executable as a host (this is a multiplayer networked game) the text also looks fine. But when I start a client instance the text doesn't appear.

I debugged and paused the game in unity in client mode and noticed that the text object is miles away from where I'm expecting it to be (and as a result doesn't show on the camera).

You can just about see the black line on the below image which is my level and the text anchored miles up and right of the level.

It seems like I've done something stupid here but I can't work out what :s

EDIT: Leo's answer was correct conceptually, but here's how I implemented the suggestion.

Created an empty game object GameStateManager in the hierarchy
Add a GameState script to the manager with a network identity
Added my 'RemainingTime' property to the game state script and put the [SyncVar] attribute on it
Put logic in the game state Update method to update the remaining time
Added a ClientTimer script to the text object (mono behaviour), which retrieved the GameState from within the clients copy of the game state manager.
In the update method of the client time, get a reference to the Text object and set the .text property to the value of the remaining time.

I'm not sure if this is correct, but it does seem to work, and now the ClientTimer script isn't networked, which resolved the issues with placement of the text.


texts:
I tried to UV unwrap this octahedron, by slicing one of the sides.

I was able to lay it out on the texture like this, but with severe distortions.

Can someone help me UV map this without distortions?


texts: How do I implement group formations in a 3D RTS?

texts:
I managed to get pathfinding work for a single unit, and I managed to avoid agent-agent collision, but now I need to be able to send a group of agents to some location.

This is my set-up so far:

Waypoint pathfinding
The minimum distance between two nodes is a little bigger than the
biggest bounding sphere radius allowed for an agent.
Agents avoid collisions with other agents by doing some steering behaviour I based on clearpath

So now I need to send my agents somewhere in group. I have read some posts saying that some way to do it is to create a group leader and give the other units offsets to his position.

But then the problem is, what if the group formation cannot be achieved?
e.g. you want to form a rectangle, but at the target position there is a structure nearby which prevents you from creating a rectangle setup.


texts: glDrawElementsInstanced rendering always rendering the last instance at the origin

texts:
I'm in the process of adding instanced rendering to my engine, to do this I'm adding an offset attribute with a divisor of 1. But for whatever reason, OpenGL is consistently rendering 1 instance at the origin and missing the very last instance (or putting the last instance at the origin).

Say I have the offset buffer filled with {{1.0f, 1.0f, 1.0f},{2.0f, 2.0f, 2.0f},{3.0f, 3.0f, 3.0f}}, then I end up getting objects rendered at (1.0f, 1.0f, 1.0f), (2.0f, 2.0f, 2.0f) and (0.0f, 0.0f, 0.0f)... which is clearly wrong.

Vertex shader:

#version 330 core
in vec4 vPosition;
in vec3 offset;
uniform mat4 projview;
smooth out vec4 fColor;
void main()
{
    vec4 fPosition = projview * vec4(offset + vPosition.xyz, vPosition.w);
    fPosition.z = 0;
    gl_Position = fPosition;
    fColor = vec4(gl_InstanceID/3.0f, gl_InstanceID/3.0f, gl_InstanceID/3.0f, 1.0f);
}

Fragment shader:

#version 330 core
smooth in vec4 fColor;
out vec4 pColor;
void main()
{
    pColor = fColor;
}

I have triple checked that the buffers are loading all the data correctly (going as far as using glGetBufferSubData), and that seems to be fine, which tells me either OpenGL is broken (unlikely), or there's something wrong with this:

// vPosition
glEnableVertexAttribArray(0x0);
glVertexAttribPointer(0x0, 0x4, GL_FLOAT, GL_FALSE, 0x10, 0x0);
glVertexAttribDivisor(0x0, 0x0);

// offset
glEnableVertexAttribArray(0x1);
glVertexAttribPointer(0x1, 0x4, GL_FLOAT, GL_FALSE, 0xC, 0x0);
glVertexAttribDivisor(0x1, 0x1);

glDrawElementsInstanced(GL_LINES, 0x6, GL_UNSIGNED_INT, 0x0, 0x3);

I'm putting the following into the buffers (which again, I have triple checked):

vPosition buffer:

vector<glm::vec4> {
    {0.0f, 0.0f, 0.0f, 1.0f},
    {1.0f, 0.0f, 0.0f, 1.0f},
    {0.0f, 1.0f, 0.0f, 1.0f},
    {0.0f, 0.0f, 1.0f, 1.0f}
};

index buffer:

vector<GLuint> {0, 1, 0, 2, 0, 3};

offset buffer:

vector<glm::vec3> {
    {1.0f, 1.0f, 1.0f},
    {2.0f, 2.0f, 2.0f},
    {3.0f, 3.0f, 3.0f}
};

It ends up looking like this (note, black: gl_InstanceID = 0, white: gl_InstanceID = 2):

Gif of this happening with a different model:


texts:
I'm working on a Tile-Based game and I can't figure out how to make my tiles fall down smoothly like in candy crush. All column tiles fall-down at the same time. And spawn new like how many tile place if null.
What I want:

Update [25.12.2015]
But the my code works like this:

Update [26.12.2015]
Hello Again,
World Scale (x,y)
World Scale OLD: (10,10)
World Scale NEW: (10,11)
Y=11 Tiles type = Empty
Now, when i click the random place like (5,7),above all blocks down to :
block.transform.pozition += new Vector3(0,-1,0);
It's working. But again, when i click same place (5,7) not working...
I changed Y scale 10 to 11. Because, when i clicked tile, the tile will return to Y=11 position and fall down, how many tile place null.
When Tiles state "fallling down", the space between two blocks distance not more "0.01".
I do not know how to do. But I approached. I need to more improve this.
Thanks...
Pseudo-code:
When I click the (4,7) coord, the tiles,
tile(4,8) is smooth down the coord(4,7)
tile(4,9) is smooth down the coord(4,8)
tile(4,9) is generate new tile.

What I have (Code not working properly :( ):
World.Height = 10
World.Widht = 10
Tile X and Y {get, protected set}

public void ColumnDown(int x , int yStart)
{
    if (IsColumnFull(x)) return;

    for (int y = yStart; y < World.Height; y++)
    {
        //Yeni tile spawnla
        if (y + 1 >= World.Height) continue;

        Tile tile = World.GetTileAt(x, y);
        Tile tile2 = World.GetTileAt(x, y + 1);

        GameObject go_Tile = GameObject.Find("Tile-(" + x + "," + y + ")");
        GameObject go_Tile2 = GameObject.Find("Tile-(" + x + "," + (y + 1) + ")");

        if (tile != null)
        {
            if (go_Tile == null && go_Tile2 == null)
            {
                Debug.Log("go_Tile NULL");
                continue;
            }

            tile2 = tile;
            go_Tile2.transform.position += new Vector3(0, -1, 0);
            go_Tile.name = "Tile-(" + x + "," + (y + 1) + ")";
            go_Tile2.name = "Tile-(" + x + "," + (y) + ")";
        }
    }
}


texts: Static SFML 2.2 libraries and Code::Blocks on windows 7

texts:
I am starting to program games for the first time, but I've been doing general programming for a couple years now. I have Code::Blocks, which I am fairly comfortable with, but now I am struggling with trying to add a game library to my projects.

I decided on SFML 2.2 because it has all of the features I need. I am also planning on writing this in C++ if that affects anything. I read the instructions that SFML has on their site, but I still can't seem to get it to work. I am also under the impression that having the static version of SFML implemented will make the end result program be all one executable file rather than a file that accesses other files. If that is not what this means, please correct me.

I messed with the directories settings like their site mentioned, as well as the linker settings and the compiler settings. I keep getting errors that say something along the lines of...

"Undefined reference to 'sf:VideoMode::VideoMode(unsigned int, unsigned int, unsigned int)"

...along with many other undefined functions. Any help on implementing game libraries in general would be very helpful as well.

For reference, the tutorial I attempted to follow is at http://www.sfml-dev.org/tutorials/2.2/start-cb.php


texts:
i am creating a game with C++ and SDL2 game engine but i noticed this.
I used the Vsync option for rendering, so it'll render at 60fps.
If i use this game with another monitor, fps are different (for example 75).
I understood that this depends by the monitor frame rate.
My monitor is 60Hz and the other is up to 75Hz.
The problem is if i disable the Vsync option, Rendering will be accelerated.
Fps will increase up to 200 or will be unstable.

Sorry if my english is bad but for example this:
I want a block moving 5 pixels per frame.
If i have a slow pc the block will move slow.
If i have a fast pc the block will move fast.

So i searched for Frame Independent Movement and i pick up this:

movementPerSecond * (timeElapsedInMilliseconds / 1000.0)

I got this formula but i don't know what to use for "movementPerSecond" if i want the same velocity as before.
That block will not move 5 pixels per frame but some pixels per second.
Before, frames were 60 so the blocks was moving 60*5=300 pixels per second.
300 p/s should be this movement.
I disabled Vsync and i tried to do this:

while(1) {
    ...
    // updating coords
    x += 300.f * (timer.get() / 1000.f);
    timer.start();
    // rendering..
    ...
}

i was thinking that this was correct but velocity is faster than before.
In some frames, the block doesn't go.
i use timer.get() to get the time elapsed since i used timer.start();
i tried to print to the console these values and i got (1, 2, 0, 1, 1, 0, 2, 1).
So i think time in one frames is about 1ms.
I think however that if milliseconds are 0, movement variation will be 0.. (300*(0/1000) = 0).

I hope you understand what i'm telling.
What should i do?
Thanks


texts: Would it be too much overhead to keep a HashMap of variables on a server per object for the purpose of syncing object changes with the client?

texts:
I am currently writing a server for a multiplayer game. I am trying to find a good solution for synchronizing GameObjects across the server. The server sends each client a snapshot of every object in range over TCP once every 1/15th of a second and it sends minor updates over UDP every 1/30th of a second. I've come to the point in the code where after I've handled login and the basic information exchange I need to start synchronizing objects between the client and server. My original solution was to keep a boolean flag inside of each GameObject class to tell if it had been changed that update cycle or not and then send a serialized version of it across the server. However, the problem with that is that that sends the entire object even if only one variable was changed which wastes bandwidth not to mention the fact that I would need to serialize a representative class and not the actual one that may contain information that should only be server-side. A friend proposed the solution that I should write a class that contains a HashMap of variables that maps Strings to NetVars(a class containing the value and an index for referring to it). All variable changes would go through a get and set function so that we could tell if it had been modified. Each GameObject would keep one of these and when the server goes through its update cycle it would send the updates as a serialized list of NetVars that have been changed for each object to the clients who should receive them along with the object's id.

My question is would that be too much overhead? Would it slow down the server by having a NetVars class for each GameObject? and finally are there any better solutions than these and if so what?

Extra info:
Using Java with Kryonet for networking and the game is expected to have a fair number of entities in player view at any one moment.


texts: OpenGL ES, orthographic projection and viewport

texts:
I want to make some simple 2D game on iOS to familiarize myself with OpenGL ES.
I started with Ray Wenderlich’s tutorial (How To Create A Simple 2D iPhone Game with OpenGL ES 2.0 and GLKit). That tutorial is quite good, but I miss some parts of a puzzle.

Ray creates an orthographic projection using some magic numbers like 480 and 320. It is not clear to me why he took these numbers, and as far as I can see - sprites are not mapped to the iPad simulator screen one-to-one pixel. I tried to play with parameters with which the ortho matrix is created, but I cannot figure out the maths in here.

How can I calculate numbers (bottom, top, left, right, close, far) which will be parameters to the orthographic projection matrix creation and have the sprite on the screen shown in its original size?


texts: Removing walls of a tilemap at runtime in unity

texts:
I've been trying to implement some light procedural generation into my game, nothing fancy. Just spawning rooms down in different areas in order to add some replayability. I watched a few videos and the prevailing wisdom seems to be creating room prefabs and placing them at points in the world which I have done.

Its at this point I want to differ my implementation than those online, I would like to at runtime remove tiles at the North, South, East and west parts of the walls like so.

My main problem is trying to figure out where these points are in the tile map, I have tried creating empty game objects and adding them as children to the Tilemap and taking their positions and then using Tilemap.SetTile(child.transform.position,null) to remove the tiles, however the tile that ends up being set is always wrong and offset by a certain amount, I have tried to use Tilemap.bounds and Tilemap.localbounds to try calculate the width and height of the Tilemap in order to get the midpoint between 0-width and 0-height but the bounds of the Tilemap is actually way bigger than the space my tiles actually cover in the world, so that's also untenable. Using Tilemap.WorldToCell or Tilemap.LocalToCell also has not worked.
If this is impossible, or just way more complicated than its worth, are there other ways for me to draw rooms at runtime that dont involve me creating a big 2D of gameobjects with sprites and colliders because that'll just tank my performance.
Heres the Code I'm using to loop through all the children of my Grid and check if they contain the correct tag (North South East West) and then using that position to swap the tile
 void clearTiles(string dir){
    List<Transform> tiles = FindComponentInChildWithTag(this.gameObject,dir);
    foreach(Transform t in tiles){
        map.SetTile(new Vector3Int((int)t.position.x,(int)t.position.y,0),tile);
    }
}
    public static List<Transform> FindComponentInChildWithTag(GameObject parent, string tag){
       Transform t = parent.transform;
       List<Transform> children = new List<Transform>();
       foreach(Transform tr in t)
       {
              if(tr.tag == tag)
              {
                   Debug.Log(tr.name + " " + tr.localPosition + " " + tr.position);
                   children.Add(tr);
              }
       }
       Debug.Log("Children size " + children.Count);
       return children;
 }


texts: My character can jump even when its not grounded

texts:
Here is the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovementscript : MonoBehaviour
{
    //vars
    public CharacterController controller;

    public float speed = 12f;

    Vector3 velocity;

    public float gravity = -9.81f;

    public Transform groundCheck;
    public float groundDistanace = 0.4f;
    public LayerMask groundMask;
    public float jumpHeight = 3f;
    bool isGrounded;
    //-----------------------------------

    // Update is called once per frame
    void Update()
    {
        isGrounded = Physics.CheckSphere(groundCheck.position, groundDistanace, groundMask);

        if(isGrounded && velocity.y < 0)
        {
            velocity.y = -2f;
        }

        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");

        Vector3 move = transform.right * x + transform.forward * z;

        controller.Move(move * speed * Time.deltaTime);

        if(Input.GetButtonDown("Jump") && isGrounded)
        {
            velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
        }

        velocity.y += gravity * Time.deltaTime;

        controller.Move(velocity * Time.deltaTime);
    }
}

character controller and etc


texts: How can I change the Google Play Console language? Here you can see that the language is not English:


texts: Looking for a game engine to make a game like "Ikariam" or "Ogame"

texts:
I'm an IT student and currently in my spare time I want to start a project. I would like to make a game that resembles a browser games like "Ikariam" or "OGame". I don't want this game to be a browser game, but It has to work like the games above with a couple of players.
What game engine would you suggest?


texts:
I am developing a game in Python using Pygame. I am wondering whether there is a way to make changes to a currently running game by modifying the script (like Notch does in this clip).

For example, suppose I am doing a bit of testing and I want to increase my player jump height variable. I would like to simply go into the script while the game is running, change the value of the variable, and have the new value reflected in the current run. This would simplify the process of fine-tuning all my physics variables.

My IDE is Sublime Text (I know, it's actually just a glorified text editor, but you can run code from it).

Is there any way to do this? For example, with a particular IDE?


texts: How should I organize Lua scripts so that some entities do not have access to functions they shouldn't?

texts:
For my game in C++ I'm using different objects (like player, enemy, et cetera) which will have to be controlled by a Lua script. My problem is that if I were to write a function in my player script, all my other scripts will have access to it as well, and I don't want that.

I can think of three basic solutions:

For every iteration clear the entire state and re-register everything
Determine out what functions a script registers and remove them
Have every gameobject running it's own Lua state

Is there a good way to do this, keeping runtime performance in mind?


texts: Identify objects of the same type from each other, even between game restarts?

texts:
So I have a simple Character class:

class Character:

    def __init__(self, type, level, health, items=None):
        self._type = type
        self.level = level
        self.health = health
        self.items = items if items is not None else []

    def __getattr__(self, attr):
        return getattr(self._type, attr)

And a CharacterType:

class CharacterType:

    def __init__(self, name, max_level, max_health):
        self.name = name
        self.max_level = max_level
        self.max_health = health

    def new(self, *args, **kwargs):
        return Character(type=self, *args, **kwargs)

This allows me to easily spawn multiple instances of the same character type:

t_dragon = CharacterType('Dragon', 30, 2080)
t_mage = CharacterType('Mage', 100, 610)

dragon0 = t_dragon.new()
dragon1 = t_dragon.new(health=437)  # Damaged one
mage0 = t_mage.new(level=50)

But now I need to store these into a database table, and be able to somehow identify the character's type. I can't create a separate table for each type, since these types will be manageable by designers through JSON and thus new types can be added dynamically and old types be removed. So as it stands now, the above characters would populate the character table like so:

 id | level | health | type_identifier
----+-------+--------+-----------------
 0  | 0     | 2080   | ????
 1  | 0     | 437    | ????
 2  | 50    | 610    | ????

I would highly prefer if there's a solution which doesn't require the designers to have to come up with an unique ID themselves, so while something like this would work, where the designer comes up with an unique ID:

{
    "name": "Dragon",
    "max_level": 30,
    "max_health": 2080,
    "unique_id": "#dragon_2017-04-12"
}

and keeps it even if they change the character's name, it's very bothersome to have to maintain something like this in the JSON itself.

How can I get a string/integer/value to identify the character types (Python objects) from each other, in a consistent manner between server restarts, without the designer having to manually come up with an unique ID?


texts: Calculate travel time on road map with semaphores

texts:
I have a road map with intersections. At intersections there are semaphores. For each semaphore I generate a red light time and green light time which are represented with syntax [R:T1, G:T2], for example:

    119                   185                 250
A ------- B: [R:6, G:4] ------ C: [R:5, G:5] ------ D

I want to calculate a car travel time from A - D. Now I do this with this pseudo code:

function get_travel_time(semaphores_configuration)
{
    time = 0;
    for( i=1; i<path.length;i++)
    {
        prev_node = path[i-1];
        next_node = path[i]);
        cost = cost_between(prev_node, next_node)
        time += (cost/movement_speed) // movement_speed = 50px per second
        light_times = get_light_times(path[i], semaphore_configurations)
        lights_cycle = get_lights_cycle(light_times) // Eg: [R,R,R,G,G,G,G], where [R:3, G:4]
        lights_sum = light_times.green_time+light_times.red_light; // Lights cycle time
        light = lights_cycle[cost%lights_sum];

        if( light == "R" )
        {
            time += light_times.red_light;
        }
    }
    return time;
}

So for distance 119 between A and B travel time is, 119/50 = 2.38s ( exactly mesaured time is between 2.5s and 2.6s), then we add time if we came at a red light when at B. If we came at a red light is calculated with lines:

lights_cycle = get_lights_cycle(light_times) // Eg: [R,R,R,G,G,G,G], where [R:3, G:4]
lights_sum = light_times.green_time+light_times.red_light
light = lights_cycle[cost%lights_sum];
if( light == "R" )
{
    time += light_times.red_light;
}

This pseudo code doesn't calculate exactly the same times as they are mesaured, but the calculations are very close to them.

Any idea how I would calculate this?


texts: SFML Segmentation Fault when using VBOs?

texts:
I'm trying to follow along with the gltut tutorials and for some reason when I call GLDrawArrays my program segmentation faults. I've been looking at the state of my application with the Mac OpenGL Profiler and Googling and I can't seem to figure out why it isn't working. I may have missed setting some OpenGL state somewhere.

My code is here, it segfaults on line 32. If I don't call glEnableClientState(GL_VERTEX_ARRAY); and the respective glDisableClientState(GL_VERTEX_ARRAY); it compiles and runs, but I get no rendering, which is what I would expect given my limited OpenGL knowledge.


texts:
I'm currently rewoking my RTS cover system. This should highlight the closest coverspots from my mouse cursor and sent the units to these locations. everything works, but I can't get the closest sport, it always selects the sames ones, regardless to the mouse position.

These cover spots are child objects of the obstacle, that has this script attached.

This is my not working implementation of the idea:

 void Update()
    {

        var dist = Mathf.Abs(transform.position.z - Camera.main.transform.position.z);
        var v3Pos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, dist);
        v3Pos = Camera.main.ScreenToWorldPoint(v3Pos);
        mousePos = v3Pos;
}

...

public void getPointDistances()
    {
        foreach (CoverPosition pos in coverPositions)
        {
            if (!pos.occupied)
            {
                pos.distanceToCursor = Vector3.Distance(pos.transform.position, mousePos);
            }
        }
        Array.Sort(coverPositions, delegate (CoverPosition x, CoverPosition y) { return y.distanceToCursor.CompareTo(x.distanceToCursor); });

    }

Later, I simply Iterate over the sorted array and make it visisible.

I'm woking on this for hours, but i cannot find, a solution why it always displays the same cover spots.

I hope, someone can find my (possibly stupid) error.

Edit:

I also tried this, but tata returned always the same values, regardless of my mouse positioning:

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit))
            mousePos = hit.transform.position;


texts: What is a suitable input method to use for a 2D platformer on a touch device?

texts:
I am creating a 2d platformer game like Super Meat Boy in which precision of movement of my lead character matters. I am using libgdx. The keyboard controls on the PC work precisely, but when it comes to accelerometer handling, it's really hard to handle the character precisely. This worsens in stages with congested safe paths to escape. I thought of implementing an on-screen analog ball for handling input, but read a lot of bad consequences of that on the internet.

What is an intuitive but precise input method to use for platformer games on touch devices?


texts: How to make it so my cursor is not behind the UI?

texts: My cursor keeps going behind the UI how to make it go above?


texts: Developing a general use multiplayer API

texts:
I'm tasked with the development of a general use multiplayer API in JavaScript, with a Node.js back-end. The goal of the API is to provide a service to JavaScript mobile game developers so they can develop multiplayer games with an easy to use API and existing back-end.

The project also includes the development of implementations, a Node.js server and a test game, otherwise I can't test it ofcourse. So it's more accurate to call it the development of an entire library.

The problem I'm having is trying to figure out how to provide a nice mechanism for game synchronization. The library can provide room- and connection-management, friendlists, registration and soforth because those things are using the same mechanism in every game. However, game synchronization logic can be very game-specific and that is absolutely not allowed in a general use library and server.

I'm using the following libraries/frameworks for development:

Node.js as a game server.
Socket.io on client-  and server-side for websocket communication.
Require.js client-side to enable modular development.
Redis as a database for persistent storage.

To clarify the goal of the library:

Support for a wide range of games, from a turn-based strategy game with 100 syncable objects to a multiplayer top-down shooter where latency is of the utmost importance.
No client has to act as 'server' of some sort.
Minimize manual setup client-side.
Accurate synchronization without synchronizing the entire gamestate.
Server-client architecture without the server containing game-specific code.
Shouldn't pose restrictions to the developer and shouldn't demand certain coding practices.
Provide an easy to use abstraction to use the generic synchronization mechanism.
The whole range of games has to be supported by the same generic server logic.
Lag compensation must be automatic in the API or on the server, but not game specific.

So for the main question: is this possible or should I just provide a way to easily cast, multicast and broadcast messages, and leave the actual synchronization mechanism to the developer? How would you go about it?


texts:
I'm working on a tower defense game.

I'm trying to make my gun object rotate and shoot the nearest instance of the "enemy" object.

My problem here is my gun script rotates only to the main enemy object and not at its cloned objects or even the closest one!

I need my gun to rotate and face the closest enemy to itself.

Here is my clone script:

public GameObject enemy;
public float spawnTime = 3.0f;
public Transform[] spawnPoints;

void Start ()
{
    InvokeRepeating ("Spawn", spawnTime, spawnTime);
}

void Spawn ()
{
    int spawnPointIndex = Random.Range (0, spawnPoints.Length);
    Instantiate (enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
}

Gun script:

private GameObject target;
private float enemy_distance;

void Update()
{
    target = GameObject.FindGameObjectWithTag("enemy");
    enemy_distance = Vector3.Distance(transform.position, target.transform.position);
    if (enemy_distance <= 20) {
            Quaternion rotation = Quaternion.LookRotation(target.transform.position - transform.position);
            transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.fixedDeltaTime * 2);
            transform.localPosition = new Vector3(transform.localPosition.x, transform.localPosition.y, transform.localPosition.z);
    }

}


texts: How to make a z-depth buffer with pygame?

texts:
I am making a 3d renderer with python and so far am sorting the triangles which I want to replace with a z-depth buffer. The thing is, I don't know how to make a z-depth buffer in pygame. I still want it to be playable however.
By the way, I am using pygame polygons.


texts:
I want to develop a 3D game (sci-fi type with spaceships) which can be played on multiplayer mode and by multiplayer i mean around 10 players for start as it will be a personal testing project and mostly educational. I have been searching for some days about the available languages and engines but i am kinda confused. Since i have been learning Java for my 1st year in I.T university and i have pretty good understanding i thought i would go with the Java language and develop that game on an applet so it could be played on a browser. After going through an applet game tutorial i understood how graphics work on an applet.

So.. 1st question: Could an applet carry the burden of a 3D game especially on multiplayer? My thinking: It's a space game so the graphics should not be such a big problem since it wont be that crowded with entities apart from ships, planets and some effects.

If the java applet is not the way for my project i would't mind "developing it on desktop"(i mean not making it a browser game). 2nd question: Should i use Unity engine for my purpose(space game)? If not name other language/engine combo.


texts:
I want a matrix that scales first and then rotates. I tried the code below, but it didn't work. zRotation, yRotation and xRotation are rotations that shouldn't be affected by the origin. allrot should be affected.  xScale, yScale and zScale are the scaling variables. The code below works except that it rotates and then scales.

Matrix worldMatrix = (
    Matrix.CreateRotationZ(MathHelper.ToRadians(zRotation)) *
    Matrix.CreateRotationX(MathHelper.ToRadians(xRotation)) *
    Matrix.CreateRotationY(MathHelper.ToRadians(yRotation))
) * (
    Matrix.CreateTranslation(origin) *
    Matrix.CreateRotationY(MathHelper.ToRadians(allrot)) *
    Matrix.CreateScale(xScale, yScale, zScale)
);


texts: Preserve top right position and relative size to screen

texts:
I have the following circle laid out where I'd like it at 1920x1080: http://imgur.com/a/PmvVA at 1280x720 it takes the same amount of relative screen space.

When the aspect ratio changes I want the circle to remain a circle and for it to always be top right aligned.

When I set the image to preserve aspect it gets pushed downwards like so: http://i.imgur.com/1sicdD5.png

How can I ensure the image stays top right aligned in all cases?


texts: Confusion about Rotation matrices from Euler Angles

texts:
I am trying to learn more about Euler Angles so as to help myself in understanding how I can control my camera better in the game.

I came across the following formula that converts Euler Angles to rotation matrices:

In the equation, I could see that the first matrix from the left is the rotation matrix about x-axis, the second is about y-axis and the third is about z-axis.

From my understanding about ordinary matrix transformations, the later transformation is always applied to the right hand side. And if I'm right about this, then the above equation should have a rotation order starting from rotating about z-axis, y-axis, then finally x-axis.

But, from the symbols  it seems that the rotation order start rotating about x-axis, then y-axis, then finally z-axis. What should the actual order of the rotation be?

Also, I am confuse about if the input vector, in this case, would be a row vector on the left, or a column vector on the right?


texts: Calculating the "power" of a player in a "Defend Your Castle" type game

texts:
I'm a making a "Defend Your Castle" type game, where each player has a castle and must send units to destroy the opponent's castle. It looks like this (and yeah, this is the actual game, not a quick paint drawing..):

Now, I'm trying to implement the AI of the opponent, and I'd like to create 4 different AI levels: Easy, Normal, Hard and Hardcore. I've never made any "serious" AI before and I'd like to create a quite complete one this time.

My idea is to calculate a player's "power" score, based on the current health of its castle and the individual "power" score of its units. Then, the AI would just try to keep a score close to the player's one(Easy would stay below it, Normal would stay near it and Hard would try to get above it). But I just don't know how to calculate a player's power score. There are just too many variables to take into account and I don't know how to properly use them to create one significant number(the power level).

Could anyone help me out on this one?

Here are the variables that should influence a player's power score:

Current castle health, the unit's total health, damage, speed and attack range.
Also, the player can have increased Income(the money bag), damage(the + Damage) and speed(the + speed)... How could I include them in the score?

I'm really stuck here... Or is there an other way that I could implement AI for this type of game?

Thanks for your precious time.


texts:
I'm just a normal guy trying to do some basic collision detection but I suck at it. I either get stuck in a wall or I go in reverse in the wrong direction trying to update the player position to a non collision part. So here is how I check for collision and this function will return true or false. True if collision and false if not.

roguelike.player.collision = function() {
  var player = roguelike.player;
  for(var i = 0; i < roguelike.map.rooms.length; i++) {
    var room = roguelike.map.rooms[i];
    if(player.x > room.x && player.x < room.x + room.width && player.y > room.y && player.y < room.y + room.height){
      return false;
    }
  }
  return true;
};

This function works just fine just like expected. But it's when I try to stop the player when he hits a wall is where I get bugs. When the player goes down and hits a wall he gets stuck there. Here is the function that updates the player position.

roguelike.update = function() {
  var player = roguelike.player;

  //Left
  if(player.moving.left && !player.collision()) {
    player.x -= roguelike.game.speedPerSecond(player.speed);
  } else if(player.collision()){
    player.resetPosition();
  }
  //Up
  if(player.moving.up && !player.collision()) {
    player.y -= roguelike.game.speedPerSecond(player.speed);
  } else if(player.collision()){
    player.resetPosition();
  }
  //Right
  if(player.moving.right && !player.collision()) {
    player.x += roguelike.game.speedPerSecond(player.speed);
  } else if(player.collision()){
    player.resetPosition();
  }
  //down
  if(player.moving.down && !player.collision()) {

    player.y += roguelike.game.speedPerSecond(player.speed);
  } else if(player.collision()){
    player.resetPosition();
  }
  player.savePosition();

};

So what I do is check what direction the player is moving and if there is no collision detected then the player is free to move. Otherwise if there is a collision I put the player position as the last position he was when there was no collision so he will be free to move. This works going left, up, and right, but not going down. Going down the player gets stuck in the collision and the resetPosition function doesn't put the player back in the safe zone.

So I know there must be a better way. And I would appreciate your advice on what you think that way should be.


texts: High poly vs Low Poly when creating model

texts:
I am new in game development, but I have some knowledge in Maya and 3ds Max, I want to create pirate ship for game. So I spoke with many 3d artists and there are different opinions about low polygons and high polygons modelling. I am an iOS developer too so I know that it's hard for computer to process many polygons, so we should reduce amount of faces as much as we can. But my question is much more connected to 3D.

Do I need to create low polygons model at start and then smooth it to increase amount of faces or do I need to create high polygons model and then reduce amount of edges, faces and etc?


texts:
I'm currently developing my own game but I'm facing a little problem. I am trying to figure out how to get the position of a fixture (collision) between two entities.

For example this:

(the grey rectangle is the player and the greens is an entity (not moving)).

With this code :

        Array<Contact> contacts = levelDatas.world.getContactList();
        try {
            for(Contact contact : contacts) {
                if(contact.getFixtureA().equals(playerBody.getFixtureList().get(0))) {
                    levelDatas.bodyIsWall(contact.getFixtureB().getBody());
                }
                if(contact.getFixtureB().equals(playerBody.getFixtureList().get(0))) {
                    levelDatas.bodyIsWall(contact.getFixtureA().getBody());
                }
            }
        } catch(GdxRuntimeException exp) {
        }

I get all the collision between a player and something else. But my problem is that I want to know where the collision is happening (on the left? on the right? bottom? top?). We can see that if there is a collision between 2 entities, a little point is draw. Anyone have a tip to give me the position of the collision?

Thanks


texts:
I'm working on a turn based rpg and have an action/queue system setup that I'm happy with. However, I am having trouble implementing a feature and I am here for some advice. I want to have effects/abilities that alter other outcomes of actions/effects and am not sure how to structure things to allow for this.

I'll provide an example to illustrate what I am trying to achieve.

Say we have two characters in combat. The attacker needs to roll 1d20 and add the result to their current strength to see if they make a hit. If that value is equal to or greater than the defender's toughness the attack is successful and the defender takes damage.

def Attack(attacker, defender):
    roll = Dice.roll()
    roll += attacker.strength

    if roll >= defender.toughness:
        defender.damage(attacker.weapon.power)

Now lets say the attacker has a piece of gear on that says if they get a critical hit (a roll of 20) they hit the monster no matter what and deal one point of damage. How do I inject this code into the attack function and have it ignore the portion of the function after the dice is rolled (the armor's effect is replacing the rest of the attack)?

I've thought of breaking the code into chunks

def Critical_Hit_Buff(roll, defender):
    if roll == 20:
        defender.damage(1)
        return False
    return True

def Attack(attacker, defender):
    do_continue = True
    roll = Dice.roll()

    #check if any buffs from armor/etc. activate
    for buff in attacker.buffs('attack'):
        do_continue = buff(roll, defender)

    if do_continue:
        roll += attacker.strength

        if roll >= defender.toughness:
             defender.damage(attacker.weapon.power)

But I really don't like having to carry around the continue variable everywhere and further I don't know if an action is not continuing because the action failed (some buff/debuff prevents the attack from being successful) or if it was because some effect replaced the attack event (this might be relevant if I give the player notifications that about if the action was successful or not).

Any advice?


texts: Unity: Assign GameObject to Class that hasn't been yet instantiated

texts:
I'm creating a game where I have an Entity class that contains basic entity info (pos, health,..) and some functions. Enemies and Player later on inherit from this class.

Public class Entity {

public Vector2 position;
public float health;
,...

Lets say that I have a function like this inside the Entity class:

public GameObject movingIntoEnemy(Vector2 movingToPoint)
{
    foreach (GameObject go in GameObject.Find("GameMap").GetComponent<GameMap>().enemyList)
    {
        if (go.GetComponent<EnemyScript>().enemy.position == movingToPoint)
        {
            return go;
        }
    }
    return null;
}

This function looks for a GameObject called "GameMap" and then cycles through enemies in it's list. If an enemy is found, it returns it's GameObject. Using GameObject.Find() is pretty ineffective, so what would be a better approach to this? I mean, I can't just easily use

public GameObject GameMap;

since the code is in a class, and this class needs to be instantiated first in my player/enemy scripts.

My question is - how do I attach gameObjects to this class before it is even created? What is the appropriate approach to this? I guess that I might pass these GameObjects to the class through it's constructor, but it would make things much more complicated.

Thanks in advance ;)


texts: Instantiated objects sharing the same animator cannot animate independently?

texts:
I have two scripts and an animator. The first script is attached to an empty gameobject and creates eight plane (for use as cards). The second script runs a flipping animation if the plane/cards are click.

Card Init

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

public class cardInit : MonoBehaviour {

    List<Texture> cardFront = new List<Texture>();
    List<GameObject> cardList = new List<GameObject>();

    public GameObject newCard;

    Vector3 startPos;
    Vector3 endPos;

    // Use this for initialization
    void Start () {

        startPos = new Vector3(-10, 0, 0);
        Vector3 left = new Vector3(3 ,0 ,0);

        for (int i = 0; i <= 7; i++)
        {
            cardList.Add(GameObject.Instantiate(newCard,startPos,Quaternion.Euler(90,0,0)));
            startPos += left;
        }
    }

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

    }
}

Card Flip

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

public class cardScript : MonoBehaviour {

    private Animator animator;

    // Use this for initialization
    void Start ()
    {
       // animator = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit))
            {
                //gameObject.animator.SetInteger("onMouse", 1);
                gameObject.GetComponent<Animator>().SetInteger("onMouse", 1);
            }
        }
    }
}

However, since the instantiated objects all uses the same animator, changing the animator parameter to flip a single card causes all the cards to flip.

I believe the issue lies with the instantiated objects all referencing a singular animator rather than initialising a copy of its own. Is there a way to rectify it so each card only flips itself on click?


texts: Understanding and editing HDR light environments in Photoshop

texts:
I'm working with an in-development system that uses .hdr environments (equirectangular projection) to provide image-based lighting (IBL) to a 3D rendering.  I'm trying to understand what range of values can be stored in an .hdr image, and how to edit them in Photoshop.

In Photoshop, I can open (or create) .hdr images with 32-bits per channel. In this mode, 'normal' colors have RGB values in the range 0.0 - 1.0. However, I can pick colors that go as high as 20.0 in each channel. I thus assumed that a value of 20.0 was the maximum that could be stored in a .hdr file.

However, if I fill a region with brightest white (20.0,20.0,20.0), and then fill again with (4.0,4.0,4.0) on Multiply mode, I end up with colors that have a value of ~80 (as reported by the Info palette in 32-bit mode). Do it again and I get ~320. I can keep repeating the multiplication and the values shown in the Info palette get successively larger, until the Info palette display maxes out at -231 (-2,147,483,648).

Some of the free .hdr panoramas that I have found online max out with the sun at around 20 brightness. Some of them, however, max out at 16000 or so. The result is that there are massive tone mapping differences needed between different environments that should be equivalent, e.g. both are a sunny day outdoors. I want to normalize the maps we use and generate, but I first need to figure out what "good" values are for the sun, sky, and ground.

What is the largest channel value represented in a .hdr image?
What is the significance of Photoshop's 20.0 maximum for a color?

Edit: Manually entering RGB channel values of 1, 4, 10, and 20 and painting one pixel using them shows the following results. The fifth square was painted with RGB of (20,20,20) on Normal mode, and then painted again with RGB of (4,4,4) using Multiply mode. The color of this pixel is shown at the top of the Info palette. (The first RGB entry is set to Actual Color, while the second is set to RGB; both readouts are set to 32-bit, as shown.)

Note that these colors are obtained by typing values in the RGB channels of the Color Picker (section "D" in the picture below from Adobe's help), NOT by using the "Intensity: [______] stops" entry. Typing in RGB values of 20.0 sets the Intensity to 4.73 stops. Entering larger intensity values—up to a maximum of 20.0—still results in the RGB values showing 20.0 each in the color picker, but the resulting paint showing larger RGB values of up to 786432 in the Info palette.

Photoshop CS3 HDR Color Picker http://livedocs.adobe.com/en_US/Photoshop//10.0/images/im_hdr_picker.png

As described above, however, even this "largest" value can be made even larger by multiplying the color.


texts: GLES2-AnchorCenter branch has no org.andengine.util.color.Color

texts:
I am porting my game from GLES2 to GLES2-AnchorCenter branch. I am using

import org.andengine.util.HorizontalAlign;
import org.andengine.util.color.Color;
import org.andengine.entity.particle.modifier.ExpireParticleInitializer;

... but these aren't available in GLES2-AnchorCenter branch, it seems.
Could anybody guide me on this?


texts: Libgdx storing rendered frames quickly to use them later

texts:
I have implemented a gif-button for my libgdx game that allows the player to store the last few seconds of gameplay as a gif.

It works by storing frames in memory, and encoding them into a gif if the player presses a Button.

The problem is, that my method of storing the frames takes around 20ms, far to slow for my 60fps game. This leads to stuttering.

Currently im storing the frames like this:

private static LinkedList<Pixmap> frames = new LinkedList<>();

private static float delay = 0;
static Pixmap pixmap;
static int width = Gdx.graphics.getWidth();
static int height = Gdx.graphics.getHeight();

// called every frame
public static void act(float delta) {
    delay -= delta;
    if (delay <= 0f) {
        // the actual storing of the frame. ~20ms
        Gdx.gl.glPixelStorei(GL20.GL_PACK_ALIGNMENT, 1);
        pixmap = new Pixmap(width, height, Pixmap.Format.RGBA8888);
        Gdx.gl.glReadPixels(0, 0, width, height, GL20.GL_RGBA, GL20.GL_UNSIGNED_BYTE, pixmap.getPixels());
        frames.add(pixmap);

        // remove old frames and reset delay
    }
}

I have tried to allocate as little memory as possible but its still way to slow.

Concurrency is not an option for this approach since the gl methods need to be called on the rendering thread.

I would be very thankful for a solution or ideas for other possible ways to achieve my goal.


texts: ID3D11DeviceContext:::CopyResource is bottleneck in my particle system

texts:
I have a snow particle system and I use simplex noise for creating turbulence effect.
At first, I made calculations on the CPU, and the simplex noise calls obviously were the bottleneck.
The MAX_NUM_PARTICLES limit was 50k (to hold the 60 fps). There was a fatal drop for 75-100k.
That's why I moved the calculation to compute shader like here.
Snow particle system is working, however, I got a weird result: the fps limit left the same, but it does not fall so critically -- I can render 100-200k with 45 fps.
At first, I played with Dispatch params, but the fps was the same for 512, 1, 1 and 1, 1, 1 calls.
Second, I convinced that simplex noise calculations were not a problem just passing input coordinates into the output buffer.
Then I commented out different parts of the code and realized that ID3D11DeviceContext:::CopyResource is the bottleneck. I use RWStructuredBuffer buffer to gain compute shader results and, as I know, it requires additional buffer with D3D11_USAGE_STAGING usage and D3D11_CPU_ACCESS_READ flag. So think I can't refuse to use it.
Please share your ideas What can I do about it?
Code part:
    // Create a system memory version of the buffer to read the results back from.
    outputDesc.Usage = D3D11_USAGE_STAGING;
    outputDesc.BindFlags = 0;
    outputDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;

    result = (device->CreateBuffer(&outputDesc, 0, &mRWOutputBuffer));
    if (FAILED(result))
        return false;

    D3D11_UNORDERED_ACCESS_VIEW_DESC uavDesc;
    uavDesc.Buffer.FirstElement = 0;
    uavDesc.Buffer.Flags = 0;
    uavDesc.Buffer.NumElements = m_pParticleSystem->GetInstaceCount();
    uavDesc.Format = DXGI_FORMAT_UNKNOWN;
    uavDesc.ViewDimension = D3D11_UAV_DIMENSION_BUFFER;

    result = device->CreateUnorderedAccessView(mRWBuffer, &uavDesc, &mRWUAV);
    if (FAILED(result))
        return false;

    m_pParticleSystem->FillConstantDataBuffer(deviceContext, mInputBuffer);

    // Enable Compute Shader
    deviceContext->CSSetShader(mComputeShader, nullptr, 0);

    deviceContext->CSSetShaderResources(0, 1, &mInputView);
    deviceContext->CSSetUnorderedAccessViews(0, 1, &mRWUAV, 0);

    // Dispatch
    deviceContext->Dispatch(512, 1, 1);

    // Unbind the input textures from the CS for good housekeeping
    ID3D11ShaderResourceView* nullSRV[] = { NULL };
    deviceContext->CSSetShaderResources(0, 1, nullSRV);

    // Unbind output from compute shader ( we are going to use this output as an input in the next pass,
    // and a resource cannot be both an output and input at the same time
    ID3D11UnorderedAccessView* nullUAV[] = { NULL };
    deviceContext->CSSetUnorderedAccessViews(0, 1, nullUAV, 0);

    // Disable Compute Shader
    deviceContext->CSSetShader(nullptr, nullptr, 0);

    // Copy result **(FPS DROP HERE)**
    deviceContext->CopyResource(mRWOutputBuffer, mRWBuffer);

Thank you for your answer in advance.


texts: Unity: parallel vectors and cross product, how to compare vectors

texts:
I read this post explaining a method to understand if the angle between 2 given vectors and the normal to the plane described by them, is clockwise or anticlockwise:

public static AngleDir GetAngleDirection(Vector3 beginDir, Vector3 endDir, Vector3 upDir)
{
    Vector3 cross = Vector3.Cross(beginDir, endDir);

    float dot = Vector3.Dot(cross, upDir);

    if (dot > 0.0f)
        return AngleDir.CLOCK;
    else if (dot < 0.0f)
        return AngleDir.ANTICLOCK;
    return AngleDir.PARALLEL;
}

After having used it a little bit, I think it's wrong.
If I supply the same vector as input (beginDir equal to endDir), the cross product is zero, but the dot product is a little bit more than zero.

I think that to fix that I can simply check if the cross product is zero, means that the 2 vectors are parallel, but my code doesn't work.

I tried the following solution:

Vector3 cross = Vector3.Cross(beginDir, endDir);
if (cross == Vector.zero)
    return AngleDir.PARALLEL;

And it doesn't work because comparison between Vector.zero and cross is always different from zero (even if cross is actually [0.0f, 0.0f, 0.0f]).

I tried also this:

Vector3 cross = Vector3.Cross(beginDir, endDir);
if (cross.magnitude == 0.0f)
    return AngleDir.PARALLEL;

it also fails because magnitude is slightly more than zero.

So my question is: given 2 Vector3 in Unity, how to compare them?

I need the elegant equivalent version of this:

if (beginDir.x == endDir.x && beginDir.y == endDir.y && beginDir.z == endDir.z)
    return true;


texts:
I'm working on a game using SDL2. Today I noticed the game has some jolty issues when not fullscreened so I made an extremely simplified program that simply moves a square from left to right to see if the result is the same.

I expected the squares movement to be very smooth but instead it's very jolty/laggy (when not fullscreened).

At first I thought it was to do with how I was calculating the time between each frame but after outputting the 'ftime' I can see the time each frame takes ranges from 13 to 30(ish) as opposed to a consistent 16/17.

Here's the code:

#include <iostream>
#include <SDL.h>

const int GAME_WIDTH = 1920;
const int GAME_HEIGHT = 1080;

//frame independent movement variables
double old_time = 0;
double current_time = 0;
double ftime = 0;

#undef main
int main(int argc, char** argv)
{
    SDL_Window* mainWindow;
    SDL_Renderer* mainRenderer;

    SDL_Init(SDL_INIT_EVERYTHING);

    mainWindow = SDL_CreateWindow("MiracleSquare", 50, 50, GAME_WIDTH, GAME_HEIGHT, 0);
    mainRenderer = SDL_CreateRenderer(mainWindow, -1, SDL_RENDERER_PRESENTVSYNC);

    SDL_Rect miracleRect; //creating the SDL square
    miracleRect.x = 0;
    miracleRect.y = 400;
    miracleRect.w = 100;
    miracleRect.h = 100;

    bool running = true;

    while (running)
    {
        old_time = current_time;
        current_time = SDL_GetTicks();
        ftime = current_time - old_time;

        std::cout << ftime << std::endl;

        SDL_Event e; //stops crashing on input
        if (SDL_PollEvent(&e))
        {
            switch (e.type)
            {
            case SDL_KEYDOWN:
                break;
            default:
                break;
            }
        }

        miracleRect.x += (ftime / 1000.0f) * 100.0f;
        if (miracleRect.x> 1920) miracleRect.x = 0;

        SDL_SetRenderDrawColor(mainRenderer, 0, 0, 0, 255);
        SDL_RenderClear(mainRenderer);
        SDL_SetRenderDrawColor(mainRenderer, 255, 255, 255, 255);
        SDL_RenderDrawRect(mainRenderer, &miracleRect);
        SDL_RenderPresent(mainRenderer);
    }

    return 0;
}

Am I doing something wrong? As far as I can tell this should produce a smooth movement.

Any help would be greatly appreciated!

Edit: Since posting this I've figured out it has something to do with my use of dual monitors. If, for example, I have a video playing on chrome on my secondary monitor, the lag issue is very prominent. I'm now looking into if this issue is avoidable, or if I'll just have to ignore it.


texts: I want to get rid of my make-everything-static-and-global design pattern, but how?

texts:
I'm making a little dungeon crawler in space, and I'd like to hear some advice on how to make the backend of the engine nicer. Basically, currently everything is based on a crapload of managers:

BackgroundManager: has AddBackground(image, parallax) method for making cool background effects.
ConfigManager: reads/makes the config file and also holds the data read from that config file.
DrawManager: has Draw(sprite) method to draw stuff to the screen, and things like SetView(view), GetView() etc.
EntityManager: holds all active entities and has methods for adding, removing and finding entities.
DungeonManager (actually called a GridManager, but this is for simplicity): has methods like GenerateDungeon(), PlaceEnemies(), PlaceFinish() etc.

Now I'm not even halfway there listing all my managers, so I think this has got to change. My game is also based on Screens, which makes it more annoying because I don't need half of the stuff my managers are managing in, for example, the main menu (I don't need physics/entities/dungeons in my main menu!)

Now I thought about making the managers not static, and giving my ScreenMainGame an instance of all game-specific managers. But that makes calling/getting anything related to the managers a huge mess... for example, if I wanted to draw my dungeon from any place that's not in ScreenMainGame.Draw(), I'd have to do this...

((ScreenMainGame)ScreenManager.CurrentScreen).GridManager.Draw()

That's really ugly.

So, fellow game developers, does any of you have an idea how to solve this mess? I'd be appreciated!


texts: How to remap world space to screen space?

texts:
I am noob to game development, and while using a simple graphics library in Python to make a 2D game, I noticed that the coordinate system of the library had its upper left corner as (0,0), whereas conventionally (at least in math) the lower left corner is set as (0,0).

I want to keep the world space in my physics calculations, but want to map the world space coordinates into the screen space. Furthermore, I want the world space sizes to be a scale of 10 larger than the screen space sizes.

In terms of programming methodology, how should I go about doing this in the most modular fashion?


texts:
I'd like Unity to get a specific button with:
GetComponent<Button>().interactable

But how do I get a specific button with a name?


texts: How to calculate vector that is perpendicular to the direction of moving in Flash?

texts: In flash i have a class that extends movieclip and i am moving it forward, up and down, and rotating it. How can i calculate the vector that is perpendicular to this movieclip?


texts:
There are white little dots between blocks at random places, mainly at very near blocks. They disappear when I move the mouse and change the view direction.

I use Vertex Arrays with glVertexAttributePointer to send the data directly to the shader. The shader only adds some fake light based on the face direction and draws the pixels.

What could be the reason for the small white artifacts?

Chunk render code:

public void renderChunk() {
    glPushMatrix();

    glTranslatef(pos.x*world.chunkSize.x, 0.0f, pos.z*world.chunkSize.z);

    glBindBuffer(GL_ARRAY_BUFFER, vao_id);

    glVertexAttribPointer(world.game.positionAtt, 3, GL_FLOAT, false, 32, 0);
    glVertexAttribPointer(world.game.normalAtt, 3, GL_FLOAT, false, 32, 12);
    glVertexAttribPointer(world.game.texCoordAtt, 2, GL_FLOAT, false, 32, 24);

    glDrawArrays(GL_TRIANGLES, 0, arraySize / 8);

    glBindBuffer(GL_ARRAY_BUFFER, 0);

    glPopMatrix();
}

Vertex Shader:

attribute vec3 in_position;
attribute vec3 in_normal;
attribute vec3 in_texcoord;
varying vec2 texture_coordinate;
varying vec3 normal;

void main()
{
    gl_Position = gl_ModelViewProjectionMatrix * vec4(in_position, 1.0);
    normal = in_normal;
    texture_coordinate = in_texcoord;
}

Fragment Shader:

varying vec2 texture_coordinate;
varying vec3 normal;
uniform sampler2D texture;

void main()
{
    float add;

    if (normal.x == 1.0 || normal.z == 1.0) {
        add = 0.65;
    } else if (normal.y != 1.0) {
        add = 0.8;
    } else {
     add = 1.0;
     }
         gl_FragColor = texture2D(texture, texture_coordinate) * add;
     }

Enlarge the image by click it to notice the artifacts.


texts: How detect which OpenGL texture formats are natively supported?

texts:
For example, how detect if my videocard doesn’t support "bgr8" and convert it to another format, such as "rgba8" in software mode.

UPDATE: Sorry for the confusion. This question more about situation when I set internalFormat in glTexImage2D to something like "bgra8" but videodriver internally convert data to another format, like "rgba8".


texts: Why my images always change color when I use glDrawPixels?

texts:
I am doing a exercise for the college, where I need load a file 'ppm' but any picture does not load with correct colors. I tried change parameter of glDrawPixels, glBlendFunc, but nothing change for the correct colors.
And some changes makes  window do not show the picture.
I don't know I need to do.

int CALLBACK WinMain(
__in  HINSTANCE hInstance,
__in  HINSTANCE hPrevInstance,
__in  LPSTR lpCmdLine,
__in  int nCmdShow )
{
    if (!glfwInit()) return -1;

    window = glfwCreateWindow(WIDTH, HEIGHT, "ParallaxGame", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }

    glfwMakeContextCurrent(window);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0.0, WIDTH, HEIGHT, 0.0);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    while (!glfwWindowShouldClose(window) && glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS)
    {
       glEnable(GL_BLEND);
       glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
       functionTemp();

       glfwSwapBuffers(window);
       glfwPollEvents();
    }

    glfwTerminate();
    return 0;
}

void functionTemp() {
    vector<Image*> chars;
    base->load("sully.ppm");

    for (int y = base->getHeight() - 256; y >= 0; y -= 256) {
        for (int x = 0; x < base->getWidth(); x += 256) {
            Image *c = new Image(256, 256, 4); // width, height and channel
            base->cut(c, x, y);
            chars.push_back(c);
        }
    }

    for (int i = 0; i < chars.capacity(); i++)
    {
         glDrawPixels(256, 256, GL_BGRA_EXT, GL_UNSIGNED_BYTE, chars[i]->getPixels());
    }

}

Images:

Someone can help me please?


texts: How does this formula for generating water waves work?

texts:
I have been trying to implement the wave equation described in this paper ("Water Simulating in Computer Graphics," Kai Li and Liming Wu) in Java. Part of the paper discusses modeling waves as a sum of sine waves ("sine wave piling"); in that section there an equation for describing a single sine wave:

Y（x，y，t）= A * cos（w *（x，y）+ wt * t + FI;

where

A = amplitude of wave
L = wave length
w = spatial angular frequency
s = speed
wt = temporal angular frequency
d = direction
FI = initiatory phase

I understand that it returns a vector, but I don't see what this section of the formula means:

w *（x，y）

I believe that w is a vector, but I'm not sure if it's a 3D vector or 2D vector, and how it is used. If you have time, could you please explain this formula to me?


texts:
I'm not much of a maths expert, so this is probably quite straight forward. I was playing a soccer flash game where you take free kicks. You provide Power, Swerve and Direction. I'm reading up on vectors and such so I can use the direction and power information to shoot the ball with the correct velocity.

What I don't understand is how the 'Swerve' information is used. What formula connects the Swerve information with the Direction and Power? This is all assuming a 2D environment.


texts:
How can I handle collisions with obstacles in LibGDX?

Is there any automatic way to stop the character's movement when it collides with a wall or I have to constantly poll for all the possible objects it might encounter and stop the movement accordingly?
Polling this way seems pretty poor performance-wise, especially if the framework already does that for me and I make no use of it.

My game is a top view roguelike, more or less like "The Binding of Isaac".

EDIT some beginners like me might make good use of it.
Since LibGDX has no built in collision detection without Box2D, for games where physic calculation is not needed you can build your system as follows:
Create 3 lists (Static, Dynamic, Controlled) where you put all your (relatively inherited) objects in the scene.

Static objects (walls, obstacles, traps) are passive and perform no checks.

Dynamic objects (projectiles) perform checks on both Static (stop if you hit a wall, destroy self) and Controlled (deal damage)

Controlled (players, enemies) objects perform checks on self (player hit AI controlled enemy) and static objects

After a collision is reported notify the relative objects.
Controlled objects can be Dynamic aswell but if you have a lot of projectiles flying around you can avoid self-checking Dynamics and improve the performance.
This way you should reduce a lot of useless checks aswell as limit cross-checks (both player and projectile notifying eachother) and keep your game well organized.
This is just an idea that i'm testing now, I can't guarantee it's the best :P


texts:
In my dev enviroment I have a couple custom handlers I want to always be visible.

I have already figured out that I can do this by deriving a class from Editor, linking it to the desired component type, and then appending the render method to SceneView.duringSceneGui (in OnEnable(), as the target gameobject information will be available there).

However, this appending now only happens once a specific gameobject carrying the component has been selected. Is there a way I could have the Editor's OnEnable() method properly trigger on opening a scene, for all relevant gameobjects, without manually selecting them first?


texts: SceneManager.LoadScene doesn't seem to be working in Unity IDE

texts:
I'm in the start screen scene of my game and I'm trying to load the actual game. I use the following code:

public void LoadGame(){
        SceneManager.LoadScene ("Main", LoadSceneMode.Single);
    }

I set this method to be called when a button in the UI is clicked. When testing in the game in the unity IDE, clicking the button doesn't do anything. Is my code wrong, is the IDE screwing up, or will clicking the button never do anything in the ide?


texts: I am currently developing a game that includes a server and some clients. Currently, the server does its work based on user input then draws the image the clients should see and sends it. Unfortunately, the server's time is taken up almost exclusively by the drawing and encoding. Is there a better way for me to design this?


texts: Unity: how to change runtime code for different platforms?

texts:
In Unity, how can I programmatically control what source code is compiled?

I have a script with various BuildPipeline.BuildPlayer calls, allowing me to build all versions of my game. However, I'm using the AVPro Video asset to play video, and it doesn't support 32bit Mac. As such, I need to fall back other video playing code on 32bit Mac. There's no preprocessor directive to differentiate 32bit OSX (like you can do for other platforms https://docs.unity3d.com/Manual/PlatformDependentCompilation.html ).

However, since I'm building each version in sequence, it seems like I should be able to set some state so that during compilation, the right code is used. I tried this:

VersionHandler.onMac32 = true;
BuildPipeline.BuildPlayer(levels, path, BuildTarget.StandaloneOSXIntel, BuildOptions.None);
VersionHandler.onMac32 = false;

And then checking that static variable in game. However, that static is "never set", presumably because the the state of the variable during compilation doesn't affect the value at runtime. Is there any other way I can "get at" the compiled code and set a flag for certain builds?

As a fallback, I can manually swap code in every time I build for OSX 32-bit, but I'd prefer not to do that.


texts:
I know there are plenty of algorithms for finding a path from A to B. There's also a good few articles on how to avoid an enemy in a 2D space. I can't find anything on escaping from an enemy in a blind 2D space. Here's what I mean by "blind" 2D space.
1, The fleeing agent only knows its position in the grid and the enemy's position.
2, I do not know how big the grid is.
3, I do not know where the walls or obstacles are.
4, If I want to check what's directly next to me I have to "go" there, if my position changes it's an empty space, else it's a wall or an obstacle.
The goal is to avoid the chaser (enemy) for 1000 moves. I move 2x as fast therefore I get to make 1000 moves while the enemy can only make 500 (moves every 2nd turn). Furthermore I can only move in 4 directions; up, down, left, right. The enemy gets to move in diagonals too.
My first idea was to find a block or a cluster of blocks I could circle around. Well, didn't work, by the time I found one the enemy caught me. Is there a way or an article describing this problem? Would appreciate any suggestions or articles sent my way.


texts: How to make a joystick follow the touch around a starting point using atan2?

texts:
I would like to move a joystick, and be able to go beyond the limit of the circle, and the joystick should follow the angle from the touch (the touch is moving), but it should stay on the circle. It should not go beyond the circle.

I calculate the angle with atan2, then place the joystick at a specific radius from a starting point.

The problem is that the values are positive only, so the joystick only stays in the top right quarter : when the touch goes down, the joystick goes until y=0, then it goes up, whereas the touch is still going down.

Would you know how to fix this? The joystick should follow the same angle as the touch, around a starting point :

Here is the code :

func moveJoystick(touch:CGPoint){
    let invY : Float = Float(self.view!.frame.size.height) - Float(touch.y)
    let dy : Float = Float( fabs( invY - Float(startPosFrontJoystick.y) ) )
    let dx : Float = Float ( fabs( touch.x - startPosFrontJoystick.x ) )

    //find angle when more than limit of radius //** HERE **
    let radWhenBeyondLimit = atan2(dy, dx)
    let newX : Float = cos(radWhenBeyondLimit)
    let newY : Float = sin(radWhenBeyondLimit)

    //place front joystick on circle
    let yPos : Float = Float(newY) * radiusForFront + Float(startPosFrontJoystick.y)
    let xPos : Float = Float(newX) * radiusForFront + Float(startPosFrontJoystick.x)
    frontJoystick.position = CGPoint( x:CGFloat(xPos), y:CGFloat(yPos) )
}

Thanks


texts: A star pathfinding and discrete/smooth positions

texts:
The A* (A-star) algorithm usually represents a path on a grid.

Once a path has been found, however, the path looks blocky and is not suited if you move your units with floating point datatypes.

Here is an image describing the problem. The whites tiles represent the path found by A*. The black line path  is the path I want, the red line path is the one I don't.

One solution would be to select a corner when the path turns, and switch/keep side when the path turns the other way. Seems like the most logical and cleanest way to do this.


texts: Programming an Artificial Agent in Open Arena

texts: Does anyone know source example source codes and tutorials to start writing an intelligent bot for Open Arena?


texts: Should I learn 2d game development before 3d?

texts: I'm an iPhone app developer. I want to get into iOS gaming. The question is-should I start with learning 2D like Cocos 2D or Corona SDK before learning 3D gaming like Unity? I'm more interested in 3D gaming, but do you think that knowing 2D gaming is a prerequisite to learning 3D development?


texts: How can I override a trigger scripts for different triggers in Unity?

texts:
I am trying to develope a story based game. And I developed my dialouge system (not an interactive system) with triggers.

It is like this

    public class Trigger : MonoBehaviour {
        public string text;
        public int variable;
        void OnTriggerEnter(Collider other) {

          sayHi(text);

            }
         }

         void sayHi(text){
          //some codes

          }
         finish(){
          //different code for different situations
         }
    }

I want to change that finish() method for different triggers. My idea is creating scripts for every trigger and make this class as parent class of it. Are there another option for it or is it the best way? Because I dont want to create hunderds of scripts for every triggers.

Another issue is that I must get a variable from main trigger script in my save script. It is like this:

GameObject[] triggerArray=GameObject.FindGameObjectsWithTag("Trigger");
for (int i = 0; i < triggerArray.Length; i++) {
   Trigger ts = (Trigger)(triggerArray [i].GetComponentInChildren<Trigger> ());
    return ts.variable;
}

While I can not write different save sripts for every trigger I can not get variable with this way if i override Trigger scripts. Because every child class of every trigger will have a different name.

By the way if my approach is not suitable for this purpose I am open for other suggestions.


texts: Change the image gallery using joystick with Unity

texts: I want to change the image using joystick controls.I have two two button(Go and Previous).How can I change the image using joystick


texts: Procedural generation of plausible genealogy tree with time query without history

texts:
So I'm laying out the basis for procedural generation of persistent and unique NPC across their entire life, many generation and space (travel).

But right now I'm stuck on plausible genealogy. Let assume that there is infinite ancestry and infinite descendant.

Now genealogy would be simple if we had a periodic symmetric tree (as the same number of children for all ancestor), ie all children are born at the same time. If we know the time of the first generation as an arbitrary number we know it's an offset that grow exponentially at each generation. For example assuming a binary tree, we know at arbitrary generation x that total birth was x² so every indexes in that interval belong to the same generation (and to find the total number of person who live once I'm sure there is a mathematical formula to found out). This is key we don't need to know the history to infer the population's size.

Let say you have a family line. You have a mother, she hit her fertility maturity's range and give birth to a random number of child at random time. So the genealogy have a random number of branch at random time from the root ... Less easy to infer generation locally.

Let's simplify the problem to a single line (a path in the tree from 1 ancestor to 1 descendant) and assuming that all NPC are women that spontaneously give birth (men don't give birth so they don't generate branch directly, they are dead end, so we can safely ignore this point).

We have a random series where each new point is the birth of a new npc, let assume you have an input t that is use to "query" the function such as it return if the character is born or not. The problem is that all descendant's birth time depend on the sum of all the previous interval between each birth + its new random interval, which is non local ... The same problem apply for the random branch, how do we know which "branch indexes" to not visit y generation down because it was never generated?

The think is there a plausible solution to this that would give at least the illusion of randomness? In a query without history?

EDIT:
What I'm trying to determine is for a given time t, all the branches (list of indexes) that exist (character birth) without having the history of state (building the whole tree).

I have demonstrate it's possible with a symmetric ordered tree periodic on t (ie all generation happen at given interval, character indexes are predictable because of ordered tree).

I'm trying to determine if there is a pseudo random way to have a non symmetric tree with (apparently) non periodic branch and still query all the existing branch at time t.

OR if there is a better way to create the illusion of tree without the hassle to predict the tree random recurrence.

EDIT2
The point was to avoid simulation like we do in generating landscape with perlin noise, hence why I'm investigating random interval in a tree (where each branch have a differing growth rate).


texts:
I found the example code for the GestureListener class, but I don't understand the zoom method:

private float initialScale = 1;

public boolean zoom (float originalDistance, float currentDistance) {
    float ratio = originalDistance / currentDistance; //I get this
    camera.zoom = initialScale * ratio; //This doesn't make sense to me because it seems like every time you pinch to zoom, it resets to the original zoom which is 1. So basically it wouldn't 'save' the zoom right?
    System.out.println(camera.zoom); //Prints the camera zoom
    return false;
}

Am I not interpreting this right?


texts:
I am neither a game designer nor a graphic designer. I am a .Net and C#
software developer. I have a game project and I've still been studying to learn
game concepts and technolgies for a year.

I've decided to create a 3D based and networked MMO game with Unity3D.
I've planned to hire graphic artists to do my game assets.
However, I only know what I want? In other words, I only know concept of 3D models.

What I have to request from graphic artists and how can inspect their work?
Do I have to determine some quality criterias or something like this?
Same questions are also valid for humanoid and NPC animations.

Thanks


texts:
Anybody develop games for Android TV? Especially with libGDX?

I would like to know what game controllers Android TV uses? And whether we can use libGDX to control the game controllers?


texts:
I'm currently playing around with a base builder/manager-esque type of game similar to Evil Genius. To build a room I would like to have the following process:
1. Select room type
2. Click and hold the mouse. Drag to create a rectangle over the area.
3. On release, place entire room.

I have already implemented this, but I find it inefficient and I would like to improve it. As of now the indicator rectangle is simply a sprite that is scaled and moved to fit. I would, however, like to have the indicator rectangle to be "adaptive". Meaning that if I drag a placement rectangle over an invalid area the indicator will be red at that point.

To do this I figured I could go with some sort of loop. I.e. "A change in rectangle size noticed. Update all new indicator tiles with correct colour". I had all the pseudo code figured out, but then I realised instantiating a number of gameobjects would be kinda inefficient. If the player is making a large rectangle in a short amount of time, that would surely slow down the game? Is there any other way to solve my problem, or is this the most efficient solution?

I should note that this build system is grid based. Each tile has a coordinate given by two integers and is saved in a 2D array. You can easily access the array and see what tile is at any given point or find the coordinate of any tile.


texts:
In a game I'm making in LibGdx, I wish to incorporate a ripple effect. I'm confused as to how I get access to the individual pixels on the screen, or any way to influence them (apart from what I can do with sprite batch).

I have my suspicions that I have to do it through openGL, and it has something to do with apply a mesh? This brings me to my question, what exactly is a mesh?

I've been working on my game for about half a year, and am doing great with the other aspects of the game, but I find this more advance stuff isn't as well documented.

Thanks!


texts: missing editor version 5.5.1f1 on this machine. Select another version from the list unity am new to unity please help someone thanks


texts: How do I randomly spawn objects in 2D game?

texts:
How do I randomly spawn few different sprites on screen so they're not overlapping or half visible on render. The sprites should immediately start shrinking until they disappear.

I've tried to demonstrate what I have so far using JS, however it's overlapping and not shrinking:

http://jsfiddle.net/SamuraiFox/CVX7D/

Specific to Unity, I've made these sprites prefabs and have put them into the scene from where script would spawn them into game.


texts: VSSetConstantBuffers1 does not appear to be working

texts:
I'm experiencing something very strange here when using VSSetConstantBuffers1.

I have a projection * world matrix that I'm sending to a constant buffer to rotate a triangle on an axis.  When I do this, I follow this pattern:

Frame #1

Set offset to 0, count is always at 64 (4 * float4)
Map Constant Buffer using Discard.
Write matrix to constant buffer
Unmap
Call VSSetConstantBuffers1(0, 1, new []{ cbuffer }, new []{offset }, new []{ count })
Draw

Frame #2

Set offset to 64, count remains same.
Map constant buffer using NoOverwrite
Write matrix.
Unmap
Call VSSetConstantBuffers1(0, 1, new []{ cbuffer }, new []{offset }, new []{ count })
Draw

Etc... When I fill the constant buffer completely, I reset offset to 0, and start again by using discard on my map.

Now here's my problem:  Nothing shows up on the screen.  Well, that's not 100% true, the very first frame, where offset = 0 and count = 64, that shows up perfectly.  The next frame, and subsequent frames do not.

I used the Visual Studio 2017 graphics debugger to confirm that my constant buffer did indeed have data in it.  And it did, and the values were correct.

It's really weird. I should be mapping the constant buffer to the next matrix element with my 2nd call to VSSetConstantBuffers1, but it doesn't actually look like it's going anywhere near that element.

Also, I tried forcing it to just use the 0, and 64 offset/count and only updating that portion of the buffer, and it works just fine.

I've tried my best to dig up info about constant buffer offset/count, but it's pretty sparse out there (my own searches on this site gave me 0 for VSSetConstantBuffers1, same with GameDev.net).  What little I did scrounge up on Nvidia's website, makes it appear as though this pattern should work.

Since my hardware might come into question here, I have a GeForce 1080 GTX running on Windows 10 (latest update), and according to the D3D11.1 options, it does indeed support constant buffer offsets, and my feature level is at max.

Anyone have any ideas? Given the lack of info, I'm guessing the offset/count versions of constant buffers aren't too popular?


texts: In HLSL, what is the difference between "static const" and "#define" for constants?

texts:
So far I've been declaring all my constant variables as static const in my HLSL code, yet virtually every single shader example I've come across uses #define instead.

I know the reasons I would I use static const in C++ over the preprocessor and I just carried it into HLSL as well. However, I'm curious if there are any side effects or pros/cons to this, besides the standard C++ "static const versus #define" arguments.