texts: Make a bullet move towards the mouse position

texts:
Before you give me a link to another post look first, just in case.

So I'm making a top down game where the person can shoot around, I want the bullets to move towards the mouse, I have tried this:

angle = (float) Math.atan2(pmx - x, pmy - y) * 180 / Math.PI;
x += this.getVelX() + (Math.cos(angle * Math.PI / 180) * 15);
y += this.getVelY() + (Math.sin(angle * Math.PI / 180) * 15);

The pmx means previous mouse position where I clicked, and the same for pmy.
But this doesn't work properly look at this screenshot, the gun is pointed towards the mouse (the screenshot doesn't show the mouse) and the yellow squares are the bullets.

How it moves the bullets is the goes towards the mouse about 50 pixels then curls down to the left and inverted for the other side.

After looking at Theraot's post Section B:

int speed = 15;
int velocityX = pmx - x;
int velocityY = pmy - y;
length = Math.sqrt(velocityX * velocityX + velocityY * velocityY);
velocityX *= speed / length;
velocityY *= speed / length;

x += velocityX;
y += velocityY;

This has worked to move it the direction of the mouse, but a new issue has occurred whether this is my issue or not I don't know, as I'm not that good at maths, what it does is moves in the correct direction and when it gets to the mouses old position where it was clicked it stop moving:

If there is a way to stop this from that method can someone tell me if not which Section should I use instead?


texts: How can I change a shader alpha color in script?

texts:
How can I get access to the Main Color and change the alpha color ?
How do I know what is the variable of the main color in the shader code ?

If it's Main Color in the Inspector then this is the parameter I should get in the script "Main Color" ?


texts:
I am trying to implement a game like BBTAN with Unity5, the point I got stuck on is drawing numbers onto the boxes in a proper way. I have done it by adding Canvas and Text elements on each boxes and set the following properties of them in order the fit the text inside to the canvas:

Render Mode: World Space
Dynamic Pixels Per Unit = 1250
Reference Pixels Per Unit = 100

Even though the text fits into the box, its being rendered without antialiasing. And it looks like this (The box is on the right hand side is the Screen Space Overlay Canvas, for comparison purpose):

I have two questions to ask:

Is adding canvas to each block an efficient way? If not how should I implement drawing dynamic numbers (Changing when got hit) onto these boxes?
Is "changing the dynamic pixels per unit" the correct way to achieve this goal? If so, how can I fix this anti-aliasing problem?

Thanks in advance for any help!


texts: Wheels not facing right direction when car faces different directions

texts:
I am creating a real time multiplayer driving game in Unity. I am using google play's real time multiplayer service. I am having an issue where the wheels of the cars that are over the network are not facing the right direction. What I am currently trying to do is just add the calculated steering angle to the current rotation of that particular player's car, but for some reason the wheels face the wrong way and rotate incorrectly if the car is facing certain directions. Logically I thought what I have is correct. Basically for each wheel I use this code:

car.transform.rotation = Quaternion.Euler(0, car.transform.rotation.y + steerAngle, 0);

So I find the rotation of that car and then I add the steer angle to it. Why wouldn't this work?


texts: Perfect fit for isometric tiles in AS3 with BitmapData

