texts: How to make a proper release build - Unity Android - x86, ARM32, ARM64

texts:
I'm trying to create a release on Google Play.

I currently have Build App Bundle checked in the build settings, and it helps decrease the build size.

In player settings I've IL2CPP set as the scripting backend, and  x86 + ARM32 + ARM64 checked as target architectures.

Once built it creates *-symbols.zip in addition to just
aab.

My questions are,

Do I need x86 + ARM32 + ARM64 all checked? (I want to comply with Google's new 64-bit requirement)
Can I build split aab's similar to 'split APKs by target architecture'? If so can I have the same version code for aab's which targets different architectures? Is there any advantage of doing so?


texts:
How're you supposed to use vertex buffers?

Say you have 500 distinct deformable shapes/models in the world (ie you want to be able to change/delete vertices from the models somewhat arbitraily as the game progresses).  The requires you refresh the vertex buffers in the frames the model has become dirty, at least.

So how should you handle your vertex buffer, assuming D3D11 interfaces (so vertex buffers are your only option to draw anything):

Store model vertices in CPU RAM.  Create one vertex buffer at program start. For each model, copy the vertices into the single vertex buffer, render
Create 500 vertex buffers, update each when necessary, render.


texts: Strange deviations while implementing alpha compositing

texts:
I've been trying to create my own 2d renderer for my game (for learning purposes) and I'm trying to implement alpha compositing. The formula I'm using is very trivial, which is color = alpha * src + (1 - alpha) * dest.

Everything seemed to be going and looking well until I started comparing it to existing 2d canvas implementations. I've tested my canvas against OpenGL, the JS canvas, and a BufferedImage in Java, and they have all been getting slightly different results to the formula I use.

For example, let's say I have a background with a red value of 1 and shape with a red value of 0.49 and an alpha of 0.026. From plugging in the values to the formula, I got a red value of 251.6187 (multiplying the original result by 255), which can be rounded to 252. However, every canvas implementation I've used returns a red value of 251.

I'm keeping all my color values in a float between 0 and 1. However, I've tried experimenting with rounding it to increments of 255 and it still had no effect. For the js canvas implementation, I simply multiply the 0-1 by 255. (BufferedImage and OpenGl both accept a float from 0-1)

Here is a program to illustrate the issue: https://editor.p5js.org/SarahJ/sketches/VTzi0r5c7

I initially thought I needed to apply round, floor, or ceil function to my result, but while that helped this example, it caused problems for others.

Is this not the alpha compositing formula that most 2D canvas implementations use, or am I doing something wrong? Any advice is appreciated. Thanks!


texts:
I am trying to make an isometric terrain editor. My problem is not to do with making isometric graphics or rendering them, rather it is to do with indexing of tiles.

Let's say I'm making a hill at tile(10,5). This would mean that tile(10,5) will be type corner_1, tile(11,5) will be corner_2, tile(10,6) will be corner_3, and tile(11,6) will be corner_4. This will create a peak in the middle of the four tiles.

It seems simple to start with, but there are so many possibilities. If we have two hills that cross over each other, we would need inverted corner tiles. If we had a diagonal mountain, the surrounding tiles would need to be turned into diagonal inverted corner tiles. I've already created most of the images for the tiles http://opengameart.org/content/simple-iso-city-work-in-progress. My question is, is there already a set of "rules" I can follow for how terrain modifies itself around surrounding terrain? Or do I have to figure out every combination of tiles myself?


texts: How do I efficiently implement Fog of War in a Real-time Strategy game?

texts:
How is fog of war implemented in RTS games such as StarCraft II or Age of Empires? I'm making an RTS, and plan for every unit on the field to have circular vision up to a certain radius.

My first thought was having a mask that is black for every point except for points close to units, where it is transparent. The masking operation itself is fast in most graphics APIs (e.g. just call mix in a shader). The hard part is figuring out what mask to use and how to update it: updating it when any unit moves is very processor-heavy.

Is there any simpler way to manage this type of fog of war?


texts: XNA VertexBuffer.SetData performance suggestions

texts:
I have a 3d world in a grid layout where each grid cell contains its separate vertex and index buffer for the mesh/terrain of that cell.

When the player moves outside the boundaries of his cell, i dynamically load more cells in his walking direction based on his viewing distance. This triggers x number of vertex and indexbuffer initializations depending on how many cells that needs to be generated and causes the framerate to drop annoyingly during this time.

The generation of terrain data is handled in a separate thread and runs smoothly.
The vertex and index buffers are added during the update cycle of the game loop.

I´ve tried batching the number of cells to be processed to avoid sending too much data at once into the buffers, which worked ok at a shorter viewing distance (about 9 cells to process), but not as well at greater distances with around 30 cells to process.

Any idea how i can optimize this?


texts: Which will be faster? Switching shaders or ignore that some cases don't need full code?

texts:
I have two types of 2d objects:

In first case (for about 70% of objects), I need that code in the shader:

float2 texCoord = input.TexCoord + textureCoord.xy

But in the second case I have to use:

float2 texCoord = fmod(input.TexCoord, texCoordM.xy - textureCoord.xy) + textureCoord.xy

I can use second code also for first case, but it will be a little slower (fmod is useless here, input.TexCoord will be always lower than textureCoord.xy - textureCoord.xy for sure).

My question is, which way will be faster:

Making two independent shaders for both types of rectangles, group rectangles by types and switch shaders during rendering.
Make one shader and use some if statement.
Make one shader and ignore that sometimes (70% of cases) I don't need to use fmod.


texts: What is Vulkan and how does it differ from OpenGL?

texts:
Khronos Group (the standards body behind OpenGL) has just announced Vulkan:

  Vulkan is the new generation, open standard API for high-efficiency access to graphics and compute on modern GPUs. This ground-up design, previously referred to as the Next Generation OpenGL Initiative, provides applications direct control over GPU acceleration for maximized performance and predictability.

Their page is quite marketese/jargon-heavy, as is the press release… In simple terms, what does Vulkan mean to game developers? (Gabe Newell is quoted as being strongly in favour, without further explanation.)

What exactly is Vulkan's relationship to OpenGL? Its previous name "glNext" (short for "Next Generation OpenGL Initiative") makes it sound like a replacement.

Update: The Vulkan 1.0 spec was released on 16-02-2016.


texts: Running multiple box2D world objects on a server

texts:
I'm creating a multiplayer game using LibGdx (with Box2d) and Kryonet. Since this is the first time I work on multiplayer games, I read a bit about server - client implementations, and it turns out that the server should handle important tasks like collision detection, hits, characters dying etc...

Based on some articles (like the excellent Gabriel Gambetta Fast paced multiplayer series), I also know that the client should work in parallel to avoid the lag while the server responds to commands.

Physics wise, each game will have 2 players, and any projectiles fired.

What I'm thinking of doing is the following:

Create a physics world on the client
When the game is signaled to start, I create the same physics world
on the server (without any rendering obviously).
Whenever the player issues a command (move or fire), I send the
command to the server and immediately start processing it on the
client.
When the server receives the command, it applies it on the
server's world (set velocity etc...)
Each 100ms, the server sends the new state to the client which
corrects what was calculated locally.
Any critical action (hit, death, level up) is calculated only on
the server and sent to the client.

Essentially, I would have a Box2d World object running on the server for each game in progress, in sync with the worlds running on the clients.

The alternative would be to do my own calculations on the server instead of relying on Box2D to do them for me, but I'm trying to avoid that.

My question is:

Is it wise to have, for example, 1000 instances of the World object running and executing steps on the server? Tomcat used around 750 MBytes of memory when trying it without any object added to the world. Anybody tried that before?
If not, is there any alternative? Google did not help me, are there any guidelines to use when you want to have physics on both the client and the server?

Thanks for any help.


texts: Simple Bounding Box Multiple Collision problem

texts:
I'm making my first game, and in it I use a moving ball to hit static blocks (kinda like breakout).

Basically, I loop through all of the static blocks on the screen each frame, update the position of the ball based on its velocity, and if it collides with a block, the ball will bounce back off of the block.

If the ball hits one block exactly, then there is no problem whatsoever. But if the ball happens to hit two blocks at the same time (that is, it hits in between both blocks), it passes right through both of them--no deflection whatsoever.

(I know the looping is inefficient and I'm looking to correct that later, but if it has to do with the problem, I just hope someone can point to me why it is that the collision resolution fails when two similar objects are hit at once.)


texts: How can I assign a layer to tiles on an individual level?

texts:
I've just started out with my first game in Unity. It's a simple 2D Platformer with a tile-based level.

When coding in the movement, I used the Physics2D.OverlapCircle() and an empty to check whether my player was touching the ground. However, I need to use a layer to make sure only the ground is detected.
my code below
//fixed update used for physics calculations
void FixedUpdate()
{
    //right or left arrows being pressed
    float moveX = Input.GetAxis("Horizontal");

    Vector2 moveDir = new Vector2(moveX * playerSpeed, rb.velocity.y);
    rb.velocity = moveDir;
}

//update used for spacebar input and force
void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        rb.velocity = Vector2.up * jumpForce*Time.deltaTime;
    }

    //is my circle overlapping any other colliders
    Collider2D collider =  Physics2D.OverlapCircle(feet.position, checkRadius, groundLayer);
    Debug.Log(collider);
}

When I tried assigning layers to my tiles, I couldn't find a way to do it.
I would be really grateful if anyone could show me how to, or if anyone can tell me a more efficient way to deal with jumping in a 2D platformer.


texts: Blender 2.6: Changing the Resolution (Rings/Segments) of a UVSphere's

texts:
I know that it's possible to change the resolution (I mean the rings and the segments) of a UVSphere by pressing [F6] and changing some arguments.

But what if I add a UVSphere to my canvas at first, then I do something else in the meantime and not till then I want to change the resultion of the UVSphere which I added before. Is that possible? Thanks.


texts: How to load in meshes efficiently into DirectX11

texts: I wanted to know if there was a standard and efficient method to load meshes from a file into DirectX11.  Currently, I'm loading .obj's by parsing them in and storing their information into a vertex buffer. This appears to be extremely slow especially when I have meshes with many vertices like the Stanford Dragon or other standard objects like the Mitsuba or Buddha.


texts: Is it possible to use Google Play Service on a game not published on Google Play?