texts:
I'm creating a game which uses 320x160 sized isometric tiles. I've got an editor that allows me to take loaded in tiles and plot them. The map size is 8x8, and instead of placing down 64 movieclips, and then moving them around, I thought I'd use the bitmapData.draw function to plot these mc's directly to a bitmap (as I'm not doing anything with them after they are put down anyway).

That works fine apart from there's a small line appearing between the tiles, along the edges. I think this has something to do with anti-aliasing, because when I export the tile as a .png with no smooth, and use that tile in my editor, there's no faint line between the tiles, but that also makes the tile overall look pixely, so I'm at a bit of a loss.

I want the edges to fit perfectly together so need to be pixel perfect, but I want the interior of the tiles to be smoothed, any ideas? unless there's a way to solve this with the bitmapData approach in itself? The only thing I can think of right now is to make the tiles slightly bigger than they need to be so they overlap slightly, but that's a bit of a fudge, which I want to avoid if possible.


texts: Scene dark when perspective camera is far from scenery

texts:
I can't find anything about this subject in the docs or forums to know if this is normal behavior: There seems to be a direct correlation between how close to the scenery my camera gets and how brightly lit the scene is. My camera is able to move up to 200 units from Vector3.zero. Here are two shots of the same piece of scenery - one close up, one far away:

The camera is set to perspective, using deferred rendering.

Things I've tried:

Turning off post processing
Using auto expose in post processing
Changing to orthographic (removes the issue, scene is uniformly bright at any distance)
Changing the FOV
Changing global lighting to use color rather than skybox
Putting some lights at altitude

This may be normal behavior & I just havent noticed before. Can anyone confirm? Is there some way to prevent this happening? I don't want to use an orthographic camera but I do want the scene to be evenly bright at any distance from the camera.


texts: Ball not throw proper direction unity3d?

texts:
I am making a game where the player throw basketball in 3d view but it may not throw proper.So I need ball throw proper on z direction with curve move when player mouse up.

Reference Link

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class BallController : MonoBehaviour
{

 public static BallController instance;

 [SerializeField]
  private GameObject Player;

 private Vector3 touchStart;

 private Vector3 touchEnd;

 private Vector3 screenPoint;

 private Vector3 offset;

void OnMouseUp ()
{
   ThrowBall ();
}
public void ThrowBall ()
{
    touched = true;
    Vector3 pos1 = new Vector3 ();
    Vector3 pos2 = new Vector3 ();
    touchStart.z = Camera.main.nearClipPlane - (.2f);
    touchEnd.z = Camera.main.nearClipPlane - (0.08f);

    pos1 = Camera.main.ScreenToWorldPoint (touchStart);
    pos2 = Camera.main.ScreenToWorldPoint (touchEnd);

    Vector3 v = pos2 - pos1;
    v.z = 0.02f;

    Player.GetComponent<Rigidbody> ().AddForce (v * 600, ForceMode.Impulse);
  }
}


texts: Is it possible to use Unity 3D engine with LibGDX when making Android game apps? Is it also possibly used for making 2D games using Unity 3D and LibGDX? I would like to know if it's possibly applicable in Java programming.


texts: I can't find a way to make my projectile gameobject collide with my ofscreen collider

texts:
so my code on my collider is as followed

public class Collide : MonoBehaviour
{

    private void OnCollisionEnter2D(Collision2D collision)
    {
        Debug.Log("Collision");
    }
}

the projectile has a rigidbody2D and a capsule Collider 2D.

collider has a box collider 2D.

the projectile spawns from my player and moves upwards in the direction of the collider (the collider is large enough that the projectile cant miss it).

the projectile however goes straight through the collider and no message appears and I have no idea why.

what I've tried and made sure of :

both are on the same layer and plane(z axis)
gave the collider a rigidbody but changed nothing
made the collider on trigger and not on trigger
made the projectile dynamic and kinematic
changed collider script to onCollisionEnter and onCollisionEnter2D


texts: Game artist computer workstation set-up – is this overkill?

texts:
I'm part of a small business (so very limited constraints)  working with a very talented, professional game artist and will need to provide all necessary equipment. The artist has asked for the following setup (which to me seems super expensive):

Latest graphics targeted high-end laptop with matching keyboard
Large drawing tablet
Ergonomic mount for the tablet
Vertical ergonomic mouse

Do they really need all of this? Why?


texts: I have got a problem, because I wan't to add collision detection to my 3d game, which I am developing in Java, using the Lightweight Java Game Library (LWJGL). I have googled a bit, and I have found this interesting library, called JBullet, which is a port of Bullet for C/C++. But I can't find any tutorials covering, how to add collision detection to my 3d shapes in LWJGL. Is there any simple way to do it, or please direct me to a tutorial, covering that topic.


texts: For a 2D game on the iphone would I better using OpenGL or CoreGraphics?

texts:
I am planning on developing my first iPhone game, and I was wanting to know whether I should use OpenGL or CoreGraphics for a 2D game.  An outline of the benefits would also be helpful.

Edit: Set this for the community wiki as the answer will be too subjective


texts: Does it require any license to use soccer players and teams names in a paid or free game?

texts:
I would like to know if any license is required to use Fifa registered team names and player names in paid or free games (e.g. Spanish League teams, Messi, Cristiano Ronaldo names etc).

I'm currently developing an interactive soccer game for mobile platforms (iOs and Android specifically) and I was wondering if it there is any legal issue on using this information. I suppose that if I publish it as a paid-app, it is maybe ilegal without a Fifpro License or something like that. But would it be ilegal if I publish the game for free, and charge for special items in the game?


texts: OpenGL ES 2.0: Controlling Transparency in Fragment Shader

texts:
The following is the OpenGL ES 2.0 simple GLSL Fragment Shader, I use to place textures on polygons, to render 2D sprites.

varying mediump vec2 TextureCoordOut;
uniform sampler2D Sampler;

void main()
{
gl_FragColor = texture2D(Sampler, TextureCoordOut);
//gl_FragColor = vec4(texture2D(Sampler, TextureCoordOut).xyz, TextureCoordOut.w * 0.5);

}

The fragment shader places voxels with alpha information taken from the source 2D texutre(.png image). Apart from alpha information, I need to control overall polygon/sprite transparency to achieve Fade In/Fade Out effects.

Could you show me, please, how to modify the above shader to control the overall transparency, besides the alpha information?

Note: The commented out line is used for my attempts to achieve the transparency. I wish to combine both the alpha information with the overall polygon/sprite transparency.

Thanks.


texts:
I'm creating a game that utilizes off center projection. I've got my game set up in a CAVE being rendered in a cluster, over 8 PC's with 4 of these PC's being used for each eye (this creates a stereoscopic effect). To help with alignment in the CAVE I've implemented an off center projection class.

This class simply tells the camera what its top left, bottom left & bottom right corners are. From here, it creates a new projection matrix showing the the player the left and right of their world. However, inside Unity's editor, the camera is still facing forwards and, as a result the culling inside Unity isn't rendering half of the image that appears on the left and right screens.

Does anyone know of a way to to either turn off the culling in Unity, or find a way to fix the projection matrix issue?


texts: How to use multiple textures in OpenGL ES 2.0?

texts:
I am working in OpenGL ES 2.0.

I load two png images as my textures with the libSOIL. I need to use one of them as the texture for the background and another one as the texture of a rotating cube.

In OpenGL ES 2.0, the adding texture operation is in the shader. I don't know how to add the different textures to the different places in a shader. How do I do that?


texts: How can I keep vertex order the same on every Instantiate()?

texts:
While trying to resolve another question, I have discovered that if I Instantiate() from a prefab, the order of the mesh vertices (and therefore triangles) is inconsistent between instances. This is apparent, for example, if I RaycastHit.triangleIndex the same location on the mesh on different runs of the game. The same location returns the same triangle index during one run of the game, but a different triangle index in the next run.

If instead I add the model to the scene in the editor, and then run the game, the same location returns the same triangle index in every run of the game. If I duplicate the model through the scene editor, the duplicate also returns the same triangle index. This is the behaviour I am aiming for.

However, I would obviously prefer to Instantiate at runtime. (This would allow me flexibility on when and how many models to instantiate, and in the long run I want to add other models too. The alternative is to add the model to the scene and create a large number of "offscreen" duplicates, which seems prone to inefficiencies on multiple fronts.)

Is it possible to use Instantiate and maintain a consistent vertex/triangle order between instances and between runs of the game?


texts:
Hi I'm trying to get my enemy to fire once every few seconds, I tried using a Coroutine but due to me essentially calling the Coroutine through the update method, the Coroutine is repeating every frame update and spamming the shoot key. What is a solution for this?

void Update () {
        Shoot ();
}

public void Shoot(){

        StartCoroutine ("ShootContinuous");

}

public IEnumerator ShootContinuous() {
    yield return new WaitForSeconds (1);
    anim.SetTrigger("Shoot");
    Instantiate (Bullet, firePoint.position, firePoint.rotation);
    isShooting = true;
    yield return new WaitForSeconds (1);
    anim.SetTrigger("NoShoot");
    isShooting = false;

}


texts:
I am trying to create a WebGL plugin and I read in the docs here:
http://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html

But I'm not sure I understand.

I created a file in Assets/Plugins/WebGL called DomPlugin.jslib:

var DomPlugin = {
    ReadFromDom: function()
    {
        var mapStr = document.getElementById('my-elm').innerText;
        var buffer = _malloc(mapStr.length + 1);
        writeStringToMemory(mapStr, buffer);
        return buffer;
    }
};
mergeInto(LibraryManager.library, DomPlugin);

Within one of my C# scripts, I created a method declaration like so:

[System.Runtime.InteropServices.DllImport("__Internal")]
private static extern string ReadFromDom();

Then I call this external method like so:

private string ReadData()
{
    if (Application.platform != RuntimePlatform.WebGLPlayer)
        return testData.text;

    return ReadFromDom();
}

My WebGL Template page has an element with ID my-elm defined above %UNITY_WEBGL_LOADER_GLUE%

When I deploy I find this error:

Invalid function pointer called with signature 'ii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)


texts: Entity component systems and DDD: violation of encapsulation?

texts:
I'm using a hybrid of DDD (domain-driven development) and an entity-component system. That is to say:

I have an Entity class with a list of Components, and the ability to add/remove/get components
I have component instances like HealthComponent (health and is-alive), DrawComponent (position + display), etc.
System instances (like DrawSystem) that find a bunch of components and operate on them

I also have "domain objects" like Player and Monster, which subclass Entity. Their constructors usually add a bunch of components.

Since I'm a fan of the DDD idea of objects represent business/game entities, I model my classes around that. For a roguelike, my Player class has methods like:

Attack(Monster)
GetX and GetY (delegates to the position component)
LevelUp
RegenerateHealth
And others

It seems to me that the components are a white-box internal detail; they shouldn't be known to any outside objects. In fact, domain objects should operate on other domain objects (eg. Player.Attack(Monster)).

Most (if not all) of my actual game code operates on entities, not components. My tests usually do something like:

Create an entity
Grab a certain component
Verify that it meets expectations

In general, this raised a question in my mind: isn't this a violation of encapsulation? Aren't components just an internal implementation detail of entities (that could change or disappear at any time)?

On the other hand, I have a lot of delegation, which seems useless (like Player.getX() is just Player.get(DisplayComponent).getX()).

This seems confusing. Can someone provide some clarity? What is the right mix of DDD, encapsulation, and entity/component composition?


texts: A* only for horizontal / vertical movement

texts:
anyone can share a link for a tutorial or article about optimizing A* for horizontal / vertical movement (no diagonal). Is not as easy as change the G values to 10 everytime.

Thanks


texts:
Hi i have some questions :

How to properly delete unused asset ?

I have an unused game object and i want to delete it together with its material/texture. I can select it and RMB select dependencies , but i can't delete them all because some of these selected textures is being used by other object. So i have to manually check them one by one. Is there any other faster method ?


texts: Entity Component Architecture - initialization between multiple components

texts:
I'm starting work on an game set in an isometric world, and I'm having a bit of trouble understanding how to implement certain aspects of the entity component system idea.

Here are the Components and Systems I have so far:

WorldData (only one ever used, contains map and cell sizes)
Camera (currently also only one ever used, though that could change I guess)
WorldPosition (just contains X and Y values, in world space)
Renderable (contains the image to draw, screen position values + offset, and a depth)
Floor (contains the type of flooring and a walk speed)

Now If I create an entity with WorldPosition, Floor and Renderable components, where do I put the logic to enforce certain rules. For example, if Floor.FloorType is set to 'Grass', I want the image in the Renderable component to be set to 'floor-grass.png'. Should this go in something called 'FloorSystem', which checks every entity that has a Floor and Renderable component and updates them? And if so, do I need some sort of 'dirty' flag on Floor to say when it has changed, so that FloorSystem knows to update it and is not updating every floor tile in every frame? Or do I instead create a 'Dirty' component which I attach to that entity when it changes?

Any guidance would be much appreciated! I love the general elegance of this architecture and I think it will work well in my game once I get a better handle on it.


texts: Best way of passing game data in functions?

texts:
In most programs, if we want to do something to, say, Bob, then myFun(bob) is enough. We know that the function deals with Bob and won't touch Alice.

However, in a game, everything wants to freely interact with everything else:

Option 1

killTime(bob){
  cat=bob.getNeighbor().getPet();
  bob.talkTo(cat);
}

We are forced to have every piece of data hold reference to each other. Web-shaped dependency is hard to maintain, hard to serialize. Chained dots don't look nice, either.

Option 2

killTime(bob,neighborList, petList){
  alice = neighborList.findNeighbor(bob);
  cat = petList.findPet(alice);
  bob.talkTo(cat);
}

The argument list can get long, and it is not clear what should be included. What if we want Bob to read his poem written in his notebook hidden in his drawer?

Option 3

killTime(world, bob){
  cat = findTheCatYouLike(world, bob);
  talkTo(world, bob, cat);
}

Bob could do anything to world in his small talk, not necessarily a bad thing in a game. But it doesn't feel right passing the same world to every function. Also, if we use C, then we are forced to have pointer members instead of data in world, just to reduce the compilation time of #include "world.h"

I don't think any approach I found is good. What would be the least bad solution in this situation?

================== edit ================

To elaborate my question, suppose that we have a RPG system, with world map, characters with HP, MP, so on. Now we want a simple player.walk function. position+=velocity straightforward? Not really. What if we want footprints on map? What if we deal damage to units we pass by? We now need to touch everything in game to in order to walk.

In most programming scenarios, it is assumed that function and data are coupled to each other. Only these functions work on these data, and only these data are used for these functions. Put the functions and the data into a class, and it's high cohesion.

I am looking for an architecture where the opposite is true. I have a bunch of data (hp, mp , pos, vel), a bunch of actions (walk, attack, wait). That is all I can be certain of. I want the flexibility to change my mind everyday how the actions affect the data. In my code, I actually started with option 1 and gradually slid into option 3.


texts: 2D engine that uses Flash Platform classes?

texts:
I want to develop a 2D game for Android, but, I want to use Flash Platform's framework APIs, ex: Sprite, Shape, Graphics, Bitmap .. etc as I have already wrote my game in AS3 ..

Is there a 2D engine for Android that uses Flash Platform's framework APIs?

If not, does Unity use Flash Platform's framework APIs?

I know that I can Adobe AIR to port the game to android, but, I want it a native code based to avoid Adobe AIR player as a requirement ..

Any guidance?


texts: Errors when calling functions from File class?

texts:
When I try something like File.Delete("Assets/a.txt"); it gives me a error saying

  Unknown identifier: 'File'.

In Unity Documentation https://docs.unity3d.com/ScriptReference/Windows.File.html
it gives an note saying "this class is only available when targeting Universal Windows Platform." What does this mean?

In top of unity documentation it says File is a class in UnityEngine.Windows

So I tried Windows.File.delete("Assets/a.txt").

Now the error changed to

  Language feature not implemented: UnityEngine.Windows.

What is it I am doing wrong?


texts: Must I display Health and Mana to the player?

texts:
I'm thinking of doing one or more of the following:

hiding the player's Health
hiding the player's Mana
hiding the player's Health from other players
hiding the player's Mana from other players

I don't know of any game that has done such things before so I'm wondering if this will have a positive effect on the players and why no game has done so before.


texts: I've seen some varying tick rates used for RTS engines. Supreme Commander ran at a super-low 10 ticks per second. Is this normal for RTS engines, or do they normally have a higher tick rate?


texts: What is the easiest and fastest way to display an SDL_Surface in a window with SDL2?

texts:
I would like to have an SDL_Surface representing the contents of the window, just like in the old days with SDL1.2. What is the best and fastest way to do it in SDL2?

What I found is that I need an SDL_Window, an SDL_Renderer for that window, an SDL_Texture to render, and an SDL_Surface to create a texture from. This seems a bit too much to me, since I just want to display a single image on the screen.

Not to mention the impact on the performance. On my machine (Lenovo Y510p laptop) this whole procedure takes 9ms, without any memory allocation, only using pre-allocated variables and totally black SDL_Surface.

Is there a way I could speed up things?


texts: Controlling resolution in Unity 3D. Beginner's problems

texts:
i started working on developing games one month ago. I really like it, although it isnt easy.

The problem i have now, is with display resolution after i build game. So far i have been working with 2D Space Shooter game (getting help from the tutorial), everything is working smoothly. The only thing that i hardly understand is the resolution, aspect ratio thing. I have made a game that looks like this:

I have drawn a gizmos around the allien formation, and written a script with some calculations that everytime formation hits the edge, it goes to the other edge, hits the other edge, and goes to the other edge, and so on and on. In the free aspect movement looks great, but however, then i change the resolution to any other, movement is stuck, or it barely moves.

Now here is my question. What should i do, to make the game look and work smoothly on every resolution like it works on the free aspect display? I tried to change formation height and width and so on, but i assume this is not an option.
I will add my formation controller script as well(it contains several other things so i printscreened only the code that helps formation to move):

Thank you for your time, and sorry if you can't understand everything or something is unclear to you, i'm beginner at game development and English is not my first language.


texts:
Right now I am trying to make a 2d collision response system for a platformer, and the algorithm I have for it works quite well. The only problem is that if the player is standing exactly on a tile, he cannot move. I think this is related to the fact that the manager is checking if he is colliding on the X axis, instead of the Y Axis.

I have thought of making one big AABB for a check, using all applicable tiles, but I feel as if there is a simpler way. I don't really understand normals, so I have not tried anything with them yet.

Right now, I am getting the centers of both objects, the distance inbetween them, and the minimum distance between them, returning the overlap. And then applying the overlap to the players position. It looks like this

sf::Vector2f centerA(
  AABBFirst.left + (AABBFirst.width  / 2),
  AABBFirst.top  + (AABBFirst.height / 2));
sf::Vector2f centerB(
  AABBSecond.left + (AABBSecond.width  / 2),
  AABBSecond.top  + (AABBSecond.height / 2));

sf::Vector2f distance(centerA.x - centerB.x, centerA.y - centerB.y);
sf::Vector2f minDistance(
  (AABBFirst.width  / 2) + (AABBSecond.width  / 2),
  (AABBFirst.height / 2) + (AABBSecond.height / 2));

return sf::Vector2f(
  distance.x > 0 ? minDistance.x - distance.x : -minDistance.x - distance.x,
  distance.y > 0 ? minDistance.y - distance.y : -minDistance.y - distance.y);

I apologize if this question has already been asked and answered before, I have not found the proper terms to search for.


texts: How can I disable Unity's default cursor functionality?

texts:
Not too sure how to ask this, I'll try my best.

Currently, I'm working on a First-Person Controller. I'm adding functionality for a pause menu so that when you press escape, it will open the pause menu, unlock the cursor, and make it visible. If you press escape again, while the pause menu is open, it will do the opposite: hide the cursor and lock it again.

The problem I'm running into is that Unity already kind of does this. It doesn't matter if you're in the editor or if your game is built: whenever you press escape, it will unlock the cursor and show it, so you can exit the game (in a built application) or get out of play mode (in the editor).

I'm 99% sure this is Unity's default functionality. I have looked in Unity itself and haven't found a way to turn it off, and I have also looked online. Any help would be greatly appreciated.


texts: Can't Create High Definition Render Pipeline Asset in Unity (Create > Rendering Doesn't Exist)

texts:
I've upgraded my project to Unity version 2019.3.0a11. It complains and can't load scripts, mostly because it can't seem to load the original HDRPipeline. I want to make graphics display properly.

In Unity's instructions, they say to go to Assets > Create > Rendering and click High Definition Render Pipeline Asset and create this in the Assets folder. Problem is, Assets > Create > Rendering doesn't exist.

I'm in Assets/Settings
I upgraded the High Definition RP, Post Processing, and Core RP Packages
Restarted Unity many times
Searched for a suitable asset

Here is what the package manager says:

There is an exception thrown in Unity about Shader error in HDRP/Lit: failed to open source file: 'Packages/com.unity.render-pipelines.core/ShaderLibrary/Version.hlsl' at /…/Library/PackageCache/com.unity.render-pipelines.high-definition@7.0.0/Runtime/ShaderLibrary/ShaderVariables.hlsl …

In fact, there is a whole wall of exceptions:


texts:
I have a gluSphere generated in my display that is rotating, but having a problem with the texture rotating with the sphere as well. So in a nutshell, no matter how the sphere rotates, the texture around the sphere remains in the same position regardless.

How am able to update the texture along with the sphere so that it rotates?

private static Texture testTex;
...

// This method is called in init()
public void sphereTexture(GL2 gl)
{
    InputStream iStream = null;

    try
    {
        iStream = getClass().getResourceAsStream("cratepng.png");
        TextureData data = TextureIO.newTextureData(iStream, false, null);
        testTex = TextureIO.newTexture(data);
        testTex.getImageTexCoords();
        testTex.setTexParameteri(GL2.GL_TEXTURE_MAG_FILTER, GL2.GL_LINEAR);
        testTex.setTexParameteri(GL2.GL_TEXTURE_MIN_FILTER, GL2.GL_NEAREST);
        iStream.close();
    }
    catch(IOException e)
    {
        e.printStackTrace();
        System.exit(1);
    }
    // Set material properties
    gl.glEnable(GL2.GL_TEXTURE_GEN_S);
    gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_WRAP_S, GL2.GL_REPEAT);
    gl.glTexGeni(GL2.GL_S, GL2.GL_TEXTURE_GEN_MODE, GL2.GL_NORMAL_MAP);

    gl.glEnable(GL2.GL_TEXTURE_GEN_T);
    gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_WRAP_T, GL2.GL_REPEAT);
    gl.glTexGeni(GL2.GL_T, GL2.GL_TEXTURE_GEN_MODE, GL2.GL_NORMAL_MAP);

    gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_MAG_FILTER, GL2.GL_LINEAR);
    gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_MIN_FILTER, GL2.GL_LINEAR);

    testTex.setTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_WRAP_S);
    testTex.setTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_WRAP_T);
}

// Draw Sphere (FILL, LINE, POINT) method called in display()
public void draw(GL2 gl, GLU glu)
{

    gl.glTranslatef(1f, 0.0f, -20.0f);
    gl.glRotatef(angleSphere, 1f, 0.0f, 0.0f); //90

    GLUquadric sphere = glu.gluNewQuadric();
    glu.gluQuadricDrawStyle(sphere, GLU.GLU_LINE);
    glu.gluQuadricTexture(sphere, true);
    glu.gluQuadricNormals(sphere, GLU.GLU_SMOOTH);
    glu.gluQuadricOrientation(sphere, GLU.GLU_OUTSIDE);

    testTex.enable(); // enable texture
    testTex.bind(); // bind texture

    glu.gluSphere(sphere, radius, slices, stacks);

    testTex.disable();
    glu.gluDeleteQuadric(sphere);
    angleSphere += speed;
    //System.out.println(angleSphere);

}


texts: How to adapt pathfinding algorithms to restricted movement?

texts:
Imagine car-like movement where entities cannot turn on a dime. Say, for the sake of discussion, that when at-speed they can turn 90 degrees per second. This would in many cases change the optimal path and therefore the pathfinding. It may even make 'usual' paths entirely impossible to traverse.

Are there any pathfinding algorithms or movement planning algorithms that can keep this in mind, or are there simple ways to adapt the popular ones?


texts: What elements are indispensable to players of a tactical strategy game?

texts:
Tactical strategy games typically involve area capture/control, unit building, terrain effects, various specialized unit types. Some will include resource gathering / management, unit customization / advancement, experience benefits for units, tech / research trees, and commander powers.

Many are turn based to allow careful planning, while others are real time. Some have movement and targeting restricted by a grid, while others calculate rate of speed and distance - and in the case of 3d or pseudo-3d arcs of fire in vertical elevation. A few have side quests, a plot / story line - possibly branching, and an overall theme or genre of some type (sci-fi, fantasy, modern, etc). User interface elements are also critical to consider.

Of these elements, and any additional elements not listed that can be thought of, which are the most indispensable? Which elements make or break a game, and keep you coming back or drive you away? Please provide only the top three answers with supporting explanations and references, if available. Should platform impact the answer, please assume a game developed for both mobile devices and computers.


texts: C# (Mono)/Java 3D Game Engine recommendation

texts:
Can you recommend a good C# game engine for cross platform (Win/Mac/Linux, I don't care about consoles) development?

I've got some experience with raw OpenGL and I played around with Java bindings and the JMonkeyEngine. However I'm somewhat disappointed those solutions and I tried Ogre3D which seemed really promising but I would rather not have to develop with the PITA that is C++.

I've had a look at this list but it is pretty overwhelming. I'm not looking for a all-in-one solution, i.e. I don't really require support for networking, audio and all that jazz but it wouldn't hurt if it's supported.

Maybe there's also an awesome Java solution out there that I don't know about?


texts: How do I create menu with text in OpenGL?

texts:
How would I go about creating a menu system with fonts in OpenGL? I want to make a dungeon crawler and will need a menu for inventory and stats for the weapons. I can draw a world made out of blocks ok but I'm not quite sure how to do this.

I think I need to use the matrix that glortho applies to the matrix stack. Specifically I'm using WebGL and I don't have access to fonts so it seems like I have to create my own.

Any help with how I would go about doing this would be appreciated.


texts:
I have got a json file and I am trying to load the single sprites from that file
but I gives this error after a few loops and also the animation is not smooth(gets stuck)
error:
Traceback (most recent call last):
  File "test.py", line 18, in <module>
    screen.blit(image, (0, 50))
TypeError: argument 1 must be pygame.Surface, not None

This is the json file I am using:
{
  "textureAtlas": {
    "texture": "Run (32x32).png",
    "regionWidth": 32,
    "regionHeight": 32
  },
  "cycles": {
    "animation0": {
      "frames": [0,1,2,3,4,5,6,7,8,9,10,11]
    }
  }
}

The script for the animation:
import json

pygame.init()

clock=pygame.time.Clock()
c=0
def lcAnim(sfile):
    global c
    with open(sfile) as f:
        data=json.load(f)
        img=pygame.image.load(data['textureAtlas']['texture'])

        while c<len(data['cycles']['animation0']['frames']):
            img.set_clip(pygame.Rect(data['cycles']['animation0']['frames'][c-1]*32,0,32,32))  # Locate the sprite you want
            draw_me = img.subsurface(img.get_clip())  # Extract the sprite you want
            c =c+1
            print(c)
            return draw_me
    c=0

and the main script:
import pygame
import lcanim #name of the animation script
(width,height)=(300,200)
clock=pygame.time.Clock()
screen=pygame.display.set_mode((width,height))
pygame.display.flip()
running=True

while running:

    image = lcanim.lcAnim('run.sf') #name of json file
    for event in pygame.event.get():
        if event.type==pygame.QUIT:

            running=False

        screen.blit(image, (0, 50))
        #screen.blit(alimg,(-10,10))
        pygame.display.update()
        screen.fill((255,255,255))
    clock.tick(10)
pygame.quit()

Here's a video showing the problem:
https://youtu.be/8IeaqVCxvms
(sorry other video sharing services were not working)


texts: how to change floor sprite in unreal engine

texts: I have started a 2D side scrolling game in Unreal Engine from the menu when you start a new game. The basic environment loads up and it works but I don't know how to change the floor sprites and player sprites. Please Help.


texts:
I have a circle sprite that i only want to move between 2 empty game objects (points). Using Vector3.Lerp() I'm able to move the circle between those points

void FixedUpdate()
{
    float speed = 10 * Time.deltaTime;
    float current = Mathf.PingPong(Time.time * speed, 1.0f);
    transform.position = Vector3.Lerp(startPoint.position, endPoint.position, current);
}

The output:

The problem:

I want to move that circle using a mouse drag (basically like a UI slider from point a to point b) and as soon as the mouse leaves the circle to stop moving it