texts:
I'm developing a game for a local Android market but for the leaderboard I'm using Google Play Services. I wanted to know whether it's possible for people to use my leaderboard without publishing on Google Play and just on that local Android market.

Problem is I got Leaderboard up and running with the GPGS but only testers can use it and I think for others be able to use it has to be out of beta and published, please correct me if I'm wrong.

Best, idn


texts: Can't join to room through Unity's Matchmaking system on the Internet

texts:
It works perfectly when I try to connect locally from my editor to my running build.

But after I start the server on my Android, and try to connect to it from my editor, it time outs:

As you can see, it finds the match, and then tries to join, but it can't.

If I try to do it from a build, the log says the following:

Log: cannot connect after {10} attempt address {::ffff:127.0.0.1:7777}
ClientDisconnected due to error: Timeout

Why does it tries localhost, when I obviously use the Matchmaking system?

When I tried it on 2 Android devices, the same happened.

Ps.: I know that it's going to be depracated, I just want to use it during a short term gift.

Thanks in advance!

Starting Matchmaker in a Start:

networkManager.StartMatchMaker();
networkManager.matchMaker.baseUri = new System.Uri("https://eu1-mm.unet.unity3d.com");

When the MatchScene ("Battle") is loaded:

if (this.isHost)
{
    networkManager.StartHost();
}
else
{
    networkManager.StartClient();
}

And the Play button's handle: (still same component)

public void Play()
{
    networkManager.matchMaker.ListMatches(0, 1, string.Empty, true, 0, 0, OnMatchList);
}

void OnMatchList(bool success, string extendedInfo, List<MatchInfoSnapshot> matches)
{
    if (matches.Count == 0)
    {
        networkManager.matchMaker.CreateMatch("match", 2, true, string.Empty, string.Empty, string.Empty, 0, 0, OnMatchCreate);
    }
    else
    {
        networkManager.matchMaker.JoinMatch(matches[0].networkId, string.Empty, string.Empty, string.Empty, 0, 0, OnMatchJoined);
    }
}

void OnMatchCreate(bool success, string extendedInfo, MatchInfo matchInfo)
{
    this.isHost = true;
    this.networkId = matchInfo.networkId;
    SceneManager.LoadScene("Battle");
}

void OnMatchJoined(bool success, string extendedInfo, MatchInfo matchInfo)
{
    SceneManager.LoadScene("Battle");
}


texts: Help understand Z value of CameraToWorldPoint

texts:
I do not understand what this CameraToWorldPoint function is used for, what is the use case of this function:
1.From my understanding, my cursor is sitting on the near clipping plane, so I am actually clicking all the points on the near clipping plane, the near clipping plane represents my screen, am I right?
2.When I use this function to convert B point to world point, I am getting the point C position, is that true?
3.Is part A->C represent the Z value, or part B->C is the Z value?
4.Then finally, is this function useless? Because I get a world position in the predefined Z position, and I do not even know what Z value should be in the first place, I can randomly assign a pointless Z value, so what is use case for this function, I know raycast can do anything I want, but when to use this function?


texts: Tile-based board game collision mechanism algorithm

texts:
I am looking to see ideas for an algorithm which will handle collisions for some battle-ship tile-based board game.

A little about the game

The game is pretty simple. Basically there is a board, which usually sized 20x36 tiles. One tile is a position that a ship can be at, unless the tile is a rock tile.

Many ships are in the game, and all players have 35 seconds to select 4 moves that their ship will perform. After these 35 seconds, all ships will perform the selected moves parallel, by doing the first selected move, then going to the second, third and fourth, and then 35 seconds again to select new moves.

A ship can either move Forward, Left or Right.

Now these are the collision rules for the game:

All ships that are moving (regardless of direction) attempt to "claim" the space that started directly in front of them. That space has five possibilites:
a. That space is empty and unclaimed. Then move the ship into that space.
b. That space contains a stationary ship. Then execute a "bump" (see below).
c. That space contains a ship that is moving, and claiming the first ship's space. Then stop movement entirely (with a collision).
d. That space is empty but claimed by a ship of the same or larger class. Then stop movement entirely (with a collision).
e. That space is empty but claimed by a ship of smaller class. Then move the ship into that space (with a collision).
All ships that are turning but have not "stopped entirely" then attempt to claim their destination space. Now that space also has five possibilities:

2.a. That space is empty and unclaimed. Then move the ship into that space.

2.b. That space contains a stationary ship OR a ship that moved there in step 1. Then stop movement entirely (with a collision).

2.c. That space contains a ship that is moving, and claiming the first ship's space. Then stop movement entirely (with a collision).

2.d. That space is empty but claimed by a ship of the same or larger class. Then stop movement entirely (with a collision).

2.e. That space is empty but claimed by a ship of smaller class. Then move the ship into that space (with a collision).
Note: At the end, all ships have their orientation changed if they tried to turn... even if they had "stopped entirely."
Note that (2b) does not depend on the ship's class. This allows a small ship to move forward into a tile even if a larger ship is attempting to turn into that tile. If two ships both try to move into the same tile for any other reason, the larger ship succeeds.

Example

So let's say you select the forward move on your ship, and there is another ship on the target tile you are aiming to (forward). So what do you need to make sure?

You need to check if that target tile is unclaimed. If it's not unclaimed, you can check if its a rock or another ship. If it is a rock, cancel movement. If it's another ship, and it does not move, push it by 1 tile and stay in the same location. If that ship does move, you have to ask it if that ship has successfully moved, but for it to return a success message, that other ship has to check if it can move, and that can have a lot of cases with a lot of callbacks and might end up not efficient.

So my question is, how can this be done, in the proper way?

Read more here about the collision mechanism rules


texts: Change collision body position in Bullet Physics Hello World project

texts:
I have got stupid and annoying problem in my app. I am using bullet physics and I've started with hello world example on wiki:
http://bulletphysics.org/mediawiki-1.5.8/index.php/Hello_World

There is someting like this:

btDefaultMotionState* fallMotionState =
            new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(0,50,0)));

What is described as set object 50m above something. So I can change the height but nothing more. I can't move it left, right - anything. Also when I set 0 everywhere ( I mean in btVector3) the object is jumping up rather than falling down or better stay still.

Can someone help me with that?

Also are there any materials except those on bullets page where are some tutorials or something?

EDIT

The main thing which I want to achive is to move my object for example left not only top or bottom.

Hope It will help in understanding.


texts: What are AO / NM / D / SG texture name equivalents in Unity

texts:
I'm not a modeler and i don't know how to match each texture with the requested ones by the material.

In one side i got unity:

And in the other, this model textures:

The only references that i found online were:

AO => Ambient Occlusion - Occlusion
NM => Normal Map - Normal Map
sg => ?
d => Diffuse?Displacement? - ?


texts:
I was trying to develop a very simple ping pong game using XNA.

In my Draw() I am drawing the player paddles first then the ball as follows:

spriteBatch.Draw(myPlayer, myPlayer1Pos, null, Color.Aqua);
spriteBatch.Draw(myPlayer, myPlayer2Pos, null, Color.Aqua);
spriteBatch.Draw(myBall, myBallPos, Color.LawnGreen);

Now the problem is the ball is no longer displayed in the game window as shown below

If on the other hand I draw the ball before the player paddle

spriteBatch.Draw(myBall, myBallPos, Color.LawnGreen);
spriteBatch.Draw(myPlayer, myPlayer1Pos, Color.Aqua);
spriteBatch.Draw(myPlayer, myPlayer2Pos, Color.Aqua);

then the right hand side paddle is no longer visible as shown below:

Can anyone explain what is going wrong here?

edit: The complete Draw():

protected override void Draw(GameTime gameTime)
{
      GraphicsDevice.Clear(Color.CornflowerBlue);

      // TODO: Add your drawing code here
      spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);

      spriteBatch.Draw(myBall, myBallPos, null, Color.LawnGreen);

      spriteBatch.Draw(myPlayer, myPlayer1Pos, null, Color.Aqua);
      spriteBatch.Draw(myPlayer, myPlayer2Pos, null, Color.Aqua);

      spriteBatch.Draw(myBkgTexture, graphics.GraphicsDevice.Viewport.Bounds, Color.Blue);

      spriteBatch.End();

      base.Draw(gameTime);
}


texts: What should the Z coordinate be after transformed by the projection matrix?

texts:
I'm working on an OpenGL 1.x implementation for the Sega Dreamcast. Because the Dreamcast didn't have any hardware T&L the entire vertex transformation pipeline has to be done in software.

What also has to be done in software is clipping to the near-Z plane as failure to clip results in the polygon being dropped entirely from rendering by the hardware.

I'm having some trouble getting the transform -> clip -> perspective divide process working correctly and basically I can sum up the problem as follows:

I transform polygon vertices by the modelview and projection matrices
I clip each polygon against the W = 0.000001 plane
This results in new vertices on the near plane with a W of 0.000001, but a Z which is twice the near plane distance
At perspective divide vertex.z /= vertex.w results in an extreme value because we're dividing a Z value (e.g. 0.2) by 0.000001

Something seems very wrong here. The projection matrix is being generated in the same way as described in the glFrustum docs.

So my question is, if I have a coordinate on the near plane, should its Z value be zero after transform by the projection matrix or should it be the near-z distance, or something else?

After clipping polygons to the W = 0.000001 plane, should the generated Z coordinates be -0.000001?

Update:

Here is the projection matrix as calculated by: gluPerspective(45.0f, 640.0f / 480.0f, 0.44f, 100.0f);

1.810660 0.000000 0.000000 0.000000
0.000000 2.414213 0.000000 0.000000
0.000000 0.000000 -1.008839 -0.883889
0.000000 0.000000 -1.000000 0.000000

Does this look correct? It's the value in the right-hand column I'm not sure about...


texts: How can I add two Vector3 directions together?

texts:
I have a direction to my target object, which is in a Vector3 format. I want cast a number of rays, as offsets from this initial direction.

X is the object. D is the direction the player needs to travel in. A & C are other directions that I want to cast rays towards to check for impacts.

A    D    C
 \   |   /
  \  |  /
   \ | /
    [x]

I was trying to add an offset, such as Vector3.Right to the Direction and then normalise the result, however this only works if everything is oriented towards World Space.

So how can I convert and add a direction (Vector3.right) as an offset to an existing direction?

I'm fairly sure I just have World Space and Local Space directions mixed up but can't see an easy way to convert between this with Vector3?


texts:
I'm building a simple snake game, which is my first game ever. I'm using LibGDX, which is Java-based.

I've looked at the Tiled Map Editor, but I don't know if it is necessary in a simple game like snake. Is it?

I don't know how to make grid however, and I think that the map editor could make a grid easier than by code? I don't know.


texts:
I have written the following function to inter-change 2 specific elements of an array of quaternions:

private void ChangeRotations(Quaternion[] rotationsArray)
{
    Quaternion bone1Rot = rotationsArray [(int)Bone1ID];
    Quaternion bone2Rot = rotationsArray [(int)Bone2ID];

    Quaternion temp = bone1Rot;
    bone1Rot = bone2Rot;
    bone2Rot = temp;
}

But when I use Debug.Log to see if this has taken effect, I realize that the 2 array elements are unchanged.

What am I doing wrong here?


texts: I'm very new to Unity game development, and I am working on a car controller script in C#. What happens to the RPM when I apply brakes to the wheel collider? I do not know how to view the RPM changes.


texts:
Just want to note first I know there are lots of topics on this. I've bought books, read tons of posts here, but still stuck on a few topics from a conceptual level. One of them is concerning how larger online games manage path finding server side when there are lots of actors.
My problem isn't necessarily how to program the path finding when it comes to move NPC from position1 to position2 that's pretty straight forward but if the goal is to have as little to no physics done as possible on the server side I'm stuck on: How do larger games manage pathfinding for lets say NPC's chasing players?
We know the following:

Mobs will only chase x distance
While not chasing players the mobs normally have a predefined path to follow so the server doesn't have to calculate that nonstop.
If no players are around the calculations can stop and free that resource up.

Most of my server side code is easily managed without the need of running the client exe. Is it normal to lets say have a cluster of servers that does nothing but manage pathfinding for certain areas of the world? So for example the server exe would communicate to the client exe(sitting on a server) I need to move npc from current position (x,y,z) to the current player position of (x,y,z) calculate my path. The client does this, respond to the server.exe request, this is then shared with the player clients?
I guess the same could be said for players themselves. If we need to validate their movements are accurate we need to know that they were able to move to x/y/z coordinates by checking it against a client somehow? The only other option I can think of is that somehow these companies are exporting their navmesh in some format that the server exe can look at and run calculations against.
I hope one of y'all out there smarter then me will be able to see where I'm getting hung up on.


texts: Why is my player still moving down when I set its gravity to 0?

texts:
I'm writing Lode Runner like platformer game. I'm trying to solve player sprite slowly moving down when on ladder by setting player.body.gravity.y = 0. I have arcade physics gravity y set to 900 in game config. But game gravity settings seems to override player.body.gravity settings.

I even log player.body.gravity.y to console. It shows 0 when player is on ladder. But it still slowly moving down.


texts: Unity Animation (2D) - Cannot drag sprite into animation

texts:
I am trying to create animations for my sprite which are configured to the "Multiple" option. When I try to drag the sprite into the timeline for the animation it won't do anything. It will just go back into the folder like nothing happened. I don't know if this is normal or there is a problem.
Thank You.
EDIT - First I created a 2D animation, I gave it a name, docked and locked the animation then tried to drag the sprite into the timeline and didn't let add components nor drag the sprite i spliced.


texts: Error when trying to use VBO "array vertex_buffer_object must be disabled to call this method"

texts:
EDIT

I have effectivley re-wrote this question in order to greatly imrpove its quality - see revision logs if you must

I have narrowed down my problem to the initialisation phase of my program, when I am trying to create my vertex buffer. The code that I am currently using is...

vaoID = new int[1];
gl.glGenVertexArrays(1, vaoID, 0);
gl.glBindVertexArray(vaoID[0]);
vboID = new int[1];
gl.glGenBuffers(1, vboID, 0);
gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, vboID[0]);
FloatBuffer vData = FloatBuffer.allocate(vertexData.length);
vData.put(vertexData);
vData.rewind();
gl.glBufferData(GL4.GL_ARRAY_BUFFER, vData.capacity() * (Float.SIZE / 8), vData, GL4.GL_STATIC_DRAW);
gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, 0); // With out this line my code throws the exception
gl.glEnableVertexAttribArray(0);
gl.glVertexAttribPointer(0, 4, GL.GL_FLOAT, false, 0, null); // This is the line where the exception is thrown
gl.glBindVertexArray(0);

So yes, at present my code is able to run with out crashing, but it must have a mistake some where as I am not able to get this to render. For the buffering the index data, I use this code, which does complete successfully when it runs

gl.glGenBuffers(1, bufferIDs, 0);
gl.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, bufferIDs[0]);
ShortBuffer iData = ShortBuffer.allocate(indexData.length);
iData.put(indexData);
iData.rewind();
indexCount = iData.capacity();
gl.glBufferData(GL4.GL_ELEMENT_ARRAY_BUFFER, indexCount * (Short.SIZE / 8), iData, GL4.GL_STATIC_DRAW);
gl.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, 0);

Then when it comes to drawing, I perform the following steps, and I don't think this really matters, as I am sure I am still not buffer correctly in the first place

// first I bind my VAO
gl.glBindVertexArray(vaoID[0]);
// then bind, draw, unbind the index buffer
gl.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, bufferIDs[0]);
gl.glDrawElements(GL4.GL_POINT, indexCount, GL4.GL_UNSIGNED_SHORT, 0);
gl.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, 0);
// finally I unbind the VAO
gl.glBindVertexArray(0);

I am fairly sure that this is the correct process for rendering buffered geometry. I have confirmed that my shader code is correct and valid by use of some immediate drawing commands, so I do I have full pipeline, it just seems I am not feeding data into it. As a point of interest, I also tried editing my vertex shader to set all points to (0,0,0,1) so that if any points where being passed in, I should see them, but this did not work, which I took to mean that I am not passing data into my shader in the first place.

Thanks for all the help so far.


texts: Tile Based Sprite Collision With Lots of Sprites

texts:
I am running into lag when loading many sprites onto the screen. If I have less than 12 on the screen it runs smoothly until I add a couple more and then it bogs down.

I currently have this as my detection code;

public void Collision(Sprite sprite, Rectangle newRectangle, bool passable, bool speedRestricted, int xOffset, int yOffset)
        {// Tile boundaries
            if (sprite.Bounds.Top(newRectangle) && passable == false)
            {
                animation.Position = new Vector2(sprite.Position.X, (newRectangle.Y - sprite.Bounds.Height));
            }
            if (sprite.Bounds.Left(newRectangle) && passable == false)
            {
                animation.Position = new Vector2((newRectangle.X - sprite.Bounds.Width), sprite.Position.Y);
            }
            if (sprite.Bounds.Right(newRectangle) && passable == false)
            {
                animation.Position = new Vector2((newRectangle.X + sprite.Bounds.Width), sprite.Position.Y);
            }
            if (sprite.Bounds.Bottom(newRectangle) && passable == false)
            {
                animation.Position = new Vector2(sprite.Position.X, (newRectangle.Y + sprite.Bounds.Height));
            }
}

It is called in like this;

foreach (var tile in map.CollisionTiles)
        {
            player.Collision(player, tile.Rectangle, tile.Passable, tile.SpeedRestricted, map.Width, map.Height);

            foreach (var sprite in sprites)
            {
                sprite.Collision(sprite, tile.Rectangle, tile.Passable, tile.SpeedRestricted, map.Width, map.Height);
            }
        }

Now collision detection works perfectly so I don't have an issue there it's just when there are lots of sprites in my List<Sprite> sprites does it lag. If I remove the collision detection from the code I can load thousands of sprites onto the map.

Question:
How do I limit the detection area for the sprites so it only compares the tiles around the sprite instead of all the tiles on the map for each sprite.

I have looked through the other questions and found none when it comes to multiple sprite detections for tile maps, just the main player's collision detection.


texts: What is the difference between a Listener and a CaptureListener in LibGDX Scene2D

texts:
According to the documentaton.

Adding a listener : Add a listener to receive events that hit this actor.

Adding a capture listener : Adds a listener that is only notified during the capture phase.

I was not successfully able to find information on this so called capture phase. What is the difference between both listeners? When should I use one over the other?


texts: OpenGL Fragment Shader simulate LCD slow response time

texts:
I have a very simple OpenGL view rendering 2 triangles with a single texture applied. The minimum setup for rendering a 2d game.

What i do is redraw the texture for every frame and easily get 60fps.

I would like to add an effect simulating LCD slow response by outputting pixels that are the average between the current and the previous frame.

The pseudo code of fragment shader would look like this

varying vec2 v_TexCoordinate;
uniform sampler2D u_Texture;

void main() {
    gl_FragColor   = (texture2D(u_Texture, v_TexCoordinate) + PIXEL_PREVIOUS_FRAME) / 2;
    PIXEL_PREVIOUS_FRAME = gl_FragColor;
};

Well, i think shaders can't keep a persistent variable like PIXEL_PREVIOUS_FRAME, then i really don't know how to tackle this problem.

Any suggestion?


texts: Unity Photon multiplayer :: check distance between two players

texts:
How to get distance between two player in a photon multiplayer game. Condition is both the player is moving.
I have tried something like this, in my player control script:

if (photonView.isMine)
pos1 = rigidBody.position;
else
pos2 = rigidBody.position;
Distance= Vector3.Distance(pos1-pos2)

But its not working. For a player the pos2 is always (0,0).
Please help.


texts: Cocos2D-iPhone, how does the Game Loop work in Cocos2D?

texts:
Could anyone theoretically explain how the game loop works in Cocos2D and Objective-C?

If you need me to be more specific about what I'm asking, please read on.

I've got a rudimentary understanding of C, pointers, arrays, conditionals, loops, strings, variables, methods, structs etc... procedural thinking makes sense to me.

Cocos2D tutorials tend to introduce Director, Scenes, Layers, Nodes and Actions, then just dive into writing classes and away they go.

I'm missing something: I'm yet to grasp how the Cocos2D game loop operates - I don't know how Cocos2D decides it's time to go render the screen again then wait again for input/events again each frame.

And if there's a lot going on in the classes, how does this game loop interrupt them to say, "sorry guys, gotta render another frame, hold up a bit". Or similar.