I can currently move the circle anywhere on the screen using the mouse. I've set a circleCollider2D around the circle sprite and I have this code that moves the circle

bool Selected = false;
void Update()
{
    if (Selected)
    {
        Vector2 cursorPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        transform.position = cursorPos;
    }

    if (Input.GetMouseButtonUp(0))
        Selected = false;
}

void OnMouseOver()
{
    if (Input.GetMouseButton(0))
        Selected = true;
}

What I've tried:

I have tried adding a gameobject with a box collider between the two points and using triggers to detect when the circle exits the trigger
(OnTriggerExit2D), but this solution only works when the circle fully leaves the collider (which i don't want). I want a way for the circle to move just like its moving currently with Vector3.Lerp but with mouse control
I tried locking the circle to only one axis and moving it. While this worked, it failed when i rotated the whole slider as its only locked on one axis and rotation doesn't change that
I have also tried to implement the mouse position into the Vector3.Lerp function with no luck
Vector3.Lerp(startPoint.position, endPoint.position, mousePosition.x);

I tried with y and z, all of it failed. And this way wouldn't work when i go to rotate the slider


texts: Can I use the inclinometer and accelerometer on every Windows Phone device?

texts:
I want to do a little game that uses the Windows Phone inclinometer to control an object's pitch, roll and yaw. In addition, I need the accelerometer in another project to let an object jump.

Can I use the inclinometer and accelerometer on every Windows Phone device or are there older devices that don't support the inclinometer and accelerometer? Can I use the inclinometer and accelerometer on Windows Tablets like the surface?


texts: How do I deal with abstracting collision handling code between entities with differing collision components?

texts:
I'm using a component based entity design with Components that hold the data and Systems that act on entities based on the components they have. Entities are registered to all systems as they are created. If the entity has the list of components the system requires then it'll add it to the system's list to be processed on Update.

Lets say I have a BoundingBoxCollisionComponent a BoundingCircleCollisionComponent and an EdgeListCollisionComponent.

I have various entities that each have one of these components. For example a player entity could have the BoundingBoxCollisionComponent, a bullet entity could have a BoundingCircleCollisionComponent and a gameworld entity could have an EdgeListCollisionComponent.

Note that my player, bullet and gameworld names aren't types, they're just templates that define components that they all have along with default values for those components.

Any collision handling class(es) need to overcome the following issues, that I can't figure out how best to overcome.

Obviously the collision detection code is different depending on the exact CollisionComponent that 2 entities have. How can I effectively create classes to handle checking 2 entities for a collision, given that I could add other collision components in the future?
In the scenario above I wouldn't want to check each Bullet for a collision with every other Bullet. Once the entity is created from the bullet template all notion of it being a bullet disappears, so How can I manage what entities should be checked against what others? Do I need to have an EntityTypeComponent which would have Bullet, Player... so I can define in a class somewhere what collides with what, or maybe I could do it at entity creation time (when I know what template is used to create the entity)?


texts: Why can a certain DirectX mode produce display lag?

texts:
I have written two small test games using DirectX 9. One uses

presentParams.Windowed = false;

presentParams.PresentationInterval = D3DPRESENT_INTERVAL_ONE;

and the other one uses

presentParams.Windowed = false; // same results with true

presentParams.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;

Both use exactly the same window position, size and style. Both are written to cover the screen completely, even when using "Windowed = true".

In the latter game, to vsync and avoid tearing, my code waits until a certain scan line is passed. My tests showed: On different PCs it has to wait for different scan lines to avoid tearing completely. This is a drawback, since it has to be tweaked individually by the user. Is this technique used in any games?

And, compared to this technique, why does DirectX produce a display lag when "Windowed = false" is used with D3DPRESENT_INTERVAL_ONE?

To clarify where the lag occurs:

Windowed = false + INTERVAL_ONE => LAG

Windowed = false + ...IMMEDIATE    => no lag

Not mentioned in the question but tested:

Windowed = true;  + INTERVAL_ONE  => no lag, tearing

Windowed = true; + ...IMMEDIATE     => no lag


texts: How can I change the default New Project directory in Godot Engine?

texts: When I go to create a new project in Godot Engine (version 3.2) my Project Path is always the original default directory, no matter what path I last used. There doesn't appear to be any configuration inside the Project List window. How can I change the default project path for new projects?


texts: How to handle collision when using sprites in a 3d environment in Unity?

texts:
In games like AoE2, they've used sprites for the buildings and they've handled the collisions very well. How would I achieve something like that in Unity?

Currently, I've tried using box colliders along with the sprite renderer in a child game object. It didn't worked out well though.


texts: How do I make my rain effect look more like rain and less like snowfall?

texts:
I am making a game in that game I want a rain effect. I am little bit far from this right now. I am creating the rain effect like below:

particleSystem.addParticleInitializer(new ColorInitializer(1, 1, 1));
particleSystem.addParticleInitializer(new AlphaInitializer(0));
particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE);
particleSystem.addParticleInitializer(new VelocityInitializer(2, 2, 20, 10));
particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 30.0f));

particleSystem.addParticleModifier(new ScaleModifier(1.0f, 2.0f, 0, 150));
particleSystem.addParticleModifier(new ColorModifier(1, 1, 1, 1f, 1, 1, 1, 3));
particleSystem.addParticleModifier(new ColorModifier(1, 1, 1f, 1, 1, 1, 1, 6));
particleSystem.addParticleModifier(new AlphaModifier(0, 1, 0, 3));
particleSystem.addParticleModifier(new AlphaModifier(1, 0, 1, 125));
particleSystem.addParticleModifier(new ExpireModifier(50, 50));

scene.attachChild(particleSystem);

But it looks like snowfall! What changes can I do for it to look more like rain?

EDIT Here is a screenshot:


texts: Access a ID3D11Texture2D in another thread

texts:
I created a ID3D11Texture2D texture on a thread with DirectX graphics and I passed its pointer to a worker thread. I'm assured that the creator thread will no longer reference nor use the texture. I now need the worker thread to copy the resource

pContext->CopyResource(..);

What's the correct way of doing this in the worker thread?

In other frameworks like CUDA or OpenGL I would just push/restore the creator thread's context into the worker thread, but I'm not sure if that applies in DirectX.


texts: Detecting collisions between entities in a text mode game

texts:
What I'm trying to do is create a terminal soccer game. Without using any modules/packages like pygame or anything required to have something not outside of the terminal. So, I did research on a simple code that was supposedly going to work. It required python as expected. Here's the code found on a website.
# Draw all sprites
for entity in all_sprites:
    screen.blit(entity.surf, entity.rect)

# Check if any enemies have collided with the player
if pygame.sprite.spritecollideany(player, enemies):
    # If so, then remove the player and stop the loop
    player.kill()
    running = False

How could I turn this into something that works in the terminal?


texts:
I'm trying to create a particle that will 'circle' my character. When the particle is created, it's given a random position in relation to my character, and a box to provide boundaries for how far left or right this particle should circle. When I use the phrase 'circle', I'm referring to a simulated circling, i.e., when moving to the right, the particle will appear in front of my character, when passing back to the left, the particle will appear behind my character.

That may have been too much context, so let me cut to the chase:

In essence, the path I would like my particle to follow would be akin to a sine wave, with the left and right sides of the provided rectangle being the apexes of the wave. The trouble I'm having is that the position of the particle will be random, so it will never be produced at the same place within the wave twice, but I have no idea how to create this sort of behavior procedurally.


texts: Calculating the point(s) at which two moving objects are a certain distance from each other

texts:
Problem

This is similar to a Closest Point of Approach calculation, but instead of the closest point(s), I want the points at which the objects are a given distance away from each other. (Imagine two spaceships moving on a collision course towards each other; I want to know at what point Ship B is within Ship A's weapons range.)

Attempted solution

I started by using this page which details a method of calculating the CPA. This seemed a promising start:

  d(t) = |P(t) – Q(t)| = |w(t)| where w(t)=w0+t(u-v) with w0=P0-Q0

Rationale: for a desired distance of 5 units, I want to do:

  5 = |w(t)|

Square, substitute variables, and expand. I'm working in 2D, so this isn't too bad. Variable substitution as follows:

w.x = a
w.y = b
t = x   //(Wolfram won't solve for other variables?!)
u.x = p
u.y = q
v.x = r
v.y = s

  (a +x(p-r))^2 + (b + x(q-s))^2 = 25

Throw this into Wolfram Alpha and it gives the enormous formulas to solve for x.

And turn it into Python code:

def CPA_distance(e1, e2, dist):
    """Calculates the (two) times when e1 and e2 are exactly dist apart from each other."""
    posd = e1.pos - e2.pos
    dist2 = dist*dist

    a = posd.x
    b = posd.y
    p = e1.vel.x
    q = e1.vel.y
    r = e2.vel.x
    s = e2.vel.y

    #TODO: account for the case where (p**2 - 2*p*r + q**2 - 2*q*s + r**2 + s**2) == 0 -> they'll never intersect

    #NOTE: This function will return incorrect results if the velocities for the two entities are the same. In this case, simply check the distance between them.

    denominator = (p**2 - 2*p*r + q**2 - 2*q*s + r**2 + s**2)
    sqrt_part = sqrt(   (2*a*p - 2*a*r + 2*b*q - 2*b*s)**2
                    - 4*(a**2 + b**2 - dist2)*(p**2 - 2*p*r + q**2 - 2*q*s + r**2 + s**2))
    sub = -a*p + a*r - b*q + b*s
    t1 = ( -0.5 * sqrt_part + sub ) / denominator
    t2 = (  0.5 * sqrt_part + sub ) / denominator

    return (t1, t2)

This works in the majority of cases, but not all of them. It's possible for the calculation of sqrt_part to fail attempting to take the square root of a negative number, for instance with the following parameters (pseudocode):

e1 = ( pos = (5,5), vel = (0.5, 0.5) )
e2 = ( pos = (0,0), vel = (-0.5, 0.5) )
dist = 5

Question

What's going on that causes me to have a negative value inside the square root? Just drawing out the initial locations of e1 and e2 shows me that they'll never come within the required distance of each other but I'd have thought that I'd either get a negative time or get a divide by zero somewhere.

Is this a "valid" outcome which I can take to mean "will never get within distance, even in the past" or are my formulas all wrong?


texts: Why doesn't SDL2 recognize a game controller button press?

texts:
SDL2 recognizes my PS4 controller but not the button presses. Here is a minimal code example.

#include <SDL2/SDL.h>
#include <stdio.h>

int main(int argc, char** argv) {
  if (SDL_Init(SDL_INIT_VIDEO) != 0 ) {
    printf("Unable to initialize SDL (%s)\n",SDL_GetError());
    printf("Exit\n");
    return -1;
  }

  SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER);

  SDL_GameController *gameController = NULL;
  int numJoysticks;
  numJoysticks = SDL_NumJoysticks();
  printf("%d joysticks found\n", numJoysticks);

  if( numJoysticks <= 0 ) {
    return -1;
  }

  if( ! SDL_IsGameController(0) ) {
    printf("Error: joystick 0 is not a game controller\n");
    printf("Exit\n");
    SDL_Quit();
    return -1;
  }

  gameController = SDL_GameControllerOpen(0);

  if( ! gameController ) {
    printf("No game controller found\n");
    printf("Exit\n");
    SDL_Quit();
  }

  printf("Opened Game Controller 0\n");
  printf("Found a valid controller, named: %s\n", SDL_GameControllerName(gameController));

  if( SDL_GameControllerGetButton(gameController, SDL_CONTROLLER_BUTTON_A) ) {
    printf("Button press!\n"); // Never printed
  }

  // Exit
  SDL_GameControllerClose(gameController);
  SDL_Quit();
  return 0;
}