What, when, how and where is Cocos2D instigating each "tick" of the game engine to render etc, and how does a game start itself into this game loop environment - and therefore how does one decide to structure classes and messaging activity within this frame work for any given game design?

If you're looking for an example to explain this, please use the original Asteroids game.


texts: How can I do something after an audio has finished

texts: How can I enable the SetActive() property of a game object after the audio has finished?


texts:
Reaching out yet again for a point in the right direction. Specifically, I am casting a simple struct to a void pointer so it can be sent out on the network, but it is cutting off my second variable for reasons unknown to me. I am likely looking right over it, but a significant lack of caffeine is hiding the answer from me. I have found a few similar threads, notably this one, which has been a great help. I am reasonable certain this is a "newbie mistake" or I am overlooking something exceedingly simply. Like most techs, I've become so lost looking for the "big" answer, that I'm likely overlooking the "small" answer (i.e. 'did you plug it in first?').

Any input is appreciated, so thank you in advance!

/* struct provided */
struct Login_Struct
{
/*000*/ char username[32];
/*032*/ char password[64];
/*096*/
};

void NetWrapper::sendLogin(std::string user, std::string pass)
{
    // ensure size constraints are met
    if( user.length() > sizeof(Login_Struct::username)-1
    ||  pass.length() > sizeof(Login_Struct::password)-1) { return; }

    std::string hashPass = Security::strSHA256(pass); // returns hashed password

    Login_Struct login; // empty struct
    strncpy(login.username, user.c_str(), user.length()); // i.e 'bob'
    strncpy(login.password, hashPass.c_str(), hashPass.length()); // hashed password (64 char)

    char* pData = new char[sizeof(Login_Struct)];
    memcpy(static_cast<void*>(pData), static_cast<void*>(&login), sizeof(Login_Struct)); // serial data for sending
    m_network->send(pData, OP_Login); // Network::send(char* d, short opCode)
    delete pData; pData = nullptr; // cleanup
}

Additionally, debug output looks like this (omitted from code for readability, can supply if needed/requested):

NetWrapper::sendLogin: Login_Struct Dump [bob] (bob), [5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8] (password)
DEBUG: username maxlength [32], user length [3]
DEBUG: password maxlength [64], pass length [64]
DEBUG: pData [x=�i=], [0x7ffc5e4fd0e0], sizeof(Login_Struct) [96], sizeof(login) [96]
NetWrapper::sendSerialized: New pData! pData [x=�i=]
NetWrapper::sendSerialized: Post memcpy! pData [bob]
Network::send : Sending [d0c8504000100bob] ## ignore characters preceding "bob"


texts: Integrating Moonsharp with Unity for Nintendo Switch project

texts:
Has anyone tried to run Unity project with integrated Moonsharp on Nintendo Switch? Can it be done? Are there any significant performance issues due to running Lua scripts?

EDIT: Sorry, I wasn't clear enough about my intentions. I'm working on small project in my spare time and I was wondering if I could try to port my game to Nintendo Switch in future.

The problem is, I don't have my own switch sdk right now, so I can't simply check if integrating Moonsharp is even possible in such scenario. I would like to hear if anyone tried compiling unity project with moonsharp on switch and succeed, or should I look for another runtime scripting engine. I worked with switch SDK in past and I remember that compatiblity issues were real pain.


texts:
I'm trying to increase the difficulty of the game over time. I'm using InvokeRepeating to spawn enemies and in the update function I calculate the next spawn time using the following code:

public Vector2 secondsBetweenSpawnsMinMax;
float nextSpawnTime;

void Update()
 {
    if (Time.deltaTime >= nextSpawnTime)
    {
        float secondsBetweenSpawns = Mathf.Lerp(secondsBetweenSpawnsMinMax.y, secondsBetweenSpawnsMinMax.x, Mathf.Clamp01(Time.time / 60));
        nextSpawnTime = Time.deltaTime + secondsBetweenSpawns;
    }
 }

public void StartNewGame()
{
    InvokeRepeating("Spawn", 0.1f, nextSpawnTime);
}

public void Spawn()
 {
    Vector3 enemySpawnPos = spawnPoint.position;
    Instantiate(enemy, enemySpawnPos, Quaternion.identity);
 }

I'm fixing the secondsBetweenSpawnsMinMax.y to 3 and secondsBetweenSpawnsMinMax.x to 1. The issue I'm facing is that the nextSpawnTime doesn't change. It starts at 3 and stays at that value when it should go down to 1. I'm not sure what's wrong with the code here.


texts: How to generate tile based natural looking map?

texts:
I have a tile based map which I generate using interpolation of pixels on a reference bitmap into appropriate tiles depending on the color of the pixel.

I'm trying to make the output look natural in which blocks of similar tiles look like they are forming a single entity as in the following image:

While my version only puts static sprites onto aligned cells, the second image  takes forest tiles and smashes them together like a whole single forest.
The same is done for the water area.

Could someone explain or point me somewhere where I can learn how to make the result of the first image look like the second? Thank you

Also, how are the seamless road connections done in the above image?


texts: How to animate material change to get a status bard effect, in unity

texts:
Imagine a long cube, like a bar, that has a dark material, and you want to animate changing its material to a light material, but do it gradually from one end to the other, like filling up a tube, or like a progress bar that fills from one end to the other.
Is there a way to achieve this in Unity?
Or do you need to generate the animations in Blender or similar and control them in unity?


texts:
player.vx = scroll_speed * dt

/* Update positions */
player.x += player.vx
player.y += player.vy

I have a delta time in miliseconds, and I was wondering how I can use it properly. I tried the above, but that makes the player go fast when the computer is fast, and the player go slow when the computer is slow. The same thing happens with jumping. The player can jump really high when the computer is faster.

This is sort of unfair, I think, because.

Should I be doing this someway else? Thanks.


texts: Cannot distinguish depth in an isometric cube

texts:
I am having a problem with distinguishing different depths in my new 'game.'
It is a game similar to Minecraft, only it is rendering in isometric format. The problem is, I cannot think of a way to distinguish the different depths.
Screenshots:
Above Ground:

Under Ground:

In the last picture, the player is 2 tiles underground, but it seems as if it's only 1 tile underground.
I'm not sure if this is even possible or not, but if you can think of something, please share it!


texts: How do I prevent tile tearing effects when using pixel art in XNA/MonoGame while keeping the low velocity of the player?

texts:
Most of my Texture2D are pixel art, meaning they're rather small, so my player/character's position has to change using decimal points to keep a realistic movement that matches its walking animation.

But the problem comes when I use my 2D Camera class (using a transformation matrix) to follow the player's position with a scaling/zoom multiplied by 4 (to enlarge all the art). It ends up causing some of the tiles to offset or extra pixels to appear in source rectangles which don't belong in the tile:

Tileset used:

And these are the extra pixels that don't belong in the source rectangle that start appearing when the camera moves with the player:

I realized later that the camera position works better when using int values over floats, but not having it use floats makes the movement of the camera very rigid when zoomed in that much.

So to restate my question, how can I prevent these extra pixels from appearing while keeping the slow velocity of the player to look smooth, all while keeping the camera position fixated on the player?

Edit -- This image shows the few extra lines that gets drawn when they shouldn't when the camera's position is at specific coordinates:


texts:
I'm currently designing a rough prototype of a mecha fighting game.

These are the basics I came up with:

Multiplayer (matchmaking for up to 10 people, for now)
Browser based (HTML5)
2D (<canvas>)
Persistent (as in, players have accounts and don't have to use a new mech each time they start a match)
Players earn money upon destroying another mech, which is used to buy parts (guns, armor, boosters, etc)
Simplicity (both of the game itself, and of the development of said game)
No "leveling" (as in, players don't get awarded with XP)

The last part is bothering me. At first, I wanted to have players gain experience points (XP) when destroying other mechs, but gaining two things at once (money and XP) seemed to be in conflict with my last point, which is simplicity. If I were to have a leveling system, that would require additional development. But, the biggest problem is that I simply couldn't fit it anywhere! Adding levels would require adding meaning to these levels, and most of the things that I hoped to achieve could already be achieved with the money mechanic I introduced. So I decided to drop leveling off completely.

That, in turn, removed a fairly popular and robust mean of progression in games from my game (not that I would use it well anyway). Is there another way of progression in games, aside from leveling and XP points, that wouldn't get rendered redundant by my money mechanic, would be somehow meaningful (even on a symbolic level), and wouldn't be in conflict with my last point, which is simplicity?


texts: Instantiate a GameObject in front of (snap to grid) my character

texts:
In a 2d top-down game, what would be the best approach to Instantiate a GameObject in front of my player as he moves around and I, for example, plant a tree.

I was thinking about creating a small trigger-collider that will always be 1 unit in front of my player, then get the Mathf.Round position of the ground-object that collider is currently overlapping, and place the tree there.

However the more I think about it the uglier that solution seems, is there some better way? Performance wise and just design wise. Maybe I could somehow get the wolrdposition of my player, his direction, and the amount of units in front I want to place the object (1), and Instantiate it there. But with this approach I cant check if I already planted a tree in the location, since I dont have a collider. i.e this approach would not know what GameObject is in front of the player.

Is my first approach okay or is there some better way?


texts: What does Polygon2D's polygons property do?

texts:
Godot Polygon2D class has a polygons property of type Array. The documentation -at the time of writing- does not say what it does. Adding something to it makes the Polygon2D disappear. Which I would find hard to believe to be the purpose of this property, not only an Array is excessive, but we have visible for that.
I have found a question on reddit: What does a polygon2D's polygons property do? Which has a single reply saying -among other things- that "it doesn't really do anything".
Is it true that it doesn't really do anything? If it does something, what does Polygon2D's polygons actually property do?

And I can't reply on an archived question on Reddit, so I'm answering here. Yes, this is me answering my own question. again.


texts: Isometric - Do I need to add shade to the sprite images itself, or render shade during runtime?

texts:
So I'm drawing sprites right now for my game world. It's going to be isometric, not rotatable, 2.5 Dimensional. Do I need to add in the shadow to my sprites right now (which would mean to have 5~6 variations of each sprite based on the shadow angle) or do I do that on runtime as the light source changes in the game?

Example: Say I have this drawn from a tileset.

https://imgur.com/a/LMVlD

The horizontal tiles (https://imgur.com/a/2pnK4) are reused on the top part of the wall and the bottom part of the wall. But the south side is lighter on the bottom part of the wall for reasons. I want to know if it's better to make 2 different images or make the color darker through coding. Thank you.


texts:
I have a voxel engine that generates a mesh per chunk and now I want my meshes to be 1 mesh, but if I create them as a single mesh I kind of lose the benefit of chunking the data in the first place.

=Here's what i'm currently getting

I need to remove the gaps, any ideas?


texts: Good game design process for a do-it-all programmer

texts:
I am pretty new in game development - on Android platform and thinking about one-man game development. I know I can't professionally do everything such as graphics, sounds, and music but I think I can worry about them later once I finish its coding.

My current road block is setting up game design process. I've read some books and lecture notes on game design such as A Theory of Fun, and Book of Lenses, but still not sure about the process.

Of course, making game ideas is kind of separate process in long term so I can assume I already have an idea for a game in this question. But for conceptualization, what can I do? I think people usually make a design document and story boards for this. But for android platform, I am not sure design document is necessary - maybe design summary would be enough. In that case, would story boards (or doodles of game screens) be enough for design process? What else do I need to do in the game design?


texts: Where should collision detection logic be placed?

texts:
I am developing a small 2D game engine. The characters have a paint method which currently does the following:

Calculate the new position of the character as per its speed, etc.
Update the collision grid cell **
Draw the character at the new position

** I have created a collision grid to reduce the number of intersection checks

Now the basic algorithm which I have thought for detecting collision is:

For Each Character
    Check intersection with characters in surrounding 8 cells

I can simply place this code in the paint method. But here is the problem I anticipate.

Suppose two characters A and B lie in adjacent cells in the collision grid. Now as per the above algorithm in the iteration of character A it will detect that it has collided with B. In the iteration for character B it will detect that it has collided with A.

But I have an idea that when A detects that it has collided with B, it should inform B that it has collided with A. This would save lot of comparisons when there are more than 2 actors colliding. But I am not sure how to handle this. I think instead of every character checking for its collision, I should check for the collision inside the game loop.

Would this approach be correct? How have you handled this kind of problem? I thought of the collision grid thing myself. Are there any alternatives to collision grid logic?


texts:
I was working on a small game in which you shoot projectiles towards various targets, now I decide to use OnTriggerEnter instead of OnCollisionEnter because OnCollisionEnter adds a slight force to the target during collision and I don't want that(btw, if anyone knows how to fix that, it'd be great), so I had to use OnTriggerEnter instead.

So the problem is that my code works just fine when the target is still or static. But when the target is in motion, sometimes the projectile works just fine as wanted(damages the target and disables itself afterwards) and other times, the projectile literally just moves through the target without causing any damage.

I say "sometimes" because this happens completely randomly.

Here's is my code:

public int m_DamageAmount;
public int speed;

private Rigidbody m_Rigidbody;

private void Awake()
{
    m_Rigidbody = GetComponent<Rigidbody>();
}

private void FixedUpdate()
{
    m_Rigidbody.AddForce(transform.forward * speed, ForceMode.Impulse);
}

private void OnTriggerEnter(Collider other)
{
    if (other.gameObject.layer == LayerMask.NameToLayer("Enemy"))
    {
        ObjectHolders._ImpactFX.Play();
        ObjectHolders._ImpactFX.transform.position = other.transform.position;

        EnemyBrain enemy = other.GetComponent<EnemyBrain>();
        if (enemy != null)
            enemy.Damage(m_DamageAmount);

        gameObject.SetActive(false);
    }
}

Here are other things I've tried:

1) I have changed both the target and the projectile's movements from transform to rigidbody.

2) I have tried changing my game time's Fixed Timestep value from 0.02 to 0.1.

These things did not have any visual effects on it.


texts:
I would like to know what best practices should I do for testing the functionality when a user buy an item/power-ups via Google Play and purchased with real money?

For example, basically, creating a simple test of purchasing and saving an item stored in the inventory during the game using a game money. (e.g. Gil from Final Fantasy series or Zenny from Tron Bonne for the PlayStation 1) I know how to make money purchase update only via game money when I'm programming in Unity3D or Eclipse w/ LibGDX library.

Now, let say I have to create a program that checks the user if actually purchase a power-up items using real money. Next, the system needs to check for online status. If connected, it will simply go to the Google Play dialog and asks the user if he/she wanted to proceed purchasing of items. If yes and the credit card balance is sufficient, then goes back to the game app and check if the boolean returns true, then item that the user is bought will be saved.

Another example is that the amount of real money will be calculated via programming and if insufficient, the user asks to add more real money value by purchasing it via Google Play. If return true, then, the real money value will be reloaded.

This concept is basically needed for game developers. However, is there a safe way to test the real money purchase test stuff without using a credit card value or something before the actual publishing of the game app in Google Play along with this feature? Is there a tutorial, start-up guide, recommendation or something for this? Please, I would like to know how will I start. Thank you.


texts: How to create a material with variable color

texts: I'm new to Unity and trying to create a Carrom game. Since all the White and Black pieces, Queen basically have the same material and physical properties and texture except for their color, I'm trying to create a single material that I could assign to all 3 types of objects but could then set the material color per object type. Can this be achieved in Unity (I'm using 5.3.2)?


texts: noSQL - Is it a valid option for web based game?

texts:
Out of an opportunity and boredom, a friend and I decided to make a web based game. This is the first 'game' I will be making, since usually I program web apps in django.

I've opted to use the same framework for the game, but I am not totally sure about the data storage, since I cannot foresee future requirements and DB related issues. Lately, the noSQL movement is gaining force and I would like to explore that area.

Therefore I have the following questions:

Would a noSQL datastorage (document-based, such as MongoDB) would be suitable for a web-based game?
What are the issues that might arise using a conventional RDBMS, such as MySQL?
How to insurance data consistency amongst users with MongoDB, during gameplay or at timed events, such as cron jobs?

Game overview:
Typical adventure game, with the player fighting monsters and gaining items and such.

Some data is static across all players: items, weapons, potion, maps, etc.
Some data tied to the player: inventory, metrics (stats), progress, etc.
A player might need to know the stats and state of another player
Scheduled tasks will be run at certain time interval


texts:
In full disclosure, I am VERY new to box2D let alone the Java version of it.

I have a box (here of type Hero) that I am trying to move. I did this by trying to apply a force as follows...

private void itterate() {
  Vec2 vec = hero.getPosition();
  hero.applyForce(new Vec2(0, 100), hero.getPosition());
  Vec2 vec2 = hero.getPosition();
  String test = "TEst";
}

The problem I am seeing is this doesn't change the poistion so vec == vec2. I also tried this....

private void itterate() {
  Vec2 vec = hero.getPosition();
  hero.applyForce(new Vec2(0, 100), hero.getWorldCenter());
  Vec2 vec2 = hero.getPosition();
  String test = "TEst";
}

Neither seemed to do what I am wanting. How can I "push" the object toward the bottom of the screen (Increase y)?

UPDATE I tried this as well...

private void itterate(int count) {
    Vec2 vec = hero.getPosition();
    Vec2 vec1 = hero.getLinearVelocity();

    int velocityIterations = 6;
    int positionIterations = 2;

    world.setContinuousPhysics(true);

    hero.applyForce(new Vec2(0, 10000), hero.getWorldCenter());
    world.step(timeStep, velocityIterations, positionIterations);
    Vec2 vec2 = hero.getPosition();
    String test = "TEst";
}


texts:
For non-game applications the model-view-controller pattern is typical where data, logic, and visuals are separated. But for a game how would you architect the game logic and the animation system in this way?

The gut instinct is to just not think about this and jam the 3d model and its animations into the Unit class where there is also the unit attack logic. And then to just to intermix the code that runs the attack logic with the attack animation. But suppose you wanted to keep these animations separated. What kind of design pattern would you use?

Perhaps a way of testing a design to see if its good is to see if it allows reasonably easy replacement. Imagine replacing the the 3d polygonal animation system with a voxel animation system. What kind of design pattern and game architecture would make this easy? Obviously just intermixing the code that runs the attack logic with the attack animation would make this hard.


texts: trying to create a triangle with procedural code

texts:
Using Godot3, I have a camera and added a MeshInstance node to the Spatial node and attached this script. Why am I not seeing any triangle yet?

extends MeshInstance

func _ready():
    var size = 10
    var st = SurfaceTool.new()
    var mat = SpatialMaterial.new()
    mat.albedo_color = Color(1.0, 0.0, 0.0)
    st.set_material(mat)
    st.begin(Mesh.PRIMITIVE_TRIANGLES)
    st.add_uv(Vector2(0, 0))
    st.add_vertex(Vector3(-size, -size,  0))
    st.add_uv(Vector2(1, 1))
    st.add_vertex(Vector3( size,  size,  0))
    st.add_uv(Vector2(1, 0))
    st.add_vertex(Vector3( size, -size,  0))
    st.generate_normals()
    var mesh = st.commit()
    self.set_mesh(mesh)


texts: How can you sync video files with animations within Unity?

texts:
I'm wondering if anyone might be able to offer some advice regarding an issue I am currently facing in trying to sync video files with animations within Unity.

Ideally my aim is to have a video file play whilst an animated camera (exported from blender) moves in sync with the rendered video file. I've nearly got this working, however there is a very slight delay between the two in which at certain points (quick rotations of the camera) the animation lags behind the video.

I have attempted to solve this issue by creating a script in which for every frame of the video, the animation component is accessed and the animation file frame set to its equivalent time with regards to the video player position. To do so I made use of 'animationState.normalizedTime' (mapping the video frame from its current position to a value of 0 - 1, so as to fit within the requirements of the normalized time function).

I'm also trying to make use of 'videoPlayer.frameReady' in order to set the animation with each new frame, with the idea being to try to only set the animator once a new frame is displayed.

The result I'm currently getting is that the animation is linked to the playback of the video, and will match up regardless of speed of playback, however there are parts in which the animation does not match up to the video. These are particularly noticeable when the camera makes a sudden movement, or when it is rotating. My current thoughts are that perhaps this could have something to do with camera easing settings (from blender to unity) or with the animation component settings. I've tried to remove animation compression and keyframe reduction, however am still having these issues unfortunately.

Does anyone have any ideas as to how this might be solved?

I've included my code below :

public class animationSync1 : MonoBehaviour

{

// Animation component
private Animation animator;

// Video player (add via inspector)
public VideoPlayer vp;

// total frame count of video
private float totalFrame;

// current video frame
private float currentFrame;

// animation frame count
private float animationFrame;

// Start is called before the first frame update
void Start()
{

    // Animation component
    animator = GetComponent<Animation>();

    // get total number of frames from video file
    totalFrame = vp.frameCount;

    // start video playback
    vp.Play();

    // begin playback of animation
    animator.Play("Camera_entrance|Camera_entranceAction");
    // set animation speed to 0 in order to set the animation frame point manually in fixed update
    animator["Camera_entrance|Camera_entranceAction"].speed = 0f;

}

// Use of fixed update to call 30 times a second (to try to match up to video and animation playback)
void FixedUpdate()
{

    // get current video frame
    currentFrame = vp.frame;

    // get frame count between 0 - 1 from current video frame
    animationFrame = currentFrame / totalFrame;

    // set the animation position to that of the current video frame
    animator["Camera_entrance|Camera_entranceAction"].normalizedTime = animationFrame;

}

}


texts: Random 2d terrain algorithm for map generator

texts:
I'm new to game development and I need some advice. I'm building a web based 2d random map generator and I wonder which algorithms there are to create such random terrains in a simple matrix as seen in the images below. It would be great if anyone could point me to some terms/algorithms as I have absolutely no clue what to search for.

Note: I'm not interested in depth/biomes - just the generation of those 2d shapes that grow from a starting point.

I tried implementing it in several ways - but all attempts seem rather childish and don't really produce the desired result. First I started with a small pattern like a plus (5 cells) and replicated it always on the edges of the already generated cells. Another way was to define cubes in different sizes and then start to generate big cubes in any direction, after that put medium cubes on some random edges, then again with smaller ones etc.

Any tips are very much appreciated!


texts: Is it possible to use true Blinn-Phong lighting on Unity Android/IOS?

texts: I've noticed that the Unity's Legacy Shaders/Specular shader does not work on mobiles due to the lighting model being incompatible. I then tried using the Mobile/Bumped Specular shader, but this shader does not support non-directional lights. So I tweaked the mobile specular shader to remove the noforwardadd argument, but I noticed that specular highlights are improperly positioned for non-directional lights, even after removing the halfasview/interpolateview argument. Does Unity even support non-directional specular highlights on mobile devices?


texts: How can I prevent seams when attempting to create a skybox for Unity5?

texts:
After following the documentation for how to create a skybox, seams are appearing around all sides of my 6 textures (sorry for faintness of image):

There are no active lights in my scene. What am I doing wrong and how can I prevent this? Any skybox creation methodology suggestions would be much appreciated.


texts: pivot of a 3d model outside its mesh after importing into Unity3d

texts:
as you can see, the pivot is outside my mesh. I want to use the pivot for rotating around, for that I need to set the pivot to the real "rotating point". I know that there's the SetPivot script, but it only works with pivots inside meshes.
This mesh is part of an object which contains several meshes, I created it with Wings3d. The problem appears with .obj  and .3ds as file extension.

1.How can I fix this?
2.Is there a possibility to define a second pivot which can be used in scripts to "rotate around"(maybe a vector3 which can be set in "Designer")?


texts: How to make the inside of a cube accessible

texts:
I have a cube, it is made up of smaller cubes each making the big cube 8x8x8. The cube is the map. The player of the game needs to be able to appraise the entire map and understand it without having to zoom through the inside of the cube since he may need to see opposite ends and interior at the same time.

How can I make this cube easy for the player to access?
Requirements:

Player must be able to see any 2 cubes at the same time, including the interior.
Player must be able to understand depth of cube
Player must be able to click on interior cubes.
Player must be able to differentiate between allied/enemy soldier, and soldier class.

if it helps at all, imagine if the rubiks cube had more cube inside it, obviously in the real world, we have no way to control them, but in a game, how would i allow someone to see and manipulate several at one time. Note: not a realtime game.


texts: Why isn't my BoxCollider2D doing anything?

texts:
I'm trying to make a speech bubble appear when you approach the tutorial board.

The bubble is there and it has its animation states "Appear" and "Disappear"

  Appear is called OnTriggerEnter2D

  Disappear is called OnTriggerExit2D

The collider is on the parent, tutorial board

The animator and script are on the bubble itself.

This is the script I have attached to the bubble, the conditions script.

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

 public class Conditions : MonoBehaviour
 {

     private Animator bubblecondition;
     private BoxCollider2D boxCollider;

     // Start is called before the first frame update
     private void Awake()
     {
         bubblecondition = this.GetComponent<Animator>();
         bubblecondition.Play("Disappear", 0, 1f);
     }
     void Start()
     {
         //bubblecondition.SetBool("Here", false);
         boxCollider = this.GetComponentInParent<BoxCollider2D>();
     }

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

     }

     public void OnTriggerEnter2D(Collider2D other)
     {
         if (other.tag == "Player")
         {
             bubblecondition.Play("Appear", 0, 0f);
         }
         else
         {
             return;
         }
     }

     public void OnTriggerExit2D(Collider2D other)
     {
         if (other.tag == "Player")
         {
             bubblecondition.Play("Disappear", 0, 0f);
         }
         else
         {
             return;
         }
     }
 }

What am I doing wrong? I spent an hour trying to know why.

  I even tried to have the console write a message on collision but it's
  just dead.
  Not only that, but I also tried to make it public and referenced it, still nothing.

Help me see my mistake :)


texts:
I am facing the same problem although the sprite flips but only one time after that it does not flips at all.

Here is the code snippet:

void Doodle::moveLeft()
{
    if(d_Right)
        d_Sprite.setScale(-1.0f, 1.0f);
    d_Left = true;
}

void Doodle::moveRight()
{
    if(d_Left==false)
        d_Sprite.setScale(-1.0f, 1.0f);
    d_Right = true;
}

void Doodle::stopLeft()
{
    d_Left = false;
}

void Doodle::stopRight()
{
    d_Right = false;
}


texts: Why isnt setting the global_position working?

texts:
Previously my items were relative to the player by node hierarchy.  But for items like bombs this is not ideal so i tried to add the items to the world scene, but when i try to adjust the position of the item to the players position it doesnt work and i see the sword in the top left corner of the screen the worlds origin.
Entity Script
func use_item(item):
    var newitem = item.instance()
    newitem.own = self
    newitem.global_position = global_position

    #not setting the position of the item correctly

    newitem.add_to_group(str(newitem.get_name(), self))
    get_node("..").add_child(newitem)

    if get_tree().get_nodes_in_group(str(newitem.get_name(),self)).size() > newitem.maxamount:
        newitem.queue_free()

Sword Script
func _ready():
    type = own.type
    $anim.connect("animation_finished",self,"destroy")
    $anim.play(str("swing",own.spritedir))
    if own.has_method("state_swing"):
        own.state = "swing"

func destroy(animation):
    if own.has_method("state_swing"):
        own.state = "default"
    queue_free()

It seems like it should work but with an engine like godot there could be several reasons why a certain thing is not working.
https://github.com/MonkeyToiletLadder/wendingo
could it be that in my animation player i set the sword positions as key frames and thats why its not working?


texts: Given a plane and a point, how can I determine which side of the plane the point is on?

texts:
Given the point

Vector pos = new Vector(0.0, 0.20156815648078918, -78.30000305175781, 1.0);

and the plane (triangle)

Vector a = new Vector(-6.599999904632568, 0.0, -78.5, 1.0);
Vector b = new Vector(6.599999904632568, 0.0, -78.5, 1.0);
Vector c = new Vector(6.599999904632568, 4.400000095367432, -78.5, 1.0);

I want to get a plane normal pointing in the direction of pos

//Getting plane normal
Vector ac = Vector.Subtract(a,c);
Vector bc = Vector.Subtract(b,c);
Vector planeNormal = Vector.CrossProduct(bc, ac);

//Testing which side of the plane the point is on
double dprod = Vector.DotProduct(planeNormal, pos);
if (dprod < 0)
{
    planeNormal.Negate();
}

But this method is wrong. The resulting planeNormal points in the negative Z direction, so it should not be negated. Is there a best practise for this? Please help me, I fail massively @ math :)


texts:
I have words inside a tween and I need to slow down a tween that is already running and I am using updateTweenData to do so. All running tweens are in an array.

updateTweenData works, but the problem is, when I set the slower speed, words become closer together and when I set the normal speed, words space out.

Here's a jsfiddle that demonstrates the problem.
Just click slower/faster buttons and notice how words behave.

I want just the speed to change and everything else to remain the same.
How can I achieve this?

Best regards.


texts: Unity3d - Find out if current animator animation is playing?

texts:
I need to call a function immediately after animator animation finished playing, I know I could solve this by adding an event to my animation, but I try it without.

How can I find out if the current animator animation is playing?

On normal legacy animations I solved it by writing a coroutine:

public static IEnumerator playAndWaitForAnim(Animation anim, string clipName, Action callback)
{
    anim.Play(clipName);

    //Wait until Animation is done Playing
    while (anim.IsPlaying(clipName)) {
        yield return null;
    }

    //Done playing. Do something below!
    callback();
}

Which I use like this:

StartCoroutine(AnimationHelper.playAndWaitForAnim(
    myAnimation,
    "ToSettings",
    () => {
        Debug.Log ("Finished playing");
    }
));

But how does this work with mecanim animator animations?


texts: How do I make 3d Sprites like Myth did 20 years ago?

texts:
The game that Bungie cut it's AAA chops on: Myth: The Fallen Lords. about 20 years old now.

https://en.wikipedia.org/wiki/Myth:_The_Fallen_Lords

For the time, it had a pretty revolutionary way of doing lots of "3d" characters, hundreds, on screen and interactive at a time.
to accomplish this, basically they use sprites for each character: choosing and skewing each sprite based on the camera perspective to make it appear 3d.

I would really love to read and learn more about how this technique worked, as I think it can still be applicable to modern indie games, but I've never seen this technique used since.
Does anyone know where I could read more on this?

here is a youtube of the game being played, showing the characters: https://youtu.be/PySrgfe6pr4?t=6m2s


texts: calculating the weights for direction vectors to a target