Here is the output I get:

1 joysticks found
Opened Game Controller 0
Found a valid controller, named: PS4 Controller

What am I doing wrong?


texts: What features does D3D have that OpenGL does not (and vice versa)?

texts:
Are there any feature comparisons on Direct3D 11 and the newest OpenGL versions?

Well, simply put, Direct3D 11 introduced three main features (taken from Wikipedia):

Tessellation
Multithreaded rendering
Compute shaders
Increased texture cache

Now I'm wondering, how does the newest versions of OpenGL cope with these features? And since I have this feeling that there are features that Direct3D lacks from OpenGL's side, what are those?


texts:
I'm just starting to learn LibGDX and have been having some troubles getting my world size to match with my texture size and box2d bodies. I have a texture 64x64 that I am trying to display but it takes up half of the window, both on desktop and android. I've tried scaling the texture down also. I am wondering if this has anything to do with my two variables FRUSTUM_WIDTH and FRUSTUM_HEIGHT being used in the creation of my camera.

  int FRUSTUM_WIDTH = 8;
int FRUSTUM_HEIGHT = 15;
World world;
Box2DDebugRenderer debugRenderer;

@Override
public void create () {
    batch = new SpriteBatch();
    img = new Texture("player.png");

    player = new Sprite(img);
    player.setPosition(5, 5);
    //player.scale(.8f);

    camera = new OrthographicCamera(FRUSTUM_WIDTH, FRUSTUM_HEIGHT);
    camera.position.set(FRUSTUM_WIDTH / 2, FRUSTUM_HEIGHT / 2, 0);

    world = new World(new Vector2(0, -50), true);
    debugRenderer = new Box2DDebugRenderer();

    setUpBox2D();

}

private void setUpBox2D()
{
    BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyDef.BodyType.DynamicBody;

    bodyDef.position.set(4, 10);

    Body body = world.createBody(bodyDef);

    CircleShape circle = new CircleShape();
    circle.setRadius(1);

    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = circle;
    fixtureDef.density = 0.1f;
    fixtureDef.friction = 0.1f;
    fixtureDef.restitution = 0.5f;

    Fixture fixture = body.createFixture(fixtureDef);

    BodyDef groundBodyDef = new BodyDef();

    groundBodyDef.position.set(new Vector2(0, 1));

    Body groundBody = world.createBody(groundBodyDef);

    PolygonShape groundBox = new PolygonShape();

    groundBox.setAsBox(camera.viewportWidth, 1.0f);
    groundBody.createFixture(groundBox, 0);
}
@Override
public void render () {
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    drawScene();
    updateScene();
}

private void drawScene()
{
    debugRenderer.render(world, camera.combined);
    camera.update();
    batch.setProjectionMatrix(camera.combined);
    batch.begin();
    player.draw(batch);
    batch.end();
    world.step(1/60f, 6, 2);
}
private  void updateScene()
{

}

I do have a resize method but it is currently empty.

The window size is 480 by 800. I looked at a game called Super Jump on Github which helped fix my camera issue, but I am still having issues with the giant textures


texts: Dynamically save an assetbundle during run time

texts:
I'm wondering if it is possible to dynamically save / amend a current asset bundle during the running of my Unity application.

I've been looking into this for a few hours, but can't find anything about how to do this. I know you can download / stream assets from a server at run time, but I'm interesting in knowing if it's possible to do the same but in the opposite direction.

Has anyone ever attempted this before? Is there any good examples of how this could be done?


texts: Libgdx: converting between two camera coordinates

texts:
I had a similar issue to the question here: Why is my text is too large even when scaled to .05f in libGDX?

So I created a second camera for my text elements. I'm rendering the text above some other elements, and under others, so I was trying to map between the two camera's coordinates when rendering.

That seems to be working OK, but I need to invert the y coordinate during the transformation. I'm wondering why that's the case?