texts:
I have an entity that is allowed to move in a fixed amount of directions. Let's call a the angle between two directions. r is the length of each direction vector. Now the entity wants to head from its current position (x1,y1) to a target (x2,y2) in one of the fixed directions. Instead of getting the direction that the entity should head into, I want to get a weight for all directions that is based on how close the entity gets to the target with that direction, so that I can combine those weights with other things like avoiding some direction for example.

I thought about calculating the distance from the new positions to the target and then use the closest distance (the one in which the entity heads in the direction directly to the target) to get a weighting from 1 to zero for the other directions.

Now I was wondering if there is some other way to get the weights without having to calculate the distance for each direction. Maybe there is some sort of relation between the angle from the ideal direction and the distance that could be used to calculate the weights instead? So far I've figured out that at least there is no no linear relation between the angle and the distance.

Here is an image to hopefully clear things up a bit:


texts: How or why are major video games programmed so reliably?

texts:
It seems like every five minutes, you come across yet another installer which fails to install certain components, another .NET application that throws up an unhandled or semi-unhandled error message, a web site whose links are broken or whose JavaScript doesn't work with the most recent IE, popular apps and Flash games that freeze on occasion, etc.  Time and again you come across programs that, though they work most of the time, you will come across occasional serious errors with them, wherein they are either dead in the water or close to it.

I remember seeing a lot of glitches back in the NES days, but since around the early- to mid-90's, major video games seem to have been mostly free of things like this.  I know there are exceptions, but basically unless you are really trying to perform some sort of hack you read about online, you just don't see any issues with them freezing, throwing unhandled exceptions, or doing anything else like that.  At worst it tends to be tiny, momentary graphical anomalies that don't really matter.

In other words, major video games seem to be built to a much higher standard in reliability than most other things out there, aside from development software, despite the fact that they tend to be very large and complex pieces of software - often written in C++, no less.  You just do not have the same sorts of problems with them that you do with software in other fields.

Why?  How?  I know this could just be a result of quality control, plus just using programmers who were at the top of their class, but I've grown doubtful of this.  To me, it seems like even these measures would not ensure consistently more reliable software in situations in which it should be much less reliable.  Are people really just doing their jobs that much better, or is there something more to the picture here (such as a business practice or a development technique that these companies tend to employ)?

I know that this isn't the most scientific question out there, but I still want to make sure I'm not just missing something.  Thanks.


texts: Trying to increase the size of a sprite when it touches a pellet in Unity with C#

texts:
This is my first game, and I'm trying to keep it simple, so just a simple platformer that works around the size of the player's character, and the character increases in size whenever they consume a pellet. I have the character's basic movement down, but I'm coming across some errors that I'm not so sure how to fix.

The way I have it set up is that I have a script attached to an empty object called 'LevelManager' that will execute actions once it's called upon (Like 'Respawn Player' and 'Grow Player'), there is a 'Pellet' script attached to the pellet that basically calls upon the 'Grow Player' function when the player touches the pellet's collision box.

LevelManager.cs

public class LevelManager : MonoBehaviour {
    public GameObject currentCheckpoint;
    private PlayerController player;

    // Use this for initialization
    void Start () {
        player = FindObjectOfType<PlayerController> ();
    }

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

    }
    public void RespawnPlayer()
    {
        Debug.Log ("Player Has Respawned");
    }
    public void GrowPlayer()
    {
        Debug.Log ("Player Has Grown");
        player.transform.localScale += new Vector2(0.5, 0.5);
    }
}

Pellet.cs

public class Pellet : MonoBehaviour {
    public LevelManager levelManager;

    // Use this for initialization
    void Start () {
        levelManager = FindObjectOfType<LevelManager>();
    }

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

    }
    void OnTiggerEnter2D(Collider2D other)
    {
        if (other.name == "Player")
        {
            levelManager.GrowPlayer();
        }
    }
}

Also, I'm sorry I don't have the exact errors with me, something funky happened with the editor and I'm unable to locate the window for the compile errors anymore, and when the bug report I sent get's responded to, I'll add that in to make this an easier problem to tackle.


texts:
I'm developing an app (XNA Game) for the XBOX, wich is a pretty simple app.
The startpage contains tiles with moving gif images.

Those gif images are actually all png images, wich gets loaded once by every tile, and put in an array. Then, using a defined delay, these images are played (using a counter wich increases everytime a delay passes).

This all works well, however, I noticed some small lag every x seconds in the movement of the GIF images. I then started to add some benchmarking stuff: http://gyazo.com/f5fe0da3ff81bd45c0c52d963feb91d8

As you can see, the FPS is pretty low for such a simple program (This is in debug, when running the app from the Xbox itsself, I get an avg of 62fps).
2 important settings:

Graphics.SynchronizeWithVerticalRetrace = false;
IsFixedTimeStep = false;

Changing isFixedTimeStep to true increases the lag. The settings tile has wheels wich rotate, and you can see the wheels go back a little every x seconds.
The same counts for SynchronizeWVR, also increases lag.

I noticed a connection between the lag and the moment the garbage collector kicks in, everytime it kicks in, there is a lag ...

Don't mind the MAX HMU(Heap memory usage), as this is takes the amount of the start, the avg is more realistic.

Here is another screen from the performance monitor, however I don't understand much from this tool, first time I'm using it...

Hope it helps: http://gyazo.com/f70a3d400657ac61e6e9f2caaaf17587


texts: Moving players into same square simultaneously?

texts:
Consider a 2 x 2 grid of squares. A player can move onto a square if:

  no other player wants to move into the square next turn
  no other player has waited and is still occupying the square this turn

I have included the image above to describe my problem.

Players move simultaneously.

If 2 (or more) players try to move into the same square, neither move.


texts:
I'm trying to implement a limited-use slow-mo power into my game using C#, but I can use it infinitely. Why won't my integer go down when my function is called?
using UnityEngine;

public class TimeManager : MonoBehaviour
{
    public float slowdownFactor = 0.05f;
    public float slowdownLength = 2f;
    public int slowmos = 5;

    private void Update()
    {
        Time.timeScale += (1f / slowdownLength) * Time.unscaledDeltaTime;
        Time.timeScale = Mathf.Clamp(Time.timeScale, 0f, 1f);
    }

    public void SlowMo()
    {
        if (slowmos != 0)
        {
            Time.timeScale = slowdownFactor;
            Time.fixedDeltaTime = Time.timeScale * .02f;
            slowmos--;
        }
    }
}

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

public class charcterMovement : MonoBehaviour
{
    public TimeManager timemanager;
    public Rigidbody rb;
    public float forwardForce = 1000f;
    public float rightForce = 100f;
    public float leftForce = -100f;

    // Start is called before the first frame update
    void Start()
    {
        rb.useGravity = true;
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        rb.AddForce(0, 0, forwardForce * Time.deltaTime, ForceMode.VelocityChange);
        //Set Speed To Cube

        if (Input.GetKey("d"))
        {
            rb.AddForce(rightForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
        }

        if (Input.GetKey("a"))
        {
            rb.AddForce(leftForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
        }

        if (Input.GetKey("space"))
        {
            timemanager.SlowMo();
        }
    }
}


texts: Unity 2D animated tiles library: IsSelected variable not working or not present within RuleTileEditor.cs

texts:
I have just tried downloading a library which will allow me to add animated tiles to unity. I have been following this tutorial:http://shadowpeakstudios.com/2018/10/22/unity-tutorial-animated-tiles/
It told me to download this library in order to work the animated tiles: https://github.com/Unity-Technologies/2d-extras
After this the tutorial told me to unzip the library and place it into my assets folder. It loaded into my assets folder and then got the following error:
Assets\2d-extras-master\2d-extras-master\Editor\Tiles\RuleTile\RuleTileEditor.cs(277,26): error
CS1061: 'ReorderableList' does not contain a definition for 'IsSelected' and no accessible extension
method 'IsSelected' accepting a first argument of type 'ReorderableList' could be found (are you
missing a using directive or an assembly reference?)

Does anyone perhaps know why this error is occuring.


texts:
I'm new to the Corona SDK(and I also suck in trigonometry) and I'm trying to achieve this:

Shoot a bullet from the player, towards the direction of the point the user touched, but always with ethe same speed, regardless of how far the touch was from the player.

I have tried several solutions. After some research I saw that I should calculate the angle from the two deltas in degrees, and then use the cos and sin of the angle as the x and y values respectively. But when I try to do so, I get pretty random results.

The closer I was able to get from what I want to achieve was to use the delta variables as the X and Y (multiplied by the speed factor). It worked, but then the speed varied based on how far from the player I touched and I want the speed to be fixed.

Here's my latest code(using sin and cos)

local math, physics = require("math"), require('physics')

physics.start()
physics.setGravity( 0, 0 )

display.setStatusBar( display.HiddenStatusBar )

local screenW, screenH = display.contentWidth, display.contentHeight
local playerX, playerY = (screenW / 2), (screenH / 2)

local player = display.newRect( 0, 0, 30, 30 )
player.x = playerX
player.y = playerY

-- local sinT = display.newText("", 100, 10)
-- local cosT = display.newText("", 100, 30)
local angleT = display.newText("", 100, 70)

local function onScreenTouch( event )
  if (event.phase == "began") then
    speed = 3
    deltaX = event.x - playerX
    deltaY = event.y - playerY

    angle = math.atan2( deltaY, deltaX ) * 180 / math.pi

    -- sin, cos = math.sin( angle ), math.cos( angle )

    -- sinT.text = sin
    -- cosT.text = cos
    angleT.text = angle

    bullet = display.newRect( 0, 0, 6, 6 )
    bullet.x = playerX
    bullet.y = playerY

    physics.addBody( bullet )

    bullet:setLinearVelocity( math.cos( angle ) * speed, math.sin( angle ) * speed )
  end
end

Runtime:addEventListener( "touch", onScreenTouch )


texts: Under what circumstances will a PIX 'Render' be different to the actual 'render'?

texts:
I am trying to implement dual-pass alpha sorting using Ogre material scripts, as part of my debugging attempts I want to compare two PIX captures, but when I attempt to debug a pixel in PIX, previously working 'geometry' is not displayed correctly.

My 'reference' blended geometry which works consistently, consists of a simple box with a translucent material, sitting over a set of opaque primitives. In my app this displays fine with the 'smoked' box tinting the objects/pixels behind it.
When I load up my app starting through PIX this continues to work, but once I load a capture taken from this in PIX, it no longer blends the pixels and instead culls them.

I know it is PIX because in the debugger tab, I see the initial value of the pixel I am debugging is the correct blended colour, but the final frame buffer value is the darker incorrect colour - its as if PIX is 're-rendering' the shot and doing it wrong!

Could anyone suggest a reason for this behaviour?


texts: What is the process for porting my game SFML from Windows to Mac

texts:
I've recently finished version one of a simple arcade game I've been making in SFML. I've already spent months on the physics engine and game, and I'm wondering how much time it will take to port it to Mac. I've been developing it using Visual Studio on Windows10.  As far as I can see, this is the only way to do it;

Open Visual Studio on my Mac laptop, download all my windows code

try to compile it, fail, fix all the various stuff that wont work, try to compile again.

I can't seem to find any tutorials indicating a better process, or how long I should expect it to take. It can't be trivial, or else there wouldn't be so many triple-A games that don't run on Mac. I would greatly appreciate any tips on the process or time estimates. Thanks


texts:
I am back with another question about Goal Oriented AIs.

To explain my problem, I will use a specific example.

In my game, population nodes are spawned on a world map, and important characters called "Migration leaders" can spawn, take in migrants, lead them to a good spot, and then establish a new population node there and finally despawn as they have served their one-time purpose.

What I want to achieve is having only one action called "MoveToTarget" which has no pre-conditions apart from having a target location, and has the effect of setting the fact "Reached target location" to true, which itself is the precondition for other actions. Not sure this is the right way to structure that in the GOAP but that's not exactly my problem, at least I do not think so.

My problem is that, since you can't work with actions that take in an argument, I have little notion of how the AI should determine the location which it will move to when the "MoveToTarget" action triggers, for the following reasons :

Depending on the character type and generally what is happening, each character will think differently about where they're interested in going. Furthermore, what happens when I have to interrupt the AI's "plan" for some reason ? The original target location for, say, transporting migrants is lost !
I do not which to make different actions like "MoveToMigrationTarget" because then I'll have to make many MANY more actions, like "MoveToCombatTarget" or "MoveToRessources" and I do not think that will work as that will make me have to keep a "Migration target", a "Combat target".. in memory even for characters that have nothing to do with either of those.

So my question exactly is, where is the AI supposed to do the "practical thinking" in a GOAP ? The Actions themselves must be abstract, and can't take in any argument so I have to somehow have target location(s) in memory and have the GOAP planner know which target corresponds to which action.

I could also extend that question to basically any action that need a specific target / object to work.


texts:
so I am making a 2d canvas game in Javascript and I want the enemy mobs to shoot a bullet every let's say 3 seconds. I'm almost done with the code , i made everything i just don't know how to make the function repeat.

//this is the enemy object
 function Enemy(x, y){
 this.sprite = enemySprite;
 this.x = x;
 this.y = y;
 this.shooting = function(){
    while(enemyBullets <= bulletsPerTick){
        var enemybullet = new enemyBullet(this.x , this.y);
        enemyBullets.push(enemybullet);//i'm adding the bullet object to an array .
    }
    for(var i = 0; i<enemyBullets.length;i++){
        enemyBullets[i].show();
        enemyBullets[i].move();//if there is an element in the array , draw and update the bullet.
    }
}// i left only the important elements of the object needed to answer my question
    //this is the enemy bullet object
    function enemyBullet(x, y) {
    this.x1 = x;
    this.y1 = y;
   this.r = 5;
    this.show = function ()
    ctx.beginPath();
    ctx.arc(this.x1, this.y1, this.r, 0, Math.PI * 2);
    ctx.fillStyle = "black";
    ctx.fill();
    ctx.closePath()//drawing the bullet
}
this.move = function () {
    this.x1 = this.x1 - 5;//updating the bullet
}

In my main file , i have a function draw() which is in requestAnimationFrame(draw):

for (var j = 0; j < enemies.length; j++) {
            enemies[j].show();//here i spawn the enemy sprite
            enemies[j].shooting();//this is the function which adds the bullets to the array , draws them and updates them.
        }

Basically , when i press the start the program now , only one bullet flies and disappears and i want that process to continue over and over again every few seconds , let's say 3 seconds for example , i tried to add enemies[j].shooting() in an interval and timeout but they are in draw, which is in requestAnimationFrame and it doesn't seem to work , if anyone have any clue how to help me I want every advice possible. Also if you need more information about the problem , let me know.


texts:
Ok, so I have my world space canvas attached to the player object. In my script I have a reference like this :

 GameObject myWorldCanvas;

Awake()
{
 myWorldCanvas= transform.FindChild("nameOfObject").gameObject;
}

Then when the right conditions are met I simply activate the object like this :

myWorldCanvas.SeActive(true);

This worked perfectly until I added a animator to the object. If I manually enable/disable the object in the scene the animation works perfectly(it just changes the scale to give it a pop effect), but when the object is activated by my script the animation still plays and changes the scale values but nothing is rendered. In play mode if I manually enable/disable the animation works.

Any ideas ? If you need more info or screens let me know.

Edit : the canvas has some buttons as children and when I mouse over something seems to be refreshed and the images show up on screen.

Edit: Further test have show that manually disabling and enabling the Canvas component also shows the images, but If the canvas and game object are enabled from a script nothing shows up on the screen.

Edit: I solved the problem by disabling the canvas component on the first key of the animation and then enabling it on the second one where the Y scale is set to 0. This seems more like a hack and I dont like it. Does anyone have a idea why this is happening ?


texts: Orientation while rotating around a point

texts:
I am using this formula to rotate around a point.

X := originX + sin(angle)*Size;
Y := originY + cos(angle)*Size;

In cartesian cordinates how would I keep the objects orientation in relation to the origin object as it moves around the origin.  Any one know where I could look for answer to that?


texts: making special blocks in a voxel game OpenGL

texts:
I'm making a voxel game and it looks quite good but then i thought of special blocks like minecrafts grass leaf blocks, and translucent water. I had the idea for the grass blocks to put them in a seperate VAO and render them after the blocks because they might look like an X from above.

How could you do water? I know you could enable blending in OpenGL and render from back to front and you could sort their distances each frame with a map.

My problem is how to render all of these waters, I could use instanced rendering but then i would have to update the buffers every time the player moved or i could draw them all individually but that would involve thousands of draw calls ex. 8000 draw calls for 20*20*20 blocks (each draw call sends a whole cube)

what would be a fast method of doing this?


texts: Game physics presentation by Richard Lord, some questions

texts:
I been implementing (in XNA) the examples in this physics presentation by Richard Lord where he discusses various integration techniques. Bearing in mind that I am a newcomer to game physics (and physics in general) I have some questions.

15 slides in he shows ActionScript code for a gravity example and an animation showing a bouncing ball. The ball bounces higher and higher until it is out of control. I implemented the same in C# XNA but my ball appeared to be bouncing at a constant height. The same applies to the next example where the ball bounces lower and lower.

After some experimentation I found that if I switched to a fixed timestep and then on the first iteration of Update() I set the time variable to be equal to elapsed milliseconds (16.6667) I would see the same behaviour.
Doing this essentially set the framerate, velocity and acceleration to zero for the first update and introduced errors(?) into the algorithm causing the ball's velocity to increase (or decrease) over time. I think!

My question is, does this make the integration method used poor?
Or is it demonstrating that it is poor when used with variable timestep because you can't pass in a valid value for the first lot of calculations? (because you cannot know the framerate in advance).

I will continue my research into physics but can anyone suggest a good method to get my feet wet?
I would like to experiment with variable timestep, acceleration that changes over time and probably friction. Would the Time Corrected Verlet be OK for this?


texts: Will function-local objects affect my performance over time?

texts:
This is a very simple question.

Let's say my render loop runs at 60Hz, in each call to render(), I draw all my game's buildings, characters and scenery to make the current frame ready. Each of these entities are drawn using its own instance of a RectangleShape, which is a class able to render a texture to the screen. (I am using OpenGL but it shouldn't be relevant)

RectangleShape is a class that once allocated, generates geometry for the "sprite" to be drawn, has some properties to configure and then renders itself using OpenGL.

The problem is, for each entity, I am allocating the RectangleShape object, configuring and rendering it inside render(). So, in practice, there are dozens if not hundreds of blocks like this inside render():

// pseudocode
RectangleShape entitySprite;
entitySprite.setSize();
entitySprite.setTexture();
entitySprite.render();

I am aware I have a performance decrease by not using a pre allocated RectangleShape, already configured, which I only call render() on. I know that is the optimal path to go, but my question is:

Will so many allocations/deallocations of RectangleShape (hundreds, 60 times a second) fragment memory over time, decreasing the performance of the whole program? Or can I be safe that despite the performance hit by on-demand allocation is constant and will not degenerate as time passes?

I am not using any kind of custom allocator for anything. Also, please have in mind that the RectangleShape constructor internally resizes a std::vector, which I think implies a heap allocation.

Thanks


texts:
I'm trying to model a star in Unity, and it, sort of works, but it's not ideal. Currently, I'm using a large sphere with a self-illuminating material containing a star texture applied to it's surface, and a spotlight to create the effect of starlight, like this:

While it works, it doesn't look the greatest. I'm looking for an effect more along the lines of how Kerbal Space Program models a star:

How can I achieve this effect?


texts:
I've previously simulated cloth using Verlet integration but couldn't successfully get the cloth to collide with itself in an efficient way. The reason being is because I used a brute force algorithm to if check all the cloth points collided with each other.

My question is how could I efficiently check for collision between the cloth points? I thought of using some sort of tree structure but it doesn't really make sense in my head given that a lot of tree structures largely depend on spatial position or don't actually suit the cloth because they're better suited to static geometry(BSP).

Additional Info: The cloth is logically just a 2D array of points tied together by a constraint. The cloth is affected by wind and gravity and is also anchored in space at the two upper corner


texts: Is it possible to use an image, sound or font without importing them externally? [SDL2]

texts:
It's hard to explain my question, but I will try my best.

When loading sounds, images or fonts in SDL2 (with SDL_image, SDL_mixer, SDL_ttf) you need to load them from an external source path. For example, res/image.png - the issue I have with this is that the user can edit this file which changes the look of the game.

Is there a way in loading the asset internally? (If that's the right term?) So that it cannot be edited by other people.

Thanks.