Here's the code:

    // Setup camera
    OrthographicCamera camera = new OrthographicCamera(VIEWPORT_UNITS, VIEWPORT_UNITS * (height / width));
    camera.position.set(camera.viewportWidth / 2f, camera.viewportHeight / 2f, 0);

    // Setup text camera
    FitViewport fitViewport = new FitViewport(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    fitViewport.apply(true);
    gameContext.setHudViewport(fitViewport);
    OrthographicCamera textCamera = fitViewport.getCamera();

    // ... later, during render(), convert between coordinates
    Vector3 textPosition = new Vector3(fontX, fontY, 0);
    camera.project(textPosition);
    textPosition.y = Gdx.graphics.getHeight() - textPosition.y; // why?
    textCamera.unproject(textPosition);

    font.draw(spriteBatch, text, textPosition.x, textPosition.y);


texts: How to calculate origin and position of a weapon which should be "in hands"?

texts:
I'm currently stuck with my game, which is from the top perspective. I'm currently using these sprites for player: (using the second at the top):

And here's what I use for my gun

My problem is that I am not sure how to calculate origin & position to make sure that gun is always in player's hands. This is my code for drawing player and gun

spriteBatch.Draw(Textures.Load("player"), new Vector2(playerPosition.X, playerPosition.Y), new Rectangle(35, 2, 27,27), Color.White, player.rotation, new Vector2(playerWidth / 2, playerHeight / 2), 1f, SpriteEffects.None, 1f);
spriteBatch.Draw(Textures.Load("Guns/deagle"), new Vector2(playerPosition.X, playerPosition.Y), null,                   Color.White, player.rotation, new Vector2(playerWidth / 2, playerHeight / 2), 1f, SpriteEffects.None, 1f);

With rotation of 0, I'd need to move my gun to playerPosition.Y + 15 to make sure gun is in guy's hands, but when I do it, it looks fine but as soon as I rotate him, it's even more weird than now.

Here's how it currently looks like, with my specified code above.

https://dl-web.dropbox.com/get/capture-14.mp4?w=40052a2d

All I need is to make sure that gun will be always in guy's hands


texts:
I have heard that you can calculate delta time with two functions called SDL_GetPerformanceCounter and SDL_GetPerformanceFrequency. I'm not sure how they work completely, but I heard it is a bit similar to using SDL_GetTicks()

    Uint64 NOW, LAST;
    double deltaTime = 0;

    while (somebool)
    {
       LAST = SDL_GetPerformanceCounter();
       NOW = SDL_GetPerformanceCounter();
       LAST = NOW;

       deltaTime = (NOW - LAST) / (double)SDL_GetPerformanceFrequency();

       /**Rendering**/
    }

I have this code but whenever I print out deltaTime or try to use it it always equals some really random and insane numbers. Is this correct?


texts:
When you buy a game at the store, and want to play it on your computer, you do the following:

Run a setup.exe
Install on computer
End up with an exe on your desktop (separate from its source files, asset files, etc.)

How do I format my program (created from Visual Studio) to be like that?

The farthest I have toward this goal is how my folder is currently structured:

If you do not know how to completely separate my .exe from my source and asset files, then do you know how to be able to put my source, header, and sfml DLL's into a folder like the following:

Or do you know how to just bundle everything into one executable package?


texts: What is the best way of storing the character's inventory (consisting of each item having a value for type and quantity). The only methods I can think of is to use the "text" type of field then parse the value from that whenever the inventory is loaded. Is there a better method or data structure?


texts: How to know when a bullet has hit its destination in a game with a fixed timestep?

texts:
@James is wording my question better than I am, so I figured I'd put this here:

  I believe what you are asking is that you have a bullet moving in a game with a fixed timestep and that when the bullet collides with something, the time step usually makes the bullet go Past where it would have actually hit making it look like the bullets hit some where beyond where it actually hit.

I'm shooting a projectile in a 2D topdown game.  The unit can shoot in 360 direction.  There's no gravity, there's no arc and it moves at a constant speed (although this last point may change in the future).  It's easy to find the point of the unit and the destination of the bullet, but how do I know when the bullet has hit it's destination?

I'll be more specific.  The bullet probably won't land directly on the point it was intended to because it moves a certain distance based on the delta of time.  The bullet will often be in a state where it will overshoot the destination on the next tick.

How do games usually handle this?  I can imagine pros and cons to "always overshoot" and "always undershoot".


texts: Matrix transforming with translation/rotation/scale at center of screen

texts:
I'm trying to create a camera using matrix transforms, the gist is as follows:
Transform =
     Matrix.CreateRotationZ(Rotation) *
     Matrix.CreateTranslation(new Vector3(-Position.X, -Position.Y, 0)) *
     Matrix.CreateScale(Zoom) *
     Matrix.CreateTranslation(new Vector3(Bounds.Width * 0.5f, Bounds.Height * 0.5f, 0));

It works but with one issue. The rotation origin remains at the starting (-Position.X, -Position.Y) while the zoom works fine (at the center screen) which is obvious from the code. I'd like the rotation to occur at the center screen as well.


texts: experience/level growth system formula based on a plot chart, what kind of equation suits this one?

texts:
Hi I am trying to build a experience/level growth system based on the following plot chart, however I can't think of a proper formula or equation to this chart. Can anyone lend me a hand, please? The x-axis grow significant bigger very fast but the y-axis grow very slow after it reaches 200.

I have tried log and power function but can't make it work. What kind of equation should I use to make it conform to this chart?


texts: How can I use shaders to make a square have a waving effect?

texts:
I'm new to using shaders to do some fancy effects and I'm struggling with them. I'm using DirectX 11 and HLSL. I have this square in the middle of the screen:

It's just a square that I've created using 4 vertices. I want to give it this waving effect on the sides, but I don't know how to do it.

This is for a little 2D game I'm making, so I have an orthogonal projection matrix which is the one I use. View matrix is set to identity.

DirectX::XMMATRIX view = DirectX::XMMatrixIdentity();
DirectX::XMMATRIX projection = DirectX::XMMatrixOrthographicOffCenterLH(0.0f, SCREEN_WIDTH, SCREEN_HEIGHT, 0.0f, 0.0f, 1.0f);

This is the constant buffer I set each frame, so I can pass a float time variable to the shader:

struct constant_buffer {
    DirectX::XMMATRIX  WVP;
    // this value starts in 0 and increases by 1 each frame until 359 degrees
    float time;
};

constant_buffer cbuffer;

The shader that I'm currently using is very simple, it just applies the matrix to each vertex to transform it.

struct in_pshader
{
    float4 position : SV_POSITION;
    float4 color : COLOR;
};

cbuffer constant_buffer
{
    float4x4 WVP;
    float time;
};

in_pshader vshader(float4 position : POSITION, float4 color : COLOR)
{
    in_pshader output;

    output.position = mul(position, WVP);
    output.color = color;

    return output;
}

float4 pshader(float4 position : SV_POSITION, float4 color : COLOR) : SV_TARGET
{
    return color;
}

I'm guessing there's some sine function involved around, so that's why I decided to pass angles per frame as input. I tried many combinations, but I'm such a newbie and can't get it right. :( Any help on this would be very appreciated.


texts: Turn-based tile game dynamic item/skill/command script files

texts:
I want to create a mechanism that could read text script, for example some kind of custom script such as  ".skill" or ".item", which maybe contain some sort of simple script like

.item
Item.Name = "Strength Gauntlet";
Character.STR += 20;

..

.skill
Skill.Name = "Poison Attack";
Skill.Description = "Steal HP and inflict poison";
Player.HP += 200;
Enemy.HP -= 200;
Enemy.Status += Status.POISON;

It may be different from this, but just want to give some idea of what I desire. However, I do not know how to dynamically parse these things and translate it into working script. For example, in battle scenerio, I should make my game read one of this ".skill" file and apply it to the current enemy, or the current player. How would I do this? Should I go for String parsing? It is like a script engine, but I prefer C# than creating new language, so how would I parse custom files into appropiate status commands?

Another problem is, I have also created a command engine which would read String input and parse it into action such as "MOVE (1,2)" would move character to tile (1,2). Each command belong to separate class, and provide generic parsing method that should be implemented by hand. This is for the reason of custom number/type of arguments per each command. However, I think this is not well designed, because I desire it to automatically parse the parameters according to specify list of types.

For example, MOVE command in "MOVE 1 2" would automatically parse the parameters into int, int and put it into X and Y. Now, this form can change, and we should be able to manually specify all type of formats. Any suggestion to this problem? Should I change from string parsing to some hardcode methods/classes?


texts: Physics.IgnoreCollision not working right after invoked

texts:
When invoking Physics.IgnoreCollision in Unity, it seems work but it still have collision detection right after creation.

I have this issue with ejecting empty case after gun fire, it's spawning position located inside of character controller(collider), so when ejecting case created, it immediately hit to my character controller and makes my character slows.

First I thought that it's coming from something else, but it's not, because when I just not spawning the empty case, it never happens.

This is the code:

GameObject ejectedCase = Instantiate(emptyCasePrefab, caseSpawnPoint.position, caseSpawnPoint.rotation);

Collider caseCollider = ejectedCase.GetComponent<Collider>();
Physics.IgnoreCollision(caseCollider, playerCollider);

Note that playerCollider is Collider. I also tried with CharacterController(because it's extended from Collider class) but result was same.

Why I said something like "it's not working right after invoked" because it's actually working after passed some time. If it's not work, character controller step on the empty case and makes camera jittering issue on vertical axis. This is totally gone after ignoring collision detection with above code, however it still works right after creation and makes my character really slow.

How do I avoid this weird glitch, makes IgnoreCollision works right after it invokes?

In addition: I don't want to fix this issue with using Layer Collision Matrix. I didn't tried but it will work sure, however I don't want to spend Layer for this purpose only, because it's number is limited and already using lots of layers in other logics so it makes game logic more complicated if I use Layer to avoid collision detection. I want to know why "Physics.IgnoreCollision" not works because literally it saids "ignore collision" but it wasn't.


texts: How to know my lighting shaders matches famous models?

texts: I have some diffuse and specular lighting shaders based on famous models like lambert etc. Thing is, how can I know that my shader is actually implementing the correct formula? I can see my materials does reflect light but how can I be sure that my formula matches the models. Any way to test this?


texts: Constant Buffer size mismatch on PS, fine on VS and GS

texts:
I have the following C/C++ struct:

struct ShadowMapCB {
        Math::Matrix4 cropMatrix[4];
        Math::Matrix4 textureMatrix[4];
        float splitPlane[4];
    };

and my HLSL constant buffer:

cbuffer CBShadowMap : register(b4)
{
    matrix g_CropMatrix[4];
    matrix g_TextureMatrix[4];
    float g_fSplitPlane[4];
};

When i bind it to pixel shader i get an error:

  D3D11: WARNING: ID3D11DeviceContext::DrawIndexed: The size of the Constant Buffer at slot 4 of the Pixel Shader unit is too small (528 bytes provided, 576 bytes, at least, expected). This is OK, as out-of-bounds reads are defined to return 0. It is also possible the developer knows the missing data will not be used anyway. This is only a problem if the developer actually intended to bind a sufficiently large Constant Buffer for what the shader expects.  [ EXECUTION WARNING #351: DEVICE_DRAW_CONSTANT_BUFFER_TOO_SMALL ]

and infact the last 4 floats (array[4]) are messed up, the weird thing is that on the VS and GS it works fine..., and yes i did bind them with PSSetConstantBuffers and update it ofcourse.

What could be causing this?


texts:
I currently have a QuadTree that contains all my Entities.  It works well and I've optimized it pretty decently, but the one thing that hurts is that I am removing from and inserting to it almost every frame. A little code:

    entityMap.remove(it->second, it->second->getLastAABB()); // Removes the entity, getLastAABB is it's last location

    QuadTree* nearest = entityMap.getLowestRoot(moved);
    std::unordered_set<Locatable*> entities = nearest->getAll();
    for (auto itt = entities.begin(); itt != entities.end(); itt++) {
        AABB aabb = (*itt)->getAABB();
        if (aabb.collides(moved)) {
            // COLLISION
        }
    }

    entityMap.insert(it->second);

That code gets run 30 times a second.  I use a dirty flag so that only entities that have moved are dealed with.  entityMap is the QuadTree itself.

Any advice to decrease insert and remove calls is appreciated.


texts: Store data on server or only in database?

texts:
I have been working on programming an online RPG in Java for a while now. It's a huge project and way too hard for me, but I'm having fun learning.

server and client: Java
database: MySQL

I have mainly been working on the GUI but now have started to draw a map based on the tileset returned from my server. I am now ready to grab my users coordinates from the db, but I am wondering if I should have them sitting in a temp variable on my server or just access/change the coordinates in the database.

Long story short: hit db always for lookups and changes or have a LinkedList or something on the server?


texts: Drawing simulator - Tracking mouse movement

texts:
I was wondering what would be the logic behind coding a drawing simulator like the one on this website: https://www.mdbg.net/chindict/chindict.php?page=chardict&cdcanoce=0&cdqchi=
The paintbrush tool when you click it, once you start drawing strokes that a similar to what a character is, it will automatically bring out a list of characters that leads toward what you are drawing. Once you are finished, the correct character will show up.
To my idea, I think that a set of coordinates are set already and once the mouse coordinates passes through these points, then from there it will detect and provide all the possibilities and narrows it even further. I think this is very complex but what would be the right path/correct way to go about programming this concept?


texts: Unity Profiling - Mesh.Bake PhysX CollisionData Doubling CPU cycles

texts:
I have a mob that, when it dies, spawns smaller versions of itself.  When this happens there's a huge resource spike.  The profiler narrowed it down to baking the meshes of the new objects.  I have a couple of smaller questions related to this, but the crux of the issue is that it looks like the baking is occurring twice (doubling CPU usage) as shown below in both Instantiate and Transform.SetParent.  I'd normally say it's redundant, but in every way it looks like it's happening twice and take over one full second total.  Why would this happen twice on the same set of object (there are a variable number of spawned mobs, so the actual numbers can vary)?

As an aside, can this be backed in the prefab somehow to avoid this?


texts: How to change the amount of Fast Linear Gaussian blur in GLSL?

texts: I implemented the GLSL from http://rastergrid.com/blog/2010/09/efficient-gaussian-blur-with-linear-sampling/, but is unclear to me how to reduce or increase the amount of blur. Has it something to do with the iterations? I don't understand how.


texts: How to spawn enemies after a certain amount of time?

texts:
I wanted to spawn different enemies(meteors) after a certain amount of time this is the script that I tried doing but it's giving me an error. I'm still just a beginner and I don't if I did something wrong with the script.

The error that I get is:

Assets/Scripts/meteorSpawner.cs(32,12): error CS1660: Cannot convert lambda expression' to non-delegate typebool'

and here is my current script

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

public class meteorSpawner : MonoBehaviour {

public GameObject[] meteors;
//int meteorNo;
public float maxPos = 2.4f;
public float delayTimer = 1.25f;
public float timeNeed = 10f;
public float time = 0f;
float timer;

// Use this for initialization
void Start () {
    timer = delayTimer;

}

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

    timer -= Time.deltaTime;
    if(timer <= 0) {
        Vector3 meteorPos = new Vector3(Random.Range(-2.2f, 2.2f), transform.position.y, transform.position.z);
        //meteorNo = Random.Range(0, 2);
        Instantiate(meteors[0], meteorPos, transform.rotation);
        timer = delayTimer;
    }
    time += Time.deltaTime;
    if(time => timeNeed){
        Vector3 meteorPos = new Vector3(Random.Range(-2.2f, 2.2f), transform.position.y, transform.position.z);
        //meteorNo = Random.Range(0, 2);
        Instantiate(meteors[1], meteorPos, transform.rotation);
    }

}
}


texts: How to implement a simple bullet trajectory

texts:
I searched and searched and although it's a fair simple question, I don't find the proper answer but general ideas (which I already have).

I have a top-down game and I want to implement a gun which shoots bullets that follow a simple path (no physics nor change of trajectory, just go from A to B thing).

a: vector of the position of the gun/player.
b: vector of the mouse position (cross-hair).
w: the vector of the bullet's trajectory.

So, w=b-a. And the position of the bullet = [x=x0+speedtimenormalized w.x , y=y0+speed*time * normalized w.y].

I have the constructor:

public Shot(int shipX, int shipY, int mouseX, int mouseY) {
//I get mouse with Gdx.input.getX()/getY()
...

  this.shotTime = TimeUtils.millis();

  this.posX = shipX;
  this.posY = shipY;

  //I used aVector = aVector.nor() here before but for some reason didn't work
  float tmp = (float) (Math.pow(mouseX-shipX, 2) + Math.pow(mouseY-shipY, 2));
  tmp = (float) Math.sqrt(Math.abs(tmp));

  this.vecX = (mouseX-shipX)/tmp;
  this.vecY = (mouseY-shipY)/tmp;
}

And here I update the position and draw the shot:

public void drawShot(SpriteBatch batch) {
  this.lifeTime = TimeUtils.millis() - this.shotTime;

  //position = positionBefore + v*t
  this.posX = this.posX + this.vecX*this.lifeTime*speed*Gdx.graphics.getDeltaTime();
  this.posY = this.posY + this.vecY*this.lifeTime*speed*Gdx.graphics.getDeltaTime();
...
}

Now, the behavior of the bullet seems very awkward, not going exactly where my mouse is (it's like the mouse is 30px off) and with a random speed. I know I probably need to open the old algebra book from college but I'd like somebody says if I'm in the right direction (or points me to it); if it's a calculation problem, a code problem or both.
Also, is it possible that Gdx.input.getX() gives me non-precise position? Because when I draw the cross-hair it also draws off the cursor position.

Sorry for the long post and sorry if it's a very basic question. Thanks!


texts: XNA slowly stops sprite movement on key released

texts:
I'm making a game where player moves around a spaceship pressing W,S,A,D. What I would like to achieve is that I would like to make the ship stop slightly when a key is released before it went to full stop. How can I achieve that?

Here's the moving code :

 kbs = Keyboard.GetState();

            if (kbs.IsKeyDown(Keys.W))
            {
                this.pos.Y -= speed;
                this.animation = "up";

                if (kbs.IsKeyDown(Keys.D))
                {
                    if (!isDirectional)
                    {
                        frameIndex = 0;
                        isDirectional = true;
                    }
                    this.pos.X += speed;
                    this.animation = "upright";
                }
                else if (kbs.IsKeyDown(Keys.A))
                {
                    if (!isDirectional)
                    {
                        frameIndex = 0;
                        isDirectional = true;
                    }
                    this.pos.X -= speed;
                    this.animation = "upleft";
                }

                if (!this.isAnimating) this.isAnimating = true;
                else this.isAnimating = false;

                CheckStop();
            }
            else if (kbs.IsKeyDown(Keys.S))
            {
                this.pos.Y += speed;
                this.animation = "down";

                if (kbs.IsKeyDown(Keys.D))
                {
                    if (!isDirectional)
                    {
                        frameIndex = 0;
                        isDirectional = true;
                    }
                    this.pos.X += speed;
                    this.animation = "downright";
                }
                else if (kbs.IsKeyDown(Keys.A))
                {
                    if (!isDirectional)
                    {
                        frameIndex = 0;
                        isDirectional = true;
                    }
                    this.pos.X -= speed;
                    this.animation = "downleft";
                }

                if (!this.isAnimating) this.isAnimating = true;
                else this.isAnimating = false;
            }
            else if (kbs.IsKeyDown(Keys.A))
            {
                this.pos.X -= speed;
                this.animation = "left";
                if (!this.isAnimating) this.isAnimating = true;
                else this.isAnimating = false;
            }
            else if (kbs.IsKeyDown(Keys.D))
            {
                this.pos.X += speed;
                this.animation = "right";
                if (!this.isAnimating) this.isAnimating = true;
                else this.isAnimating = false;
            }
            else
            {
                this.isAnimating = false;
                this.isDirectional = false;
                frameIndex = 0;
            }

I have been trying to check for the ship to slowly stop with CheckStop() function, here it is (for the sake of trying, on the above code I only apply CheckStop() on the 'W' key):

private void CheckStop()
        {
            KeyboardState nkbs = Keyboard.GetState();

            if (!kbs.IsKeyDown(Keys.W) && nkbs.IsKeyDown(Keys.W))
            {
                speed -= fraction;
                if (speed <= 0) speed = 0;
                this.pos.Y -= speed;
            }
        }

Any help is appreciated, thanks.


texts: How to properly pass sprites to a std::vector without destroying the sprite's texture in SFML?

texts:
From the official SFML tutorials, The White Box Problem:-

"When you set the texture of a sprite, all it does internally is store a pointer to the texture instance. Therefore, if the texture is destroyed or moves elsewhere in memory, the sprite ends up with an invalid texture pointer." Thus you will see a sprite without a texture.

I have a class called World. In this class I made a 2d integer array called level and a vector of type Block called blocks. Now I wanted to store the 'Block' objects inside the vector whenever level[ i ][ j ] = 1.

header file of the 'World' class:-

#ifndef WORLD_H
#define WORLD_H
#include <vector>
#include "Block.h"
#include "Grass.h"
#include <SFML/Graphics.hpp>

using namespace std;

class World
{
    public:
        World();
        void draw(sf::RenderWindow *window);
        vector<Block> blocks;

    private:
        int level[12][16];
        int wd;
        int hi;
};

#endif // WORLD_H

cpp file of the 'World' class :-

#include "World.h"
#include "Grass.h"
#include "Block.h"
#include <iostream>
#include <SFML/Graphics.hpp>

using namespace std;

World::World() : level{
        {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
        {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
        {1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1},
        {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
        {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
        {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
        {1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1},
        {1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1},
        {1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1},
        {1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1},
        {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
        {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
    }
{
    wd = 16;
    hi = 12;
    int count = 1;
    //make a 'Block' object and pass it in the vector when level[ i ][ j ] = 1.
    for(int i = 0; i<hi; i++)
    {
        for(int j = 0; j<wd; j++)
        {
            if(level[i][j] == 1)
            {
                Block block(j*50, i*50);
                blocks.push_back(block);
            }
        }
    }
}
void World::draw(sf::RenderWindow *window)
{
    for(unsigned int i = 0; i<blocks.size(); i++)
    {
        blocks[i].draw(window);
    }
}

The 'Block' class has two members - sf::Texture blockT and sf::Sprite block. It also has a draw(RenderWindow *window) method. This is how the 'Block' class is made :-

header file for block class

#ifndef BLOCK_H
#define BLOCK_H
#include <iostream>
#include <SFML/Graphics.hpp>

using namespace std;

class Block
{
    public:
        Block(float x, float y);
        void draw(sf::RenderWindow *window);

    private:
        sf::Texture blockT;
        sf::Sprite block;
};

#endif // BLOCK_H

cpp file for 'Block' class

#include "Block.h"
#include <iostream>
#include <SFML/Graphics.hpp>

using namespace std;

Block::Block(float px, float py)
{
    if(!(blockT.loadFromFile("textures/block.png")))
    {
        cout<<"Could not load block texture."<<endl;
    }
    block.setTexture(blockT);
    block.setPosition(sf::Vector2f(px, py));
    cout<<px<<endl;
    cout<<py<<endl;
}

void Block::draw(sf::RenderWindow *window)
{
    window->draw(block);
}

When I run the program, in place of blocks, only white box is shown. I don't understand how the texture is getting destroyed. This is what the output looks like :-

As you can see, the white places are sprites each of size 50*50 without any texture.

Edit: The Main Function :-

int main()
{
    sf::RenderWindow window(sf::VideoMode(800, 600), "Untitled game");
    window.setVerticalSyncEnabled(true);
    Player player;
    World world;

    //variables

    while(window.isOpen())
    {
        //event handling

        //updating

        //drawing
        window.clear(sf::Color::Black);
        world.draw(&window);
        window.display();
    }

    return 0;
}


texts: OpenGL ES Frame Skipping causing visible artifacts

texts:
I'm using OpenGL ES 3.0 on Android 5.1, and am noticing the following issues. I tried to implement the game loop which does exactly 60 updates and do as many frames as it can. Everything is smooth, but the object is being rendered twice, I think due to interpolation by hardware.

If you zoom the image (click to view in separate tab) you'll see that the green square is being rendered twice. And now if I remove the catch-up code, it works correctly.

As you can see it now renders fine. Now I'll show you my game loop. I'm using GLSurfaceView class, and doing my render in onDrawFrame of the renderer.

double now = TimeUtils.currentTime();

if (previous == -1)
    previous = now;

double delta = now - previous;

if (delta >= SECOND)
    delta = frameTime;

lag += delta;

while (lag >= frameTime)  // This line plays catchup.
                          // If commented, it works otherwise the
                          // artifact occurs
{
    updates++;
    doUpdate(frameTime);

    lag -= frameTime;
}

frames++;
glClear(GL_COLOR_BUFFER_BIT);
doRender(frameTime);

if (now - lastStatsTime >= SECOND)
{
    updatesPerSecond = updates;
    framesPerSecond = frames;

    updates = frames = 0;
    lastStatsTime = now;
}

previous = now;

Is there anything that I'm doing wrong? I'm using a dynamic VBO for rendering, the lines are generated every frame and I use glBufferData to send them to GPU. This happens every frame (This is being done for educational purpose, to learn how VBOs are streamed).

Are there any issues that I'm forgetting?


texts: Unity - get screenshots from various resolutions

texts: To upload my app to Google Play I need to provide various screenshots. Thing is, I have only one tablet, no phone and I don't feel like virtualizing a bunch of devices. Is there a way to create screenshots of different sizes? Like what would a 7" 1280X720 tablet see?


texts: Root Animation unusual position and non root animation snaps back

texts:
Im trying to do a stop animation . when i release the W key then from Run it will do this animation then goto IDLE . But somehow this is not working right. as you see in those videos below. So how do i achieve this ?

Im using animation from mixamo.

After Root Motion http://i.imgur.com/JwY98P2.gifv

Before Root Motion  https://fat.gfycat.com/ReflectingMealyCrane.mp4


texts:
I would like to create an online implementation of a board game. What engines could I use to write the game and make it easily accessible to as many people as possible?

I would like it to be as widely accessible as possible, so it would be best if the user interface would run in a browser, not in a separately downloaded app. Likewise, it should be cross platform, not limited to a single platform; pure JavaScript/HTML would be best, as that would allow it to be usable on the iPad as well, though Flash or Java may be acceptable. Silverlight doesn't have the market penetration (I don't have it installed, for instance) and XNA is far too limited.

Other features that would be nice would be good chat and social features (or integration with other chat or social network systems), leaderderboard or tournament systems, and easy integration of bots to provide AI opponents in case there aren't enough human players around. Game timers, to keep people moving at a reasonable rate, would also be good. Saving game records, and allowing people to replay and review records for study, would be nice too, though I'm not expecting much as those types of features tend to only show up in purpose-built engines for games like chess or Go.

Being free/open-source software would be a big plus, so I could extend it myself, though closed or hosted solutions might be acceptable if they provide enough of the above features or provide some means for extending them.

Are there any such systems that meet my needs? Or any that are close even if not exactly matching?

Some similar systems, that don't quite meet my needs, would include:

Yahoo Games, which is web based, but I can't write my own games for it (or any of many similar servers in that category).
Volity, which is built on SVG and XMPP. It's open source, designed to be an open standard, has support for bots, etc, but it requires a separate client download, and seems not to be actively developed or used any more.
SuperDuperGames, which is an open source, online system for doing turn-based (play-by-mail style) games. That is, it's not live or real time, but instead you submit your moves, and wait for someone to submit theirs, within the next day or so. It's an active community, but I want something where I can play games live, not over the course of weeks or months.


texts: Develop a 2d isometric mobile game on Flash

texts:
I'm building a game on Flash that will run on web/Android/iOS.
The game is 2d isometric.I heard that developing mobile apps on Flash sucks and the graphics looks just awful.It'd be quite uncomfortable to write code for every platfrom separately.What would you guys recommend-stay with Flash or some other platform?
By the way,do i need to build the game specially on MAC so that i can later port it on iOS?
Thanks


texts: Loading encounters and collisions questions within 2D

texts:
I had three basic questions regarding the creation of a 2D sandbox/openworld game much like Terreria.

Only looking for a general overview/opinion, nothing too detailed. Any links to literature that would help answer the questions below would also be helpful.

First off - Keeping track of the map using regions/chunks, lets say 512 x 512 chunks. Is it recommended to pre-load the surrounding chunks of the 'chunk in focus', so if the character enters either one there is no load time? ~Or do you simply load smaller slices of the chunk next door, in the direction of movement?

Secondly. Do I need to add a collision box to every tile that is preloaded so any NPCs that are off screen but 'next-door' can interact with the environment? Or is this going to be massively CPU intensive ? (512 x 512 x 9 tiles alone)

Third and last question. Off screen RANDOMDLY GENERATED NPCs/monsters I assume dont load and render as they enter the viewable area on the active chunk but are loaded and activated sometime before they are seen. What are the general strategies use to handle this?

For Reference: Using c# with Unity, no third party frameworks/plugins.

Many thanks
John


texts: Best system for creating a 2d racing track

texts:
I am working a 2D racing game and I'm trying to figure out what is the best way to define the track.

At the very least, I need to be able to create a closed circuit with any amount of turns at any angle, and I need vehicles to collide with the edges of the track. I also want the following things to be true if possible (but they are optional):

The code is simple and free of funky workarounds and extras
I can define all of the parts of the track (such as turns) relative to the previous parts
I can predict the exact position of the road at a certain point (that way I can easily and cleanly make closed circuits)

Here are my options:

Use a set of points. This is my current system. I have a set of turns and width changes that the track is supposed to make over time. I have a point which I transform according to these instructions, and I place a point every 5 steps or so, depending on how precise I want the track to be. These points make up the track. The main problem with this is the discrepancy between the collisions and the way the track is drawn. I won't get into too much detail, but the picture below shows what is happening (although it is exaggerated a bit). The blue lines are what is drawn, the red lines are what the vehicle collides with. I could work around this, but I'd rather avoid funky workaround code.
Beizer curves. These seem cool, but my first impression of them is that they'll be a little daunting to learn and are probably too complicated for my needs.
Some other kind of curve? I have heard of some other kinds of curves; maybe those are more applicable.
Use Box2D or another physics engine. Instead of defining the center of the track, I could use a physics engine to define shapes that make up the road. The downside to this, however, is that I have to put in a little more work to place the checkpoints.
Something completely different.

Basically, what is the simplest system for generating a race track that would allow me to create closed circuits cleanly, handle collisions, and not have a ton of weird code?


texts: Unity: How to draw 2D lines directly on a UI canvas?

texts:
The title pretty much tells my issue. I want to simply draw a few lines from a script controlled by start- and endpoint coordinates directly on the UI canvas (so the lines will move at runtime).
From what I could read up so far, there are these options:

LineRenderer:

Works in 3D space. Since I want this on the UI it seems a bit overkill and also to performance hungry for such a simple task. Further, I will have to add a virtual camera and calculate the positions in 3D space (no problems with that part). My data model represents the positions in 2D Pixel coordinates, it would be quite a lot simpler to directly use those coordinates to place the lines on the screen.

GL.Line():

Also works in 3D space, furthermore there is no freedom in terms of line thickness.

Asset Store:

I tried out a ui-extension package briefly, however it left me with several warnings not connected to the actual functions I used. However if someone knows a lightweight asset, I'm happy to test!

It kind of baffles me that there is nothing provided in Unity for something seemingly so easy. Or am I missing something fundamental here?


texts:
For my game, I have to set highest z index for my sprite.
At present, I wrote following code but didn't work for me.

    Sprite houseSprite = new Sprite(pX, pY,
            textureManager.houseBgRegion.deepCopy(),
            mVertexBufferObjectManager);
    attachChild(houseSprite);
    houseSprite.setZIndex(500);
    sortChildren();

My requirement did not satisfied with setting sprite in the HUD. So any how I have to apply highest z index. Also in my game sprites are dynamically generated as per game play.

So members please share your thoughts.


texts:
I am using game maker because I am new to game development and I think it's the easiest to understand because I took a course on it but I put in all the events so that my playerobj moves when you press the A and D keys but when I load up the game it doesn't work here is the GML code below that I am using:

//Speed of player: 5 Pixels per frame
 playerSpeed = 5;

 //Shortcuts for keypresses
 MOVELEFT = keyboard_check(ord('A'));
 MOVERIGHT = keyboard_check(ord('D'));
 MOVEUP = keyboard_check(ord('W'));
 MOVEDOWN = keyboard_check(ord('S'));

 //Move Player
 if (MOVELEFT && x > sprite_width/2)
 {
x -= playerSpeed;
 }

 if (MOVERIGHT && x < room_width - sprite_width/2)
 {
x += playerSpeed;
 }

 if (MOVEUP && y > room_height/2)
 {
y -= playerSpeed;
 }

 if (MOVEDOWN && y < room_height - sprite_width/2)
 {
y += playerSpeed;
 }


texts: Approximating Subdivision Surfaces with Gregory Patches for Hardware Tessellation

texts:
I'm trying to implement the approach (http://research.microsoft.com/en-us/um/people/cloop/sga09.pdf).
Unfortunately I'm not quite clear regarding the formulas in chapter 3, I am hoping to get some answers.

I am unclear on the following points, did you figure them out?

what kind of value do I get, when I calculate T(u,v,w) (a point?) and
what do I do with the result?
do I recieve the values u,v,w from the domain shader SV_DomainLocation or are they calculated?
are the corner points in chapter 3.2 barycentric too?
does v get replaced by p0 in figure 5?
In chapter 3.3 Edge Points there is a formula for e0+, but none for e0-? For which edge is e0+ in figure 5? and how can I calculate e0+ for the other edges? It seems for me (figure 5) there are 5 edges, but just one e0+ is calculated, shouldn't there be 5 e0+?
Do you maybe have a diagram of the controlpoints in relation to the control mesh? I am having problems seeing the big picture...
In chapter 3.4: face points,  you mention different transversal vectors r, r0+ and r0- but there is only one formula for r0+.  Are r = r0+ = r0-?  If not, how do I calculate r and r0-?

I am hoping someone could point me in the right direction, thank you in advance!


texts: How should I actually enforce the effects of components?

texts:
I asked a question about implementing components here:

Am I on the right track with this component architecture?

But I had more questions I'd like to ask.

What's the best way to actually enforce the effects of components?

For instance, I have an item object, and an optional HealingComponent. The HealingComponent allows the item to be used as a HealingItem (for restoring HP/MP/etc.). I compose the HealingComponent from up to 3 StatAffectorComponents (one for HP, MP and SP). That Affector dictates the target stat, the target amount of change, and the type of change (%, absolute, etc.). All the basic components are being implemented in C++, but I intend to make the basic components extendtable from my scripts (python)

Now my question is, how do I actually enforce this?

I had three ideas about how to do it.

Allow the HealingComponent to contain a Use function that takes in the appropriate parameters and applies the StatAffector components against them. This has the advantage of making it much easier to override/customize the behaviour if I extend it with scripts, but I'm also tightly coupling the mechanics of usage with the item.
Allow the game mechanics to enforce the components. When the item is used as a Healing Item, the mechanics will extract the stat affectors and apply them against the appropriate targets its self. This has the advantage of seperating the item/component from it's usage, but at the same time, I'll have to change the mechanics anytime I decide to add expanded functionality/components to healing items. Healing items may not change their effects too often in development, but certain item classes might
Allow the item itself to define it's Use function and make it responsible for checking against it's components. This is further specializing Item away from a base entity, but has the advantage of being overridable with scripts to allow custom components

In general, what is the best way to do this?


texts:
Possible Duplicate:
  MVC-like compartmentalization in games?

I am thinking of the best way to structure my project and was thought a MVC style pattern would be appropriate. Would be correct having the model handle the majority and basically being the game engine?

Are there any standardised patterns recommended for simple game development?

Model / Game Engine

Data: Level Design, Chat feeds, etc
Game Status: Player status, Enemy status, World Status etc etc.
Engine: Physics, Collisions, AI

View

3D: Gameplay, Camera, Rendering...
2D: UI etc

Controller:

Player Input
UI Input


texts: How to shift a vector based on the rotation of another vector?

texts:
I’m learning 2D programming, so excuse my approximations, and please, don’t hesitate to correct me. I am just trying to fire a bullet from a player. I’m using HTML canvas (top left origin).

Here is a representation of my problem:

The black vector represent the position of the player (the grey square).
The green vector represent its direction.
The red disc represents the target.
The red vector represents the direction of a bullet, which will move in the direction of the target (red and dotted line).
The blue cross represents the point from where I really want to fire the bullet (and the blue and dotted line represents its movement).

This is how I draw the player (this is the player object. Position, direction and dimensions are 2D vectors):

ctx.save();
ctx.translate(this.position.x, this.position.y);
ctx.rotate(this.direction.getAngle());
ctx.drawImage(this.image, Math.round(-this.dimensions.x/2), Math.round(-this.dimensions.y/2), this.dimensions.x, this.dimensions.y);
ctx.restore();

This is how I instanciate a new bullet:

var bulletPosition = playerPosition.clone(); // Copy of the player position
var bulletDirection = Vector2D.substract(targetPosition, playerPosition).normalize(); // Difference between the player and the target, normalized
new Bullet(bulletPosition, bulletDirection);

This is how I move the bullet (this is the bullet object):

var speed = 5;
this.position.add(Vector2D.multiply(this.direction, speed));

And this is how I draw the bullet (this is the bullet object):

ctx.save();
ctx.translate(this.position.x, this.position.y);
ctx.rotate(this.direction.getAngle());
ctx.fillRect(0, 0, 3, 3);
ctx.restore();

How can I change the direction and position vectors of the bullet to ensure it is on the blue dotted line?

I think I should represent the shift with a vector, but I can’t see how to use it.