texts: Newbie game programmer - Where do I start?

texts:
Okay, so I have been really inclined towards game programming this past few weeks. I have primarily been a web programmer and know a fair number of lanugages like PHP, Java, javascript, python, etc. I also know a little bit of C++ as I heard that it's used heavily in the game industry. I have no experience in game development, but I am a fast learner.(I am 15 so I guess I still have a lot of time.)

So, is there any language I should learn to develop 2d and 3d games? Also which IDE(free) is a nice place to start compiling your ideas(something like Polycode:-  http://polycode.org/). I looked up Polycode but it was a little confusing for me to build it. I have a fair idea about what DirectX, OpenGL, SDL and shaders are but I have absolutely no clue about programming them. I know it's a little early to start jumping into this stuff already but you gotta start somewhere right? Please help me as I really want to get into serious game programming. Thanks!

I am running Windows 8 Pro 32 bit. Please suggest me any software accordingly!


texts:
Good time of the day to everyone who is reading this topic.

I've been enjoying playing Diablo 3 and decided to try myself in game development (to lure my friends into Diablo 3 and to, ofcourse, practice in game development).

I'd like to split the question in to following sections:

Lobby System (using Unet)
Game Server
Scene Loading

So, lets start with the first part:
As far as i know, when user decided to play the multiplayer part of the game, he is either creating new game for others to join, or joining an existing game. This process can be observed on the "Joining/Creating Game" screen.

What i'm actually can't figure out, is that if the game created on the users machine (lets name it local) or the Blizzard server (this will be remote). If it is created on the local machine, how then it is protects itself from cheating. If it is created on the remote machine, does that mean that for every 5 (just any number) players, i will have to start new copy of the game server (probably on the different port)

Moving to the second question:
This requires to run a "headless" version of the game on the server. Is there a possibility to create many different rooms for many players by using only one server instance, or will it require to run separate instance for every 5 players. Also, if player is playing in single-player mode, he seems to be also connected to the game server. Looks like the game server is performing all of the necessary calculations and player only sends in the commands for server to process (e.g, move me from 1,0 to 1,1) and after receiving the response, client interpolates the movement received from the server.

And finally, the third question:
Server may have many different scenes, but many players may be situated across many different scenes. There could also be dungeons and other player oriented stuff. So the question is, is it possible to achieve this goal using default Unity functionality.


texts:
I'm doing something wrong when trying to get bodies to collide using jBox2d & Slick2d. Here is have just my basic init, update, and render methods. Render and update seem to work fine for drawing (gravity effectively pushes the ball down, and will rotate if I apply an impulse).

I have a feeling I'm overlooking something when creating the edge, but I have no idea what. My shapes/bodies work fine in the testbed, but I'm having no luck in my standalone application. I have experimented with moving the edge body / ball body around, but it doesn't seem to have any effect.

    @Override
public void init(GameContainer gc, StateBasedGame sbg)
        throws SlickException {
    world = new World(new Vec2(0F, 9.8F), false);
    windowCenter = new Vec2(gc.getWidth() / 2, gc.getHeight() / 2);

    circleShape.m_radius = CONSTANTS.BALL_RADIUS * CONSTANTS.SCALE_FACTOR;
    circleFixtureDef.shape = circleShape;
    circleFixtureDef.density = 1f;
    circleFixtureDef.restitution = .6f;

    circleBodyDef.type = BodyType.DYNAMIC;
    circleBodyDef.bullet = true;
    circleBodyDef.position.set(windowCenter);
    circleBody = world.createBody(circleBodyDef);
    circleBody.createFixture(circleFixtureDef);

    bottomEdge.setAsEdge(new Vec2(0, gc.getHeight()), new Vec2(gc.getWidth(), gc.getHeight()));
    bottomEdgeDef.position.set(0f, gc.getHeight());
    bottomEdgeDef.type = BodyType.STATIC;
    bottomEdgeFixtureDef.restitution = .6f;
    bottomEdgeFixtureDef.density = 0f;
    bottomEdgeBody = world.createBody(bottomEdgeDef);
    //bottomEdgeBody.createFixture(bottomEdgeFixtureDef);

    ball = new Image("src/main/resources/bball.png");
    float shapeToImageFactor = ball.getWidth() / circleShape.m_radius;
    ball = ball.getScaledCopy(1 / shapeToImageFactor);
    circleBody.setUserData(ball);

}

@Override
public void render(GameContainer gc, StateBasedGame sbh, Graphics g)
        throws SlickException {
    Vec2 ballBodyPos = circleBody.getPosition();
    ball.draw(ballBodyPos.x, ballBodyPos.y);
}

@Override
public void update(GameContainer gc, StateBasedGame sbg, int delta)
        throws SlickException {
    world.step(delta, 10, 10);
    ball.setRotation((float)Math.toDegrees(circleBody.getAngle()));
    System.out.println(world.getBodyCount());
    if (world.getContactCount() > 0) {
        System.out.println("thank god, something hit another thing");
    }
}

Also, the commented out bottomEdgeBody.createFixture(bottomeEdgeFixtureDef) throws a NullPointerException, and I have no idea why. Could this be related to the body not being created properly?

The world body count is at 2 as I think it should be. I was also thinking that when setting the vector's Y position at my screen height, it's actually getting set at screen height meters rather than pixels. Am I overlooking something obvious?


texts: Rotation around arbitrary vector (using quaternions?)

texts:
I currently have a camera which orbits a specific target object, always looking at it.
The user can drag the mouse to move the camera left/right/up/down and the camera will move over the surface of a sphere of fixed radius (note, I clamp the vertical angle to ± 89°).
Currently it looks something like this...
// Store position of camera for future reference
private Vector2 rotation = new Vector2(120, 25);

// Was intended to be the vector from planet to target. Only works with `up`
private rotationalPole = Vector3.up;

if (isDragging) {
    rotation += new Vector2(
        Input.GetAxis("Mouse X") * xSpeed * radius * 0.02f,
        -Input.GetAxis("Mouse Y") * ySpeed * 0.02f);

}

//target is the GameObject to center on...

var pos = target.transform.position;

camObj.transform.position = pos + (Vector3.back * actualRadius);
camObj.transform.LookAt(pos, rotationalPole);
camObj.transform.RotateAround(pos, Vector3.right, rotation.y);
camObj.transform.RotateAround(pos, rotationalPole, rotation.x);

This works fine when up is in the y direction.
Now, however, instead of an object on the ground, the target is something in orbit around a planet (currently on an equatorial orbit but hopefully on an arbitrary one in future).
I want the camera to behave the same as before, but with up being the vector from the center of the planet through the target. Nominally forward will be the direction of orbit (but since the user can spin through 360 "horizontally", that's less important).
Currently it looks like this...

Basically, I'd like to rotate the image above counter-clockwise by 90° (which I believe I can do by playing with the camera transform's up and right vectors) but also that my arbitrary rotation honors the new orientation.
Some research shows that I need to use quaternions but while my mental model for basic trig is fine, I can't picture how to use quaternions correctly in this situation.
Following on from @Jon's answer below...
I've now got the following.
var planetToTarget = (target.transform.position - planet.transform.position).normalized;
// "Reset" the camera before I do any transforms
this.transform.position = target.transform.position - tgtMovement * actualRadius;
this.transform.up = Vector3.up;
this.transform.LookAt(target.transform.position);

var camToTarget = (transform.position - target.transform.position).normalized;
Debug.Log(string.Format("targetMotion = {0}, planetToTarget: {1}, camToTarget: {2}", tgtMovement, planetToTarget, camToTarget));

// Line that's not working...
this.transform.Rotate(camToTarget, -90);

// To be added in when the above is working...
//this.transform.Rotate(Vector3.Cross(camToTarget, planetToTarget), rotation.y);
//this.transform.Rotate(planetToTarget, rotation.x);
//this.transform.up = planetToTarget;

The uncommented code (excluding the last line) keeps the camera behind the target, looking forward...
Initially, I get :

targetMotion = (0.0, 0.0, -1.0), planetToTarget: (-1.0, 0.0, 0.0), camToTarget: (0.0, 0.0, 1.0)

Which generates:

However, as the target moves around the planet, it changes to:

targetMotion = (0.4, 0.0, -0.9), planetToTarget: (-0.9, 0.0, -0.4), camToTarget: (-0.4, 0.0, 0.9)

By which point, the camera is slewing to the side...

So I'm clearly still missing something. I don't appear to be rotating around camToTarget correctly?


texts:
Since FNT is a bitmap font I was thinking perhaps making the padding negative to the right and left side of the characters and rasterizing each glyph already skewed by an angle could make the font appear to be tilted. Does any one know whether FNT sports negative padding or whether Godot support some form of skewing that could accomplish that?
Please take a look at the image to see what I'm describing


texts: Experiencing strange behavior in Unity when rotating a 2D GameObject according to the slope it is standing on

texts:
I am trying to rotate a square GameObject, so it appears to be standing perpendicular to the slope underneath it. However, when above a slope, the square constantly "spins"; it seems like the rotation is set and then immediately set back to 0, causing it to jitter.
I am currently using a RayCast based character controller instead of rigidbody. To change the rotation, I added the follow line of code following the vertical RayCast:
if (_raycastHit)
    {
       transform.rotation = Quaternion.FromToRotation(transform.up, _raycastHit.normal) * transform.rotation;

    ...
    }

It calculates and rotates the square correctly, but I am not sure why it resets back to 0 every other frame. To avoid taking up too much space, the character controller I am using is hosted on GitHub here. Specifically, this is in the moveVertically() method.


texts: How do I Sync data from client to server?

texts:
I'm trying to Sync data from the client to the server using the new Unity Networking, and I'm failing for some reason.

I've set up a prefab with a NetworkIdentity component with the attribute Local Player Authority set.

I (manually) spawn that on the server, and it is correctly propagated to the clients.

I have a couple of vars on this class, which the client sets and the server should read:

public class PlayerController : NetworkBehaviour
{
    [SyncVar] public bool engineOn;
    [SyncVar] public Quaternion lookAt;

The client correctly sets them, however the server never receives them, they always stay at the default value.

What might be happening?


texts: Is it possible for a particle to have an infinite lifespan in SceneKit?

texts: I'm trying to do an experiment where the user creates particles when they touch the screen, and then the particles just stay in place, only dying in collision. I'm wondering if it would be possible to do this in a way where the particles have an infinite lifespan? I feel like I've done this in Unity before, but never in SceneKit.


texts:
I'm developing an RPG and am stuck trying to create a formula for attack speed, using four stats and a base speed.

Basically, I'm trying to get an outcome where the encumbrance (basically weight and ease of handling in a single stat) of armor and weapon along with the players´ strength and agility will effect the attack speed.

So - for example: A player with a heavy armor and a 2-handed maul might end up with 0.35 attacks per second, while an unarmored dagger-wielding player should have around 2.5 or even 3 (which would be the maximum speed).

Weapons and armor have an encumbrance stat. Players have agility and strength.

In order to make it more realistic, I'm trying to integrate the following into the formula:

The penalty from the total encumbrance of all items should have a smaller impact on the attack speed than the encumbrance of the weapon
The penalty from the weapon encumbrance should depend on both agility and strength
There should be a maximum attack speed (around 3 attacks per second)
Higher agility should result in higher attack speed
Higher strength should lessen the overall encumbrance penalty

I'm not yet sure if the ranges or min/max stats are needed for the formula, but currently player stats will range between 1-10 and encumbrance (per item) from 1-10 as well.

I've given this a couple of hours of thought but I feel that my math skills might simply not be up to par.

Here's the current state of my attempt (non-functional): https://docs.google.com/spreadsheets/d/1S_NOsJp-FegY7ruR6EZTqWRxuP6gDnZJr9LYw8ETZKQ/edit#gid=0


texts: Units issue when exporting from 3DS Max to XNA

texts:
I am working on a XNA game where we have defined that 1 XNA unit equals to 1 meter. Then, I set meters as system unit in 3DS Max and set to meters the units in the FBX exporter. However, when I export my models, they are much bigger in the game. Am I missing something? What should I do to avoid problems with my units?

Investigating the FBX file, I noticed that I it has two values called UnitScaleFactor and OriginalUnitScaleFactor. They both are 100 when I export the files... And if I manually change UnitScaleFactor to 1, it works fine :S


texts: Playing a death anim on an enemy that I want to remove

texts:
I've been trying to find a tutorial on how to best make animations in Android. I already have some animations for my enemies and my character that are controlled by rectangles and changing rectangleframe between updates using a picture like this:

When I'm shooting my enemies they lose HP, and when their HP == 0 they get removed. As long as I'm using an arrayList (which I do for all enemies and bullets) I'm fine, since I can just use list.remove(i). But when I'm on a boss-level and the Boss's HP == 0, I want to remove him and play an animation of an explosion of stars before the "End-screen". Is there a preferred way to do temporary animations like this?

If you can give me an example or redirect me to a tutorial, I'd be really grateful!


texts:
I have been trying for the past 5 hours to get this to work.

So i have an enemy that has the following script:

        private bool Look(StateController controller)
    {
        Debug.DrawRay(controller.transform.TransformPoint(controller.mCombatant._CombatOffset),  controller.transform.TransformDirection(Vector3.forward) * 800,
            Color.green);
        RaycastHit hit;

        if (Physics.SphereCast(controller.transform.TransformPoint(controller.mCombatant._CombatOffset), 360,
                controller.transform.TransformDirection(Vector3.forward), out hit, 800)
            && hit.collider.CompareTag("Player"))
        {
            controller.mCombatant.Target = hit.transform;
            controller.chaseTarget = hit.transform;
            return true;
        }
        else
        {
            return false;
        }

        return false;
    }

Now both my enemy (the one this script is attached to) and my player are on the default layer

Here are some images that shows the gameview:

As you can see from the above picture The "Ray" should hit the player:

My Player prefab looks like this:

So my question is what have i done wrong?

EDIT

So after alot of time i managed to make the following code work (however its a normal raycast :( )

    RaycastHit hit;

    if (Physics.Raycast(controller.transform.position, controller.transform.forward, out hit) &&
        hit.collider.CompareTag("Player"))
    {
        var g = 0;
    }

This is good but not good enough since i want the vision of my enemy to be more than a straight line :(


texts: How can I make a computer opponent for my board game?

texts:
I am trying to create a game, not exactly checkers, but the level of its interactivity is on par with checkers as opposed to something more complex (I think) like chess.

Anyway, according to my analysis, the UI, gameplay, player turns, time constraints, rewards are very easy to implement.

What I find hard is the actual CPU logic.

I'm looking at checkers as an example because I used to play checkers on my PC and Nokia long before sophisticated modern AI became a thing. Are there techniques used in old checkers games that I could use to calculate which of its moves is the most advantageous for it to win the game?

I would implement a logic on my own but I need a special algorithm to compute every possible move, and this will def take me a decade to implement.

I am sure there is a smarter and quicker way but I have no idea.


texts: How to make dynamic DOF from mouse position in Unity 5?

texts:
I found a video a while ago for how to make a dynamic DOF in unity. It fires rays from the camera and positions an empty at the location that the ray first hit. How can I change this so that it doesn't fire rays from my camera but rather from my mouse position, and then positions the empty from there?

Code:

public Transform origin; //Raycast origin
    public GameObject target;

    public CameraMovement cameraMovement;

    void Start () {

    }

    void Update () {
        Ray ray = new Ray(origin.transform.position, origin.transform.forward);
        RaycastHit hit = new RaycastHit();

        if(Physics.Raycast(ray, out hit, Mathf.Infinity)){
            Debug.DrawRay(Input.mousePosition, origin.transform.forward, Color.cyan);
            target.transform.position = hit.point;
        }else{
            Debug.DrawRay(Input.mousePosition, origin.transform.forward, Color.red);
        }
    }


texts: I'm currently drawing my character from a single file, and my sprite class handles it taking the file path as an argument. Now, I need to add a simple animation, cycling between two frames. The problem is that I have the other animation frame in another file, not in the same file as the first frame. How can I handle the animation without loading and unloading the two files and without merging the files into one?


texts: How do I reduce the size of my symbols.zip?

texts:
I am making an Android app in Unity.  Google recommends using a symbols.zip, which Unity auto-generates.  However, the symbols.zip that Unity is generating for my app is over 1 GB, and the max size that Google will accept is 300 MB.
How can I reduce the size of my symbols.zip?


texts: How to implement this collision detection function?

texts:
I would like to know how to implement this collision detection function, but I'm not even sure what it's called.

The input shapes are 2D convex polygons, with an optional "rounding radius": imagine putting a circle on each vertex of the polygon, and filling in the area between them.

I already have a function that uses SAT to tell if they intersect (and return a minimum correction vector), but I also need a function that takes two of these shapes, A and B, and a unit direction vector. It should tell whether A will ever touch B if it moves along the direction, and if so, report how far it could move and the surface normal where they would touch.

So how would that be implemented, or at least how is it called, so I could search for hints?


texts: Google Play Game Services (Unity Plugin) Turn Based Multiplayer List of Open Matches

texts: I took a closer look at Google Play games services Turn based multiplayer, and I cannot find out if I am somehow able to just get a list of all open matches, so that I can implement my own GUI. It seems really weird to me that they would not let you do such a simple task. Is this just a problem with the Unity implementation or is it a general problem? Using the Google UI would make a clunky feel which I would like to avoid.


texts:
I am trying to make a point-and-click adventure game with XNA, starting off simple. My experience with XNA is about a month old now, know how the classes and inheritance works (basic stuff).

I have a problem where I cannot understand how I should load and unload the textures and game objects in the game, when the player transitions to another level. I've googled this >10 times, but all I find is hard coding while I don't even understand the basics of unloading yet.

All I want, is transitioning to another level (replacing all the sprites with new ones).

Thanks in advance


texts: How write pixel by pixel with a fast way Allegro 5.01

texts:
I'm currently trying to do a black and white filter for my game in c++ with Allegro 5.01, I'm doing like this.

void    GameEngine::blackAndWhite()
{
    ALLEGRO_BITMAP *buffer  = al_get_backbuffer(this->windows);
    ALLEGRO_LOCKED_REGION *region = al_lock_bitmap(buffer, ALLEGRO_PIXEL_FORMAT_ARGB_8888, ALLEGRO_LOCK_READWRITE);
    unsigned char *ptr = static_cast<unsigned char *>(region->data);

    for (int x = 0; x != 640; ++x) {
        for (int y = 0; y != 480; ++y) {
        unsigned char   red;
        unsigned char   green;
        unsigned char   blue;

        this->getpixel(ptr, x, y, region->pitch, &red, &green, &blue);
        unsigned char result = (red + green + blue) / 3;
        this->putpixel(ptr, x, y, region->pitch, al_map_rgb(result, result, result));
        }
    }
    al_unlock_bitmap(buffer);
}

And putpixel and getpixel is like this.

void        GameEngine::putpixel(unsigned char *ptr, int x, int y, int offset_y,  ALLEGRO_COLOR color) {
    unsigned char   red;
    unsigned char   green;
    unsigned char   blue;
    unsigned char   alpha;

    ptr += (y * offset_y) + (x * 4);
    al_unmap_rgba(color, &red, &green, &blue, &alpha);
    *ptr++ = red;
    *ptr++ = green;
    *ptr++ = blue;
    *ptr = alpha;
}

void        GameEngine::getpixel(unsigned char *ptr, int x, int y, int offset_y,
unsigned char *red, unsigned char *green, unsigned char *blue)
{
    ptr += (y * offset_y) + (x * 4);
    *red = *ptr++;
    *green = *ptr++;
    *blue = *ptr++;
}

It's working, but it's really slow, I'm thinking it's slow because this operation is do by the CPU and not the GPU.

Is there a way for reduce the time of the operation with allegro or not ?


texts: Direct3D11 and SharpDX - How to pass a model instance's world matrix as an input to a vertex shader

texts:
Using Direct3D11, I'm trying to pass a matrix into my vertex shader from the instance buffer that is associated with a given model's vertices and I can't seem to construct my InputLayout without throwing an exception.

The shader looks like this:

cbuffer ConstantBuffer : register(b0)
{
    matrix World;
    matrix View;
    matrix Projection;
}

struct VIn
{
    float4 position: POSITION;
    matrix instance: INSTANCE;
    float4 color: COLOR;
};

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

VOut VShader(VIn input)
{
    VOut output;
    output.position = mul(input.position, input.instance);
    output.position = mul(output.position, View);
    output.position = mul(output.position, Projection);
    output.color = input.color;
    return output;
}

The input layout looks like this:

var elements = new[]
{
    new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
    new InputElement("INSTANCE", 0, Format.R32G32B32A32_Float, 0, 0, InputClassification.PerInstanceData, 1),
    new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 12, 0)
};
InputLayout = new InputLayout(device, signature, elements);

The buffer initialization looks like this:

public ModelDeviceData(Model model, Device device)
{
    Model = model;
    var vertices = Helpers.CreateBuffer(device, BindFlags.VertexBuffer, model.Vertices);
    var instances = Helpers.CreateBuffer(device, BindFlags.VertexBuffer, Model.Instances.Select(m => m.WorldMatrix).ToArray());
    VerticesBufferBinding = new VertexBufferBinding(vertices, Utilities.SizeOf<ColoredVertex>(), 0);
    InstancesBufferBinding = new VertexBufferBinding(instances, Utilities.SizeOf<Matrix>(), 0);
    IndicesBuffer = Helpers.CreateBuffer(device, BindFlags.IndexBuffer, model.Triangles);
}

The buffer creation helper method looks like this:

public static Buffer CreateBuffer<T>(Device device, BindFlags bindFlags, params T[] items)
    where T : struct
{
    var len = Utilities.SizeOf(items);
    var stream = new DataStream(len, true, true);
    foreach (var item in items)
        stream.Write(item);
    stream.Position = 0;
    var buffer = new Buffer(device, stream, len, ResourceUsage.Default,
        bindFlags, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
    return buffer;
}

The line that instantiates the InputLayout object throws this exception:

*HRESULT: [0x80070057], Module: [General], ApiCode: [E_INVALIDARG/Invalid Arguments], Message: The parameter is incorrect.*

Note that the data for each model instance is simply an instance of SharpDX.Matrix.

EDIT

Based on Tordin's answer, it sems like I have to modify my code like so:

var elements = new[]
{
new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 12, 0),
new InputElement("INSTANCE0", 0, Format.R32G32B32A32_Float, 0, 1, InputClassification.PerInstanceData, 1),
new InputElement("INSTANCE1", 1, Format.R32G32B32A32_Float, 16, 1, InputClassification.PerInstanceData, 1),
new InputElement("INSTANCE2", 2, Format.R32G32B32A32_Float, 32, 1, InputClassification.PerInstanceData, 1),
new InputElement("INSTANCE3", 3, Format.R32G32B32A32_Float, 48, 1, InputClassification.PerInstanceData, 1),
};

and in the shader:

struct VIn
{
    float3 position: POSITION;
    float4 color: COLOR;
    matrix instance: INSTANCE;
};

VOut VShader(VIn input)
{
    VOut output;
    output.position = mul(input.position, input.instance);
    output.position = mul(output.position, View);
    output.position = mul(output.position, Projection);
    output.color = input.color;
    return output;
}

However I still get an exception.


texts:
I am at the design phase of a board game on the iPhone and am considering a couple of options for rendering the view:

Quartz to render top down views of the board with core animation to do the transitions to close ups etc. Using a 3D library (or GL directly) to render dice rolls on top of the 2D view.
Full 3D interface to render the board and do the transitions (something like the Monopoly app on the iPhone).

Keeping most of the game in 2D simplifies the implementation and the artwork, but I wonder if the overall finish will suffer.  Is it practical to render 3D views (for the dice rolls) on top of a Quartz 2D app?

Should I just bite the bullet and go 3D?


texts: What is the best practice to handle event with order?

texts:
When you play card games, you always face some abilities and effects will be triggered at the same time. To resolve this, players relies on the rules. For example, if a minion dies, it triggers effects on my side and opponent side. If the effects is handled on my side first if it is my turn.

But how would you resolve it in computer games. Even you are using mediator for event handling, the event is usually handled by the order of subscription. Unless there are some indicators for the subscribers, you will not able to distinguish between the subscribers. But wouldn't it defeats the purpose of observer pattern? What is the best way implement it?


texts: Control Entity Moving Speed Without Using a Delay Function

texts: In a Tetris game I'm trying to make (using C++/SDL), I need to control the falling speed of, say, one block. I have successfully done this by incramenting its y value then setting SDL_Delay(200). So every 200 ms, the block moves down one unit. However, using SDL_Delay lags the whole game, and using the controls to move the block around gets delayed as well. I need to control the falling speed in a way that nothing gets delayed except the falling of the block. How can I achieve this? Thanks.


texts: How can I have a value increase by multiples of 10 in the inspector?

texts: I have a number that I want to be editable in the inspector.  However, I want to restrict that number to be a multiple of 10.  I can always just go into the code and set it to the nearest multiple of 10, but I'd rather force it in the inspector.  I am willing to use an int, float, Vector, or really any sort that can hold a number.  How can I do this?


texts:
i clicked a cube and added a simple transform animation by using animation timeline, and the cube has a "animator" component was added into the inspector. My questions are

how can i set the animation do not play automatically? I can't find any related option in animator in inspector
how can i set the script to control the animation? for example, play the animation after the scene started 5 seconds?


texts:
I want to create a rolling, textured ball in OpenGL ES 1.0 for Android. With this function I can create a sphere:

public Ball(GL10 gl, float radius)
{
    ByteBuffer bb = ByteBuffer.allocateDirect(40000);
    bb.order(ByteOrder.nativeOrder());

    sphereVertex = bb.asFloatBuffer();
    points = build();
}

private int build()
{
    double dTheta = STEP * Math.PI / 180;
    double dPhi = dTheta;

    int points = 0;

    for(double phi = -(Math.PI/2); phi <= Math.PI/2; phi+=dPhi)
    {
        for(double theta = 0.0; theta <= (Math.PI * 2); theta+=dTheta)
        {
            sphereVertex.put((float) (raduis * Math.sin(phi) * Math.cos(theta)));
            sphereVertex.put((float) (raduis * Math.sin(phi) * Math.sin(theta)));
            sphereVertex.put((float) (raduis * Math.cos(phi)));

            points++;
        }
    }

    sphereVertex.position(0);
    return points;
}

public void draw()
{
    texture.bind();

    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, sphereVertex);

    gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, points);
    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
}

My problem now is that I want to use this texture for the sphere but then only a black ball is created (of course because the top right corner s black). I use this texture coordinates because I want to use the whole texture:

0|0    0|1    1|1    1|0

That's what I learned from texturing a triangle. Is that incorrect if I want to use it with a sphere? What do I have to do to use the texture correctly?


texts: Imported model from Blender stops updating after applying scripts

texts:
I am new to Unity3D and I am trying to import a model from Blender. I save the .blend file inside the assets folder and everything works well. I drag and drop my model and apply textures, colliders and insert a player. Up until that point, I am able to change things in Blender, and see the changes inside Unity. But my problem begins when I try to apply scripts in my objects. Then the connection between Blender and Unity breaks and the model is not updated in the later.

What am I doing wrong? Any help would be much appreciated!! Thanks!!


texts:
I'm a little confused with this construction:

float sdcolor = MyColor.r; // MyColor has float4 type
float rcolor = sdcolor.rrr; // .ggg or .bbb isn't working

return float4(rcolor , rcolor , rcolor , 1);

Hence the question: how it's possible to subscript anything from a float type? What is the meaning of the .rrr subscript?


texts: How can I make my main character move in a parabolic arc when jumping?

texts: I'm entering Android game development, and I already have a computer version of a game I want to publish. The thing is, I want to make this as good as it can be. With that said, I need a physics engine, really to only do one thing: make a parabolic movement of my main character as he's jumping in the air. Currently, my computer version simply makes the guy move up at a 45 degree angle, and as soon as it hits the ceiling, down at a 45 degree angle. I need a physics engine/library that would accomplish that, it has to be in java since that's my best language, it has to be 2D, and it has to be able to work on Android. Which physics engine/library could accomplish all of that?


texts: Unity cloud build speedtree textures incorrect type after build

texts:
So I finally (after a few days) got unity cloud build to work.

When I build it using the unity editor everything is fine. However, when the cloud build service builds it I get some odd textures for my grass and trees:

Is there anything specifically I have to do to make sure this doesn't happen.

I don't know if it matters but I am using unity 2019.1 with HDRP.


texts: Improving Processes in One-Man GameDev Shops

texts:
As a hobby programmer, how can I incorporate a continuous-improvement-like process like Agile's retrospectives in my processes?

I've tried bullet items of three good/bad things at the end of each project, but I feel it's not enough. And I feel that a sprint retrospective is overkill. Where's the balance? How can and should I open the door for continuous process improvement?

Or maybe this question should go on the beta Project Management Stack Exchange site?


texts: How to arrange copies in circle that includes the cloned object not at the centre

texts:
I am using the editor code below to create copies of a game object in a circle with a given radius from the cloned object. The result is A in the image below, the cloned object at the centre with copies around. I want to achieve B, which has the game object (CircleSpawn) at the centre and the cloned object included in the copies that are created around the centre. The cloned object should be able to rotate and function in a way similar to it's copies. How can I fix my code to create this?

CircleSpawn

public class CircleSpawn : MonoBehaviour
{

public float radius, radiusLast, spin, spinLast;
public int numOfItems;
public GameObject clonedObject;
public List<GameObject> spawnedObjects;

}

CircleSpawnEditor

[CustomEditor(typeof(CircleSpawn))]
public class CircleSpawnEditor : Editor
{

public override void OnInspectorGUI()
{
    var tar = (CircleSpawn)target;
    tar.clonedObject = (GameObject)EditorGUILayout.ObjectField(tar.clonedObject,
        typeof(GameObject), true);
    if (!tar.clonedObject) return;

    EditorGUILayout.LabelField("Radius"); // Set as required
    tar.radius = EditorGUILayout.Slider(tar.radius, 0f, 5f);
    EditorGUILayout.LabelField("Angle"); // Set as required
    tar.spin = EditorGUILayout.Slider(tar.spin, 0f, 360f);
    EditorGUILayout.LabelField("Number of Items"); // Set as required
    tar.numOfItems = EditorGUILayout.IntSlider(tar.numOfItems, 0, 12);
    EditorGUILayout.LabelField("Object");

    float angle, angleBetween = 360.0f / tar.numOfItems;

    if (tar.spawnedObjects == null)
        tar.spawnedObjects = new List<GameObject>();

    if (tar.spawnedObjects.Count != tar.numOfItems)
    {
        foreach (var ob in tar.spawnedObjects)
            DestroyImmediate(ob);

        tar.spawnedObjects.Clear();
        angle = 0f;

        for (int i = 0; i < tar.numOfItems; i++)
        {
            var rot = Quaternion.Euler(0f, 0f, tar.spin + angle);
            var localPos = rot * Vector3.right * tar.radius;
            tar.spawnedObjects.Add(Instantiate(tar.clonedObject,
            tar.transform.position + localPos, rot));
            angle += angleBetween;

        }
    }

    if (!Mathf.Approximately(tar.spin, tar.spinLast) ||
        !Mathf.Approximately(tar.radius, tar.radiusLast))
    {
        tar.spinLast = tar.spin;
        tar.radiusLast = tar.radius;
        angle = 0f;

        for (int i = 0; i < tar.numOfItems; i++)
        {
            var rot = Quaternion.Euler(0f, 0f, tar.spin + angle);
            var localPos = rot * Vector3.right * tar.radius;
            tar.spawnedObjects[i].transform.position =
            tar.transform.position + localPos;
            tar.spawnedObjects[i].transform.rotation = rot;
            angle += angleBetween;

        }
    }
}
}


texts: Would it be inefficient to call LWJGL from C++?

texts: I like LWJGL, but Java? Not so much. I recently found out a way to call Java methods from C++. But would this be inefficient? I mean, calling a C/C++ DLL from Java, just to be called back again into C++? I don't know the native method names in LWJGL. I find it better then GLFW, SDL, and all those libraries. But other than my preferences, how slow would it be?


texts: Should I worry about variable time step for simple mobile 2d game

texts:
After going through some articles on framerate independent game design, i found that its not an easy task to implement in variable time steps(it is difficult compared to fixed frame rate, and considering my lack of understanding of variable time steps), I came across this answer.

According to this answer "option 1" [ its this if you dont want to open the link - Do nothing. Attempt to update and render at a certain interval, e.g. 60 times per second. If it falls behind, let it and don't worry. The games will slow down into jerky slow motion if the CPU can't keep up with your game. This option won't work at all for real-time multi-user games, but is fine for single player games and has been used successfully in many games.]

encourages me to not go for framerate independent design.


texts: Recreating Doodle Jump in Canvas - Platforms spawning out of reach

texts:
I have started to recreate Doodle Jump in HTML using Canvas. Here's my current progress. As you can see, if you play it for a few seconds, some platforms will be out of the player's reach. I don't know why is this happening. Here's the code which is responsible for the re-spawning of platforms.

//Movement of player affected by gravity
if(player.y > (height / 2) - (player.height / 2)) {
    player.y += player.vy;
    player.vy += gravity;
}
else {
    for(var i = 0; i < platforms.length; i++) {
        var p = platforms[i];

        if(player.vy < 0) {
            p.y -= player.vy;
            player.vy += 0.08;
        }

        if(p.y > height) {
            position = 0;
            var h = p.y;
            platforms[i] = new Platform();
        }

        if(player.vy >= 0) {
            player.y += player.vy;
            player.vy += gravity;
        }
    }
}

Also, here's the platform class.

//Platform class
function Platform(y) {
    this.image = new Image();
    this.image.src = platformImg;

    this.width = 105;
    this.height = 25;

    this.x = Math.random() * (width - this.width);
    this.y = y || position;

    position += height / platformCount;

    //Function to draw it
    this.draw = function() {
        try {
            ctx.drawImage(this.image, this.x, this.y, this.width, this.height);
        } catch(e) {}
    };
}

You can also see the whole code on the link I provided. Also, when a platform goes out of the view port, the jump animation becomes quirky. I am still trying to find out what's causing this but can't find any solution.


texts: Is it possible to simulate different vendor gamepads?

texts:
As a developer it would seem natural that I would like to support as many possible hardware compositions as I can, however as I'm not a big studio I have a limited budget, which means I have to get by with what I have.

For things like operating systems and internal hardware instead of trying to buy every single computer component out there I can simulate these combinations through a virtual machine environment.

This leaves a question: Is it possible to also somehow simulate various input devices and combinations of devices in a similar fashion?


texts: The need your game fills. Establishing your "hook."

texts:
I am a programmer and have worked on games although never attempted design myself. I am now attempting to design a game myself, working with a modest team of programmers and artists.

Game designers have been telling me it is important to establish the need your game fills, in order to develop a more complete vision of the product. I think in terms of mechanics and gameplay and am having trouble finding a "hook," even in existing games.

Any advice in identifying why a mechanic is fun, and what need a game fills, to help develop my own ideas is much appreciated.


texts: 2D Collision at corners using C# - without xna or unity

texts:
I'm trying to make collision for a 2D game, the player (car) has to collide with the walls of the track when it hits them. I looked into pixel color detection, and X,Y -based collision (But since its a race track, which isn't square, I don't think this will be the best solution. Correct me if I'm wrong).

I understand the concept of collision for straight lines or squares, but i have no idea how to make a perfect collision in the corners of the track. example race track.

I've been searching the web a lot for tutorials and documents on this subject, but failed to find any real examples that don't use XNA or Unity. I need to find a solution that doesn't include using any kind of game engine.

Any links / documents / code snippets, or even pseudo code snippets would really help me a lot.

An example would be: Per Pixel Collision , the thing about this link is that it uses xna, which i can not use.


texts:
How would level scrolling be implemented with haxe and nme?

I started plying with haxe and currently the only way to display things on screen is by using nme.display.Sprite.

I don't think changing the position of all sprites to scroll the level is the most efficient way of doing things.

I can't find any comprehensive example of how this should be done with haxe.

Any pointers?


texts:
I have an image and I want to make clickable this image. I have already done this a lot of times, but this time doesn't work. Probably because the image is from a class which extends Image:

public class BitmapFontGenerale extends Image
{

BitmapFont bitmapFont;
String scritta;
private float x;
private float y;

public BitmapFontGenerale(BitmapFont bitmapFont1, String string, float scale)
{
    bitmapFont = bitmapFont1;
    bitmapFont.setColor(Color.BLACK);
    bitmapFont.getData().setScale(scale);
    scritta = string;
}

@Override
public void draw(Batch batch, float parentAlpha)
{
    bitmapFont.draw(batch,scritta,x,y);
}

public void setX(float x)
{
    this.x = x;
}

public void setY(float y)
{
    this.y = y;
}

public float getX()
{
    return x;
}

public float getY()
{
    return y;
}

}

This is the code which I used to set the input:

image.addListener(new ClickListener()
{
    @Override
    public void clicked (InputEvent event, float x, float y)
    {
       Gdx.app.log("CLICKED ", "CLICKED");
    }
});
stage.add(image);
Gdx.input.setInputProcessor(stage);

This code works if image is from Image class and not if it's from a class which extends Image. Note: I need to extend Image class. What's the problem?


texts: How can I use the same number of tiles in any screen resolution, with an isometric projection?

texts:
I have an isometric grid with 64x32 diamond images. Each tile is a class, each instance is in a 2D array.

Players have different screen resolutions and the grid must take up the whole screen. Additionally, every player should always see the same tiles (so nobody has an advantage).

The only thing I could think of was to change the tile size: Bigger screen, bigger tiles.

I suppose I could do this by resizing my existing tile images, but is there a better way?


texts:
I am making simple 2D game, imagine it as 2D Minecraft where you can dig blocks and build other things.

Currently I am struggling with movement. I have none experience in game development, but I am quite familliar with C++, that is why I am using SFML.

What situations I am considering in movement:

Collision while moving on the X axis
Collision when jumping ( on the Y axis )
Fall down if there is no block under

My player sprite is 64x32 (h x w) and block is 32 x 32.
I store blocks as vector<vector<unique_ptr<Block>>> so I can calculate the index of the block as x_pos DIV 32, y_pos DIV 32

This is how I currently check if there is block ( X axis ):

new_position = actual_pos + velocity; // calculate new position
face_level = new_position.y DIV 32; // level 0 is the ground
feet_level = face_level + 1; // +1 is good, cause we increase level by going down
x_level = new_position.x DIV 32;
if (block_exists[feet_level][x_level] || block_exists[face_level][x_level]) {
    return Collision::Block_Collision;
}

and then check

collision = check_collision();
if ( collision == Collision::Block_Collision ) {
    // X axis
    stop_moving();
}
if ( collision == Collision::No_Block_Under ) {
    // falling
    fall_down;
}
if ( collision == Collision::Block_Above ) {
    // Y axis, actually do nothing, "dont jump"
}

If going left, I consider left border of the player.
If going right, I consider right border of the player.

This was the easiest part.

What position should I use for the falling part? Should it be the middle of the player, or left/right border combined ? If I used the middle position, then player would fall into the block if he was standing on the left/right half.

Question is, what would be the best approach generally to solve these 3 situations.


texts: I need to use dinosaur/dragon eggs in my game. I have found out this resouce from Behance.net. I am not sure how to download these resources. Can anyone help me with it.


texts:
I'm currently thinking about collision and map system that I want to use in my next game and I'm kind of puzzled. Maps are going to be somewhat complex with lots of irregularities and thus tiling is out of question.

I thought about an editor where you'd draw rectangles on the map that would represent areas that are collidable with and then saving such "collision map" with only black/white gfx. Or maybe should I save exact rectangles data with their x/y/width/height into some text file and go from there?

What would you recommend? Thanks.


texts: Sprites not being rendered on screen change - Android Libgdx

texts:
In my game over screen for my Libgdx Android game I've the following code which starts a new game upon a screen touch.

       if(Gdx.input.isTouched()) {
        ScreenManager.setScreen(new GameScreen());
    }

A new game starts but none of the sprites are displayed on screen.

I've confirmed that a new game has started through logging and through use of the debugger. Also the game over screen eventually reappears after some time due to the player dying.

What's interesting is that if I hit the home button or bring up the running apps menu in Android and re-enter the app, the sprites display fine.

Both my GameOver screen and Game screen are classes which implement a Screen interface

Anyone have an idea of what could be causing the sprites not to display?

Here is my ScreenManager class which can either set or get the screen.

public class ScreenManager {

private static Screen currentScreen;

public static void setScreen(Screen screen) {
    if (currentScreen != null) {
        currentScreen.dispose();
    }
        currentScreen = screen;
        currentScreen.create();

}

public static Screen getCurrentScreen() {
    return currentScreen;
}

}


texts: Is Quadtree Terrain Decimation applicable today?

texts:
It all started from that page.
https://www.gamasutra.com/view/feature/131841/continuous_lod_terrain_meshing_.php?print=1

I didn't quite got what it was all about, so I've looked at this.
https://www.researchgate.net/publication/3410916_Terrain_decimation_through_Quadtree_Morphing

Then I've got some understanding. It was about decimating the more distant patches of the terrain.
And then I've just wondered about one thing. At every frame, the mesh is re-generated and re-uploaded. Wouldn't it be kinda of slow?

Ran the demo provided in the first link and got just 3 fps. What's the big idea of this "optimization"?

My current code has 1048576 vertices for 1024x1024 heightmap, undecimated, and it runs way faster. His code makes my laptop hot.

Another link.
Quadtree vs multiple resolution grids for terrain rendering

That is more useful. It turns out that there might be some mipmapped meshes on the GPU, and the quadtree decides which of them are turned on.

The first question. Is my last guess correct?
Second - am I right the first link isn't useful anymore?
Third - how this applies to modern Android development (I mean at least GLESv2).


texts: Unity Custom Sprite Shader: Don't write transparent pixels into Depth Buffer

texts:
For performance reasons, i have to create my own billboards to replace some geometry. I modified the standard sprite shader to Cull Back and ZWrite On.
Now my billboard layers are rendered in the correct order, but the ones in the front cull the ones in the back, even on transparent areas. This is due to the shape of the Plane/Quad i used as basis.

You can see this on the following screenshots:

The transparent pixels are occluding the second layer.

Front piece drawn with white texture to show dimensions.

How can i modify my shader below to avoid drawing the transparent pixels into the depth buffer?

    // Unity built-in shader source. Copyright (c) 2016 Unity Technologies. MIT license (see license.txt)

    Shader "Sprites/DefaultSingle"
    {
        Properties
        {
            [PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {}
            _Color ("Tint", Color) = (1,1,1,1)
            [MaterialToggle] PixelSnap ("Pixel snap", Float) = 0
            [HideInInspector] _RendererColor ("RendererColor", Color) = (1,1,1,1)
            [HideInInspector] _Flip ("Flip", Vector) = (1,1,1,1)
            [PerRendererData] _AlphaTex ("External Alpha", 2D) = "white" {}
            [PerRendererData] _EnableExternalAlpha ("Enable External Alpha", Float) = 0
        }

        SubShader
        {
            Tags
            {
                "Queue"="Transparent"
                "IgnoreProjector"="True"
                "RenderType"="Transparent"
                "PreviewType"="Plane"
                "CanUseSpriteAtlas"="True"
            }
            Cull Back
            Lighting Off
            ZWrite On
            Blend One OneMinusSrcAlpha

            Pass
            {
            CGPROGRAM
                #pragma vertex SpriteVert
                #pragma fragment SpriteFrag
                #pragma target 2.0
                #pragma multi_compile_instancing
                #pragma multi_compile _ PIXELSNAP_ON
                #pragma multi_compile _ ETC1_EXTERNAL_ALPHA
                #include "UnitySprites.cginc"
            ENDCG
            }
        }
    }


texts: Can names of abilities or spells within a game be trademarked/copyright?

texts: Okay, say I want to create an RPG similar to and takes inspiration from such games as Final Fantasy, The Elder Scrolls, Shin Megami Tensei, Pokemon, etc. and I would like to use familiar names in some cases because the names simply fit from a design perspective (like from anything as mundane-but-aptly-named as "Water" or "Waterfall" to something like "Ultima" or "Souleater"). For the sake of the question I want to make it clear I'm not attempting a parody or the sort (it's going to be its own franchise), just most ability/spell names I can think of tend to come from video games or board games I've played.


texts: Unity Javascript GUI.Button shows up twice

texts:
Hi I have created a simple menu in Unity but I wanted to create my own style for colour/fonts.

However for some reason it prints each button twice to the screen, once with my custom style, and once without.

this is the code I have used:

if(menu){

if (GUI.Button(Rect(Screen.width/2 - 50, Screen.height/2, 100, 30), "Start Game", customGuiStyle)){

Application.LoadLevel ("Level 1");
}

if (GUI.Button(Rect(Screen.width/2 - 50, Screen.height/2 + 30, 100, 30), "Options", customGuiStyle)){

menu = false;
options = true;
}

if (GUI.Button(Rect(Screen.width/2 - 50, Screen.height/2 + 90, 100, 30), "Quit", customGuiStyle)){

Application.Quit();
}
}

I have no idea why it is showing two texts, heres a screen shot of exactly what I mean...


texts:
UPDATE 3:

I have fixed the issue by reordering my effects (see my answer for details.) Anyone who wants to post more information based on that answer (either in an answer or in the comments) would be greatly appreciated.

UPDATE 2:

I think the issue may be that I've been using the default Magenta as transparent rather than having actual alpha values. It's hard to tell through Monogame what magic is happening to make the Magenta transparent (note: I'm in a 3d camera and not using spritebatch.)

I will try this again tonight or tomorrow with a set of identical textures using an alpha value instead of magenta.

Looks like this was unrelated to my issue. I now have images that have proper alpha values rather than replacement color values and am still having the same issue.

I've been able to apply my shader to multiple layered textures, with the issue that I can't seem to get the alpha to detect in my shader.

As you can see in the picture, the Alpha values for the Turret and the Tank-body are not being multiplied in properly ("derp.a") meaning that the lighting pass is hitting certain pixels 2x-3x based on how the textures overlap.

Full shader pasted below:

//Texture2D currTexture : register(s0);
sampler currSampler : register(s0);
/*{
    Texture = (currTexture);
    AddressU = clamp;
    AddressV = clamp;
};*/

float4x4 xViewProjection;
float3 tankpos;
float4 shotpos;

struct VertexToPixel
{
    float4 Position : POSITION; // Can't use in pixel shader, but required for it
    float4 Color : COLOR0;      // color for the vertex?
    float2 rPos : TEXCOORDS0;   // world position of the texture
};

struct PixelToFrame
{
    float4 Color : COLOR0;
};

VertexToPixel SimplestVertexShader(float4 inpos : POSITION)
{
    VertexToPixel output = (VertexToPixel) 0;
    output.Position = mul(inpos, xViewProjection);
    output.rPos = inpos.zx;
    return output;
}

PixelToFrame LightAroundAShot(VertexToPixel PSIn)
{
    PixelToFrame output = (PixelToFrame) 0;
    output.Color = PSIn.Color;
    float x = (PSIn.rPos.x * 0.02 - shotpos.z * 0.02) * 1 / (1 + shotpos.w);
    float z = (PSIn.rPos.y * 0.02 - shotpos.x * 0.02) * 1 / (1 + shotpos.w);
    float4 derp = tex2D(currSampler, float2(PSIn.rPos.x, PSIn.rPos.y));

    output.Color.g += (0.75 - sqrt(x * x + z * z)) * shotpos.w * derp.a;
    output.Color.br += (0.35 - sqrt(x * x + z * z)) * shotpos.w * derp.a;

    return output;
}

technique Simplest
{
    pass Pass0
    {
        VertexShader = compile vs_4_0_level_9_1 SimplestVertexShader();
        PixelShader = compile ps_4_0_level_9_1 LightAroundAShot();
    }
}

I've attempted to use curr texture at the top in a couple ways and can't seem to find the voodoo to get it working. Any help understanding the relationship (especially in monogame) between Textures, Samplers, and how to get that darn "derp" alpha to apply correctly would be great.

Note: When I tried using curr texture I was setting it before each call of the graphics device so that it'd be the appropriate texture. I've also attempted to register them in various ways to s1, different ways of setting the texture in graphics device. I'm truly stuck at the moment.

Thank you for any help!


texts: GLFW3. Destroying and create new window results in a black window

texts:
I am trying to write a fullscreen toggle handler and running into an issue.

In order to change between fullscreen and windowed I need to destroy the current window and create a new one with the 'monitor' parameter changed. I have written this and the program changes between windowed and fullscreen fine. However the new window that is created is not being rendered to and is black.

For simplicity I have reduced the code to the following that just creates a new window with the same parameters:

/* generic set up stuff */

//main draw loop
while (!glfwWindowShouldClose(window)) {

    /* generic draw stuff */

    if (GLFW_PRESS == glfwGetKey(window, GLFW_KEY_F)){
        glfwDestroyWindow(window);
        window = glfwCreateWindow(g_gl_width, g_gl_height, "Title", NULL, NULL);
        glfwMakeContextCurrent(window);
    }
}

When the program first loads everything renders fine. When I hit F, a new window is created but it stays black.

Any ideas?

Kind regards.


texts: IOS very simple 2d engine/api rendering showdown

texts:
So after taking some time running through a course, I believe I have enough experience with referring back to the course how to make the game I wish to all apart from one thing. How to draw the game on screen, I know how the game would work behind the screen, but don't know how to draw it. I'm looking for an experienced, informed answer based upon certain factors.

To provide some context, the game in question's interface would be very simple:

Grid of lines
Control each cell's content: (text and colour)
Pan and zoom

The game at the minute is based upon an excel spreadsheet as shown to show how simple it is:

My aim to keep this question open to others is to create a pros and cons of each.

I've narrowed down possibilities to this list. These are taken from the apple developer page under the section 'Graphics and Games':

Core Animation
Core Graphics
GLKit
Metal
OpenGL ES
cocoas 2d?
Other Noteworthy

I'm asking for an informed opinion as to which I should choose. This is narrowed down from research, however I assume I will have missed things that may make this task much easier. My problem thus far is that most games assumed I needed sprites but in something this simple I'm assuming I don't.

If it makes any difference, my current knowledge is only swift, high school math and hopeful abundance of learning resources. I've been stuck with this problem for a long time and I would be overjoyed if I could get some experienced advice. Thanks! :)


texts:
Games like Dwarft Fortress and Dungeon Crawl Stone Soup are drawing their boards using tiles from a tileset image (I think?). I know you can do color keying and replace the background color with transparency or another color, but how are games like these drawing the text characters into different colors? Using the same method? I am trying to find the best way to use a tilesheet to draw ascii graphics and be able to choose what color the text is, and what color the background of the tile is separately.

Something similar to what is pictured here.


texts: How can I scale by time a canvas scaler > scaler factor float value from 0.01 to 1?

texts:
The minimum is 0.01f the maximum I want it to be is 1
I want that when I start a Coroutine to be able to decide the time it will take to change the value to 1 and also the direction if from 0.01 to 1 or from 1 to 0.01
I tried this :
if (buttonType == "LoadGame")
        {
            StartCoroutine(DisplaySavedGamesWindow(5f, true));
        }

And
IEnumerator DisplaySavedGamesWindow(float time, bool direction)
    {
        float scaler = GameObject.Find("Save Slots").GetComponent<CanvasScaler>().scaleFactor;

        float currentTime = 0;
        while (currentTime < time)
        {
            scaler = currentTime / time;
            currentTime += Time.deltaTime;

            yield return null;
        }
    }

I used a break point on the line :
scaler = currentTime / time;

I see that scaler is changing up to 1 or to 0.9 ot sure why it's not getting to 1
And also it's not changing the value to 0.9 or to 1 in the editor in the scale factor it's still 0.01
Also how to use the bool flag ? true should be from 0.01 to 1 and false from 1 to 0.01
Ok I managed to make it working to be changed up from 0.01 to 1 :
IEnumerator DisplaySavedGamesWindow(float time, bool direction)
    {
        float currentTime = 0;
        while (currentTime < time)
        {
            var scaler = currentTime / time;
            GameObject.Find("Save Slots").GetComponent<CanvasScaler>().scaleFactor = scaler;
            currentTime += Time.deltaTime;

            yield return null;
        }
    }

The problem now is that when it's changing the value from the script the result is gray.
This is how it looks like when I'm changing it to 1 in the editor :
You can see the blue scroll view on the left :

but when it's changing the value from the script the result is gray scroll view and not blue like before :


texts: How to Load PDF file in runtime using PDF Renderer Asset in unity?

texts: Hello Guys : I am working in Unity PDF Renderer. I will purchased that Asset but i need to Know, How to load PDF file one by one in run time in File path mode but old PDF File will remove and Load new PDF file in run time. can any one help


texts: Is there a difference between analytics and telemetry?

texts:
We are developing a mobile game (using Unity3D). We report various game analytics events to our backend systems so they can be aggregated and analyzed later on.

I've recently watched this session from GDC on game telemetry: http://www.gdcvault.com/play/1012227/Development-Telemetry-in-Video-Games

I was wondering whether telemetry and analytics were in fact the same thing? They seem to be related to one another, although may have different use cases...


texts:
I have been working on a P2P architecture for secure gaming and I have divided the problem into five sub-problems:

Unlawful modification of sent game state
Accurately drop cheaters
Agreeing on a game state
Avoiding "look ahead" cheat
Hiding sensitive information from opponents

The first four I have pretty much all solved but it is the last one which I am having trouble with.

Before I go into details I just want to ask if there's anything I've missed in my list of making a "cheat proof" p2p network. I am not interested in cheats such as using aimbots, I am only interested in making the p2p network as secure as a centralized server.

So in my effort so far on hiding sensitive information I've focused on the position of players in a game where the position of your opponent should not always be known. The problem then becomes how to determine if you should send you position to your opponent without knowing the position of your opponent.

I have ruled out methods such as the opponent sending multiple false positions for you to compare yours too since your opponent can easily abuse such a system since he will get your position if one of the false positions happened to be "visible" from your position.

The method I have been focusing on one in which you receive a "visual field" from your opponent and can thereby determine if you should send your position or not. This is however a problem in games such as League of Legends where the visual field of your opponent is also highly sensitive information. I have tried to solve this by transforming the visual field using a singular matrix meaning you cannot go from the transformed version of the visual field back to the original version, but since it is a linear transformation you can still figure out if your position is inside the visual field or not.

This does not however work perfectly, the exact visual field cannot be restored after transformation, but information about the "slopes" in the visual field (the visual field is constructed by several lines, and the slope of each line can be determined) can be restored and this can be used to relatively inexpensively  reconstruct the original visual field.

In essence, what I need is a function which can determine if a position is "visible" or not, and reconstructing this function/visual field has to be so computationally demanding that once you are done reconstructing the visual field it is no longer relevant for the game in action. Is there any super smart person out there who happens to know of such a method?

Edit
People seam kind of confused about the whole "vision field" so I aim to give a more detailed explanation here. The vision field consists groups of a set of lines, you can easily check if a position is inside one of these groups by just checking which side of the line your position is, if it's on the same side for all lines in that group you know it's inside that group and thus inside the vision field.

The information being sent however is not this line, but a transformation of the line and the transformation (2 by 2 singular a matrix), you can still check which side of the line your position is on by first transforming it using the transformation you received and comparing that value to the transformed line. The key here is that the transformation is singular, meaning it is impossible to find an inverse to go back to the original line. However it is possible to determine the slope of the line which makes reconstructing the line by just checking on which side of the transformed line a lot of points lie until you have pinpointed the origin of the line a lot computationally cheaper than if you did not know the slope of the line.

What I am looking for is a method for determining if a point is inside of an area, where reconstructing the area from the method is either impossible (which I doubt exists since you can always brute force it) or very computationally heavy.


texts:
I made a simple OpenGL program but I can figure out why the camera is not working, here it's a little fragment of the Camera class:

public Matrix4f getView() { // initializes the view matrix
    return new Matrix4f().lookAt(
            new Vector3f(0f, 0f, 1f), // camera position at 0,0,1
            new Vector3f(0f, 0f, 0f), // camera target at 0,0,0
            new Vector3f(0f, 1f, 0f)); // up axis set to "worldUp" (0,1,0)
}

public Matrix4f getProjection() {
    return new Matrix4f().perspective(
            (float) Math.toRadians(fieldOfView), // the fov has a value between 0f and 180f, by default I set it to 90°
            viewportAspectRatio, // the aspect ratio is equal to 1024 / 960 (screen height / screen width)... even if I've not understood what is it...
            0.1f, 1000f); // I've not really understood what near and far planes are...
}

public Matrix4f getMatrix() { // with this function I obtain the final camera matrix
    return getView().mul(getProjection());
}

And it's how I handle the camera Matrix in GLSL, created using camera.getMatrix():

gl_Position = camera * model * vec4(position, 1.0);

Without the camera all is fine: here's the program running using gl_Position = model * vec4(position, 1.0);:

(Yeah, it's a cube)

But using the camera in the way I showed you before, increasing the FOV, I get this:

Could anyone look at my code and tell me where I'm wrong? I would be really happy... D:


texts: How do I contiguously store and iterate over ECS components in C++?

texts:
I'm writing an entity component system and want to store each type of component separately and contiguously in memory in a way that's easy to iterate over.
Component is a simple base class from which like classes like MoveComponent derive.
I store components inside the World class:
struct World {
    ...
    std::vector<Component> components;
};

This would work fine if there was only one type of component, just a Component class. The problem is I don't know how to handle component subclasses. For example every MoveComponent should be stored contiguously in memory in a way that I can easily iterate over and process them.
I want to avoid this kind of copy-paste junk code for hopefully obvious reasons:
struct World {
    ...
    std::vector<MoveComponent> move_components;
    std::vector<PhysicsComponent> physics_components;
    etc.
};

I'd like to instead structure it in a way that permits iterating over each component of a certain type in a World like, for example, this (inspired by Overwatch's entity component system video, see here):
for (MoveComponent *mc : ComponentIterator<MoveComponent>(world)) { ... }

I'm at a loss as to how to implement this.


texts: How should I design my classes in a game?

texts:
I'm stuck for ideas on classes in game programming. This is probably more of an opinion based question. I'm looking for information that is proving hard to find on the internet.

Say I have a class called  Bullet or Mob, the name doesn't really matter it's just an example. With this, there are two options I can think of.

Have the class purely as a way of storing data and nothing else. So I could have, for example, properties such as EntityID, Velocity, HealthPoints, NumberOfAttacks.
I would then have some other part of the game which iterates through every instance of every object and update the properties from there.

Example: During the iteration, it checks what type of object it is, such as Bullet etc. Once it has checked this, it will calculate where the bullet should move to next based upon the Velocity property.
Or, have the same properties within the class, but also have all the code for updating it's own properties in there too. Example: The bullet has some kind of Update() method which get's called periodically by the game engine. This Update method would then take it upon itself to calculate the new Velocity and update it's position etc.
Some combination of the both? Something else I haven't thought of?

Which of these options is the more commonly used approach in game programming? What are the benefits or disadvantages of these different methods?

Have I got it all completely wrong?


texts: After using Unity's Destroy() function, I see the Prefab Clones are now called "New Game Object" is this a problem?

texts:
I use a prefab to generate several gameobjects which I then get rid of with the Destroy() function.

I noticed the clones, when destroyed are replaced with "New Game Object".  Because of the nature of the game there would be thousands of these created throughout the course of the game.

Is this expected behavior, or is there something I'm perhaps doing wrong where the Destroy isn't really getting rid of it completely?


texts: Can Unity4 and Unity5 projects coexist in the same computer?

texts:
I've Unity5 installed (free edition). When I started with Unity3D I did with 5 and never had the 4 before.

A friend has passed me legacy code of a 90% complete game he used to do with Unity4 as he no longer wants to dedicate to videogames, for me to use that to finish it.

If I load that code into the Unity5, the "automatic upgrader" starts to do lots of changes. And finally the thing does not play. Says All compiler errors have to be fixed before you can enter playmode!

The thing is he used some third-party libraries, like the tk2droot among others and seems that the code of that and other dependant libreries is rather old, so I do not only need to scan over his code for the "v4 to v5 upgrade changes" but also I've to scan all his dependencies, which is rather a suicide at least for an initial contact like "let's just see if this compiles".

Questions:

Is there any way make Unity5 "behave" as Unity4 so it does not do the code-upgrade
and it uses the old API? Ie: Compile v4-code within v5-IDE?
Alternatively, is is possible to freely install Unity4 parallel to Unity5 so they do not interact and I am able to compile his source un Unity4 while doing the new things in Unity5?

The easiest solution I can find is to have 2 computers, one with Unity4 and the other with Unity5 but seems a but weird to me. I'm sure I'm not the only one with this problem.

How do game developers with codebases in Unity4 and Unity5 make all the workflow?

PD: Focusing on Android now only. No need to publish for iOS, web, consoles, etc.

Thanks.


texts: What are screen space derivatives and when would I use them?

texts:
I see the ddx and ddy glsl functions and the hlsl equivalents come up in shader code every now and then. I'm currently using them to do bump mapping without a tangent or bitangent but I basically copy-pasted the code. I don't understand what these functions actually are, what they do, and when I would look to use them.

So questions:

What are the screenspace derivatives functions?
What do these functions do? The input values and output values
What effects are they most commonly used for?
What sort of effects require that you look toward these functions?


texts: Bounds Queries for Simplex Noise Function

texts:
How do I construct a Bounds Query for 3D Simplex Noise?

[This is more or less a follow-up to my last question]

Simply put, for an arbitrary octree node (cube) in my volume (a section of Unity3d world space), I am trying to find out whether there is a surface inside the octree node (to determine if I need to subdivide my octree node). As explained in the other question, I cannot rely on edge-crossings to detect if a node contains a surface or not. Right now, I query each Vector3 integer coordinate in my volume (appropriately scaled by ~1/50) for a simplex noise value.

I was directed to bounds queries, where instead of querying for a specific point by supplying specific coordinates, I query for a [min,max] of the function in a certain volume (my octree node). If min > 0 or max < 0, I need not subdivide, because the surface is outside my node (the surface intersects edges between vertices with different polarity/signs).

What (I think) I understand so far:

At every simplex vertex, the value is 0. This means that my minimum is not greater than 0, and my maximum is not less than 0. Turns out, because of my scaling, a single octave of simplex noise usually just puts 2 simplex vertices in my volume. Does this mean that my bounds query will require I subdivide every node that contains one of these simplex vertices? This is obviously wrong, else I would be subdividing infinitely...
If I do not have any simplex vertex in my node, I still have to find the vertices' unit vectors of the simplices my node exists in. Then, somehow, I decide on a min/max. I suppose, it would come down to the nature of the simplices I am in...If they both give positive/negative values, then my bounds query would pass, and I wouldn't need to subdivide...right? But how do I calculate this?
To construct the bounds query, I must find the pseudo-random unit vector assigned to each simplex vertex found in my node. This allows me to view the range of possible values in each simplex found in the node.

(I hope that all wasn't too confusing)

Despite/Because all that, I can't for the life of me think up any algorithm. What am I missing?

If there are any resources on this, please point me to them! I've googled about every keyword-loaded phrase I can come up with, but found nothing.


texts: Displaying intersection by removing vertices

texts:
I am using WPF, using the MeshGeometry3D class to build up my model.

I have 2 pipes intersecting each other, and I would like to remove the region of intersection (meaning erase the portion of pipe 1 that lies inside of pipe 2).

I have tried to solve the problem by solving for the points(vertices) that exist inside the pipe, and deleting it from the list of vertices.

However, it does not seem to work, since (i assume) that the primitives are represented by triangles, and if I were to remove the points, the triangles would no longer exist and the model will fall apart.

My question is that considering this, is there any method that I can try to remove the intersecting regions?


texts:
I'm have trouble with my model rotating around it's own Y-axis. The model is a person.

When I test my world, the model is loaded at a position of 0, 0, 0. When I rotate my model from there, the model rotates like normal. The problem comes AFTER I moved the model to a new position.

If I move the the model forward, left, etc, then try to rotate it on it's own Y-Axis, the model will rotate, but still around the original position in a circular manner (think of yourself swing around on a rope, but always facing outward from the center).

Does anyone know how to keep the center point of rotation updated?


texts: Guidelines to create textures for materials in Unity3d

texts:
I'm facing a problem with realizing particle systems.
Following many tutorials including the recent live session everything end up assigning materials to particle to get custom shape ones.

What I'm having troubles to find is some guide to create those materials or, for the sake of being clear, to create textures to assign to the materials in order to have the desired shape.

Browsing the internet I thought I found something useful until I noticed that the link in the answer is reserved to authorized reader, making it a totally useless answer (no quotes of the contents at all).

By downloading some free cool asset like the Elemantals one, I learned a lot of things on how to combine different systems in order to get complex and spectacular visual effect but, as previously said, everything ends up with the need to create my own textured materials if I want to obtain something original.

So my question is:
where can be found guidelines in creating textures for particle materials? Is there any keyword I should look into (like texture mapping, uv mapping, bump mapping, normal mapping and so on) or (even better) any good tutorial straight to the point?


texts: How do multiple expansions to a game typically should be implemented?

texts:
Let's say I have a game that's finished and shipped, what would be the approach that is typically taken in regards to future content such as expansions? I'm not talking about programmatic implementation. I'm talking about how to integrate it to the base game, especially for multiple expansions.

If I finished making Expansion Pack 1 which adds new locations, new quests that tie in to the base vanilla game, etc, and then later down the line, I finish Expansion Pack 2 as well, how do I handle if the player only bought Expansion Pack 2 without making it feel disjointed in relation to the lack of Expansion Pack 1?

Or should I make all older expansions mandatory before being able to use the latest one?

In short, I'm trying to wrap my head around implementing multiple expansions without any of the expansions being mandatory but at the same time, I don't want them to feel "tacked on" to the base game as a side content (meaning, they should be integrated into the game's world). I want them to feel like an actual part of the world. Just that they're optional.


texts:
Okay so After all this Edits here is the main question. How I can generate Terrain with a 2d Simplex Noise Algorithm, I am deletng old info so the post its more readble. I´ve been doing some tests and here are my results so far. Any help is appreciated. Any Ideas why my code isnt working?

I am far from getting a good result, Here is an Image, I am using The Simplex Noise genrator Timothy oferred to me (thanks :D)

And Heres is the Code:

public void GenerateChunk(float offsetX, int amplitude, long seed)
{

    // Its += 16 Because each block is 16 pixels
    for(int x = 0; x < CHUNK_SIZE * CHUNK_SIZE; x += 16)
    {
            PerlinNoise.genGrad(seed);
            float height = (float) PerlinNoise.noise(x, 0);
            System.out.print(height);

            for(int y = 0; y < height * 16; y += 16){

                try {

                    Block B = new Block(Material.DIRT, x, y + 400, new Image("res/Dirt.png"));
                    Blocks.add(B);
                    B.setVisible(true);

                } catch (SlickException e) {

                    e.printStackTrace();

                }

            }

     }
}

Here its where I call it

world.getChunk(0, 0).GenerateChunk(4, 12, 1231233876); // 12312 etc is a test number for the seed.

Finally here is the example output (height value)

0.0-0.3244323-0.4746854-0.6980603-0.212961030.437604370.0-0.013018643-0.3333134-0.49871972-0.498743-0.226263150.43900093-0.305881470.026026215-0.341923240.0-0.3244323-0.4746854-0.6980603-0.212961030.437604370.0-0.013018643-0.3333134-0.49871972-0.498743-0.226263150.43900093-0.305881470.026026215-0.34192324


texts: Interpolation of render with fixed physics update

texts:
In Fix Your Timestep, they briefly address the remainder time in relation to rendering.  Saying that remainder can be used to generate an interpolated rendering.

  We can use this remainder value to get a blending factor between the
  previous and current physics state simply by dividing by dt. This
  gives an alpha value in the range [0,1] which is used to perform a
  linear interpolation between the two physics states to get the current
  state to render.

http://web.archive.org/web/20190506030345/https://gafferongames.com/post/fix_your_timestep/

So let's say your last two physics updates we'll call A and B are from 00:10.033 and 00:10.066, and it is now 00:10.070 when we want to perform a render.  We have a remainder of .004.

I take "interpolation between the two physics states" to mean we compare all the objects in update A and B and slide them back from B towards A by 88% (.033-.004)/.033).  This would mean I'm actually rendering the physical state at 00:10.037, correct?  So my physics updates A and B are really more like previous and next and my interpolation is between the previous and the next, correct?


texts:
In Age of Mythology and some other strategy games, when you select multiple units and order them to move to some place, they make a "group" when they reach the desired location:

I have a Vector with several sprites, which are the selected units, the variables tarX and tarY are the target x and y. I just want an example, so you can just set the x and y position and I can adapt it to my code. Also, I would like to ask that the algorithm calls "isWalkable" for the x and y position, to determine if it's a valid position for each unit.


texts: How to protect source code when game is developed in HTML5/Javascript

texts:
Possible Duplicate:
  How do you prevent your JavaScript / HTML5 web game from being copied or altered?

If a game client is developed in Javascript, the source code can be found in browser. It's dangerous, because it's easy to hack the game, and patent can't be protected.

Are there any good ways to avoid this, e.g Javascript can be compiled to binary file then browser load and run the compiled javascript?


texts: What Do I Pass for inputGeometryTransform Parameter of ID2D1Geometry::CompareWithGeometry?

texts:
I have a list of ID2D1Geometry objects and I'm trying to use CompareWithGeometry to detect collisions in Direct2D; unfortunately, I'm not getting the results I need.  I suspect I am improperly using the inputGeometryTransform parameter.

If I pass in D2D1::Matrix3x2F::Identity() or nullptr for this parameter, I almost always get D2D1_GEOMETRY_RELATION_CONTAINS (3) or D2D1_GEOMETRY_RELATION_IS_CONTAINED (2) results back for the returned D2D1_GEOMETRY_RELATION.  On the other hand, if I try and pass in the product of the scale and translation matrices that I used to generate the primary geometry, then I never get collisions.

Can someone help me understand what I need to pass in for the inputGeometryTransform parameter?

The source code that I believe to be relevant appears below:

// This is Shawn Eary's broken code and it is licensed 2012 under the
// Microsoft Public License (Ms-PL) which is compatible with the
// Open Source Initiative
//
// Shawn Eary is not affiliated with Microsoft.
// He just likes the Ms-PL
void SpaceObject::updateDynamics(
    Microsoft::WRL::ComPtr<ID2D1DeviceContext> const i_d2dContext,
    D2D1::Matrix3x2F const & tranformMatrix)
{
    D2D1_SIZE_F renderTargetSize = i_d2dContext->GetSize();
    float const worldWidth = renderTargetSize.width / 2.0f;
    float const halfWorldWidth = worldWidth / 2.0f;
    float const worldHeight = renderTargetSize.height / 2.0f;
    float const halfWorldHieght = worldHeight / 2.0f;

    // Update the position in ideal coordinates
    double idealX = m_p.x + m_v.x;
    double idealY = m_p.y + m_v.y;

    // Account for wrap around
    m_p.x = getWrappedResult(idealX, worldWidth);
    m_p.y = getWrappedResult(idealY, worldHeight);
    m_p.theta += m_v.theta;

    m_v.x += m_a.x;
    m_v.y += m_a.y;
    m_v.theta += m_a.theta;

    // Compute results of elastic collisions
    for (list<SpaceObject *>::iterator it = m_myObjectWorldP->begin(); it != m_myObjectWorldP->end(); it++) {
        SpaceObject * const SOP = (*it);

        // This eventually needs to be fixed, but for now assume all
        // spaceObjects are GeometrySpaceObjects
        GeometrySpaceObject * thisGSOP = dynamic_cast<GeometrySpaceObject*>(this);
        GeometrySpaceObject * currentGSOP = dynamic_cast<GeometrySpaceObject*>(SOP);

        // Don't compare this SpaceObject with itself
        if (thisGSOP != currentGSOP) {
            ID2D1PathGeometry * const thisGP = thisGSOP->gGeoP();
            ID2D1PathGeometry * const curGP = currentGSOP->gGeoP();
            D2D1_GEOMETRY_RELATION theRelation;
            thisGP->CompareWithGeometry(
                (ID2D1Geometry *)curGP,
                tranformMatrix,
                &theRelation
            );
            if (theRelation != D2D1_GEOMETRY_RELATION_DISJOINT) {
                // A Collision has occured.
                //
                // Use conservation of momentum to update
                // velocities after collission here
                int placeHolder = 0;
            }
        }
    }

    this->updateAcceleration();
}

Note: At the time I asked this question, the documentation I found on the MSDN site was a bit unclear regarding the inputGeometryTransform Parameter.  The documentation I viewed was visible at this URL: http://msdn.microsoft.com/en-us/library/windows/desktop/dd316638(v=vs.85).aspx


texts: How can I make the main game loop frame-rate independant?

texts:
I am trying to create a frame independent game loop.

I am currently using the following code

 private class MainGameThread extends Thread {
        public static final int PAUSE_SLEEP_TIME = 10;
        long previous = getCurrentTimeInMillis();
        long totalElapsed = 0;
        long gameTimeStart = 0;
        long currentTime = getCurrentTimeInMillis();
        long accumulatorTime = 0;

        @Override
        public void run() {
            gameTimeStart = getCurrentTimeInMillis();
            while (mIsRunning) {
                // Pause game
                while (mIsPaused) {
                    try {
                        Thread.sleep(PAUSE_SLEEP_TIME);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                long current = getCurrentTimeInMillis();
                long elapsed = current - previous;
                previous = current;
                processGameInput();
                updateGameState(elapsed);
                totalElapsed += elapsed;
                if (totalElapsed > MainGame.MS_PER_FRAME) {
                    drawGame();
                    totalElapsed -= MainGame.MS_PER_FRAME;
                    if (totalElapsed > MainGame.MS_PER_FRAME) {
                        Log.e("GAME", "Performance warning, rendering or update took too long");
                    }
                }
                checkIfGameShouldStop(gameTimeStart);
            }
            shutdownGracefully();
        }

        private void shutdownGracefully() {
        }
    }

It works, however it performs differently on different devices.

In my game models update method I am performing the following actions

  mCenterX += (mVelocityVector.x * timeElapsed);
  mCenterY += (mVelocityVector.y * timeElapsed + gameSpeed.getValue())

I have read this article, but I can't understand the final example:

double t = 0.0;
double dt = 0.01;

double currentTime = hires_time_in_seconds();
double accumulator = 0.0;

State previous;
State current;

while ( !quit )
{
    double newTime = time();
    double frameTime = newTime - currentTime;
    if ( frameTime > 0.25 )
        frameTime = 0.25;
    currentTime = newTime;

    accumulator += frameTime;

    while ( accumulator >= dt )
    {
        previousState = currentState;
        integrate( currentState, t, dt );
        t += dt;
        accumulator -= dt;
    }

    const double alpha = accumulator / dt;

    State state = currentState * alpha +
        previousState * ( 1.0 - alpha );

    render( state );
}

What does the State class object mean in this case?

Could someone please help to adapt this example to my case or explain the example from the article and how I could update my loop to be frame independent?


texts: Obtaining a world point from a screen point with an orthographic projection

texts:
I assumed this was a straightforward problem but it has been plaguing me for days.

I am creating a 2D game with an orthographic camera.  I am using a 3D camera rather than just hacking it because I want to support rotating, panning, and zooming.  Unfortunately the math overwhelms me when I'm trying to figure out how to determine if a clicked point intersects a bounds (let's say rectangular) in the game.

I was under the impression that I could simply transform the screen point (the clicked point) by the inverse of the camera's View * Projection matrix to obtain the world coordinates of the clicked point.  Unfortunately this is not the case at all; I get some point that seems to be in some completely different coordinate system.

So then as a sanity check I tried taking an arbitrary world point and transforming it by the camera's View*Projection matrices.  Surely this should get me the corresponding screen point, but even that didn't work, and it is quickly shattering any illusion I had that I understood 3D coordinate systems and the math involved.

So, if I could form this into a question: How would I use my camera's state information (view and projection matrices, for instance) to transform a world point to a screen point, and vice versa?  I hope the problem will be simpler since I'm using an orthographic camera and can make several assumptions from that.

I very much appreciate any help.  If it makes a difference, I'm using XNA Game Studio.


texts: Unity3D: Modifying Animator Controller parameters

texts:
I have this GameObject with an AnimatorController. The AnimatorController has several states in which I want to parametrize the animation's speed because configuration. For this, I've created an animation parameter, called "RotationMultiplier" and set up the "Speed/Multiplier" value to this paramter on the needed states.

Now, my idea is being able to configure this speed from a script "somewhere." I've read a bit about StateMachineBehaviours, but my initial idea was executing this once, instead of once in each frame/state.

The "OnStateMachineEnter" function does not execute at all, and with the OnEnable I don't have access to the Animator (nor the parameters).

So, any idea?


texts: How do I reconstruct depth in deferred rendering using an orthographic projection?

texts:
I've been trying to get my world space position of my pixel but I'm missing something.

I'm using a orthographic view for a 2.5d game. My depth is linear and this is my code.

    float3 lightPos  = lightPosition;
    float2 texCoord = PostProjToScreen(PSIn.lightPosition)+halfPixel;

    float depth = tex2D(depthMap, texCoord);

    float4 position;

    position.x = texCoord.x *2-1;
    position.y = (1-texCoord.y)*2-1;
    position.z = depth.r;
    position.w = 1;
    position = mul(position, inViewProjection);
    //position.xyz/=position.w; // I comment it but even without it it doesn't work

    float4 normal = (tex2D(normalMap, texCoord)-.5f) * 2;
    normal = normalize(normal);

    float3 lightDirection = normalize(lightPos-position);
    float att = saturate(1.0f - length(lightDirection) /attenuation);
    float lightning = saturate (dot(normal, lightDirection));

    lightning*= brightness;
    return float4(lightColor* lightning*att, 1);

I'm using a sphere but it's not working the way I want. I reproject the texture properly onto the sphere but the light coordinates in the pixel shader seems to be stuck at zero even if I move the light volume update properly.


texts: How to scale-to-fit OGL viewport to GLFW window?

texts:
Say my window is 1280x720. I want to render my stuff to lower resolution and then stretch it to window. I've tried this:

glViewport(0, 0, 1280 / 2, 720 / 2);

When I call glViewport and pass lesser width and height than window, I get all my OpenGL rendering in left bottom 1/4 of window. I need to scale it (linear filtering preferably) back to window size so I would get a pixelated effect.

I wonder if there is such possibility within glad/glfw API.


texts:
I am having trouble executing a raycast to check if there is anything between the player sprite and a second sprite. This is my code :

    void Start () {

        play1 = GameObject.Find("player");
        game1 = GameObject.Find("lightidle_0");
    }

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

        Vector3 playpos = play1.transform.position;
        Vector3 gamepos = game1.transform.position;
        Vector3 defvector = new Vector3 (1, 0, 0);

        Ray playray= new Ray (playpos, defvector);

        float distance = playpos.x - gamepos.x;

        if (distance > 0) {
            Debug.Log (Physics.Raycast(playray,distance));
        }
        else {  defvector = -defvector;
Debug.Log (Physics.Raycast(playray,distance));
}

So supposedly, if there is anything between both objects, Raycast should return true. But it is always stuck on false, I have debugged, and tried everything, its value never changes, no matter where both objects are located, I added 2 huge colliders on both sides of the scene and it still outputs false.

I also added a Debug.DrawRay (playpos, defvector * distance); but the ray isn't drawn at all, so it means that is the reason of the error, but why? I can't figure it out.


texts: Having trouble initializing jagged array ('Object reference not set to an instance of an object' error)

texts:
As per https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/jagged-arrays
I have initialized my jagged array as follows:

private float[][] bulletBehaviour;

void Start()
{
    float[][] bulletBehaviour = new float[1][]
    {
        new float[4] {12.0f, 0.3f, 0.5f, 0.5f} // [typeSelected][speed, size, lifeTime, fireRate, damage]
    };
}

Then any time I try to use bulletBehaviour elsewhere it gives the error in the title.
Note: There will be more arrays eventually (if I can get them working)

Thanks!


texts: What is the term for the level progression paradigm in Bejeweled?

texts:
Looking at the various level progression paradigms for my puzzle game, I decided to rule out the common ones such as 3-star per level, linear campaign-like story, etc. I like the idea of Bejeweled's classic mode where the player simply keeps on going.

What exactly is this paradigm called? I can't find any write-ups on it so I can't quite tell what its structure is like. Is it infinite? Does the difficultly increase with each level in some shape, way or form (more likely to get "No moves")?


texts:
I added a particle system to the flame-emitting object in my Unity scene. But it's just little white balls, and I can't figure out how to make it fiery.

Anyone?

Everything I see on the internet involves buying some asset pack that somebody put together. Does Unity really not have any built in flames stuff?


texts: How to export an animation from blender to Ethan (third person character) in unity 5

texts: I've made a human animation in blender with the intention of exporting it into unity to add to the animations of the third person character 'Ethan'. Does any one know how I can export the animation into unity for the third person character and make a trigger for the animation?


texts:
Enemies in this game take cover. AFAIK HL uses some logical decisions for enemy to start searching for cover and to abandon cover, and I am able so far to find them; but how does he find a cover place?

I know HL has waypoints. I can only guess/speculate how they find cover point. They might search for nearest waypoint which has certain properties; I thought such node might have some "cover" tag but tutorials seem not to mention it; so maybe it is a node which is not visible by player AND offers attack possibility (crate or edge of wall).

Thank You. :)


texts: How do I calculate impulse when an object collides with plane(fixed object)?

texts:
I've been developing simple 3D impulse-based physics engine.
I calculate impulse as follows:
$$j_r = \frac{-1(1+e)v_r\cdot\hat n}
{m_1^{-1}+\bbox[yellow,5px,border:2px solid red]{m_2^{-1}}+(I_1^{-1}(r_1\times\hat n)\times r_1+
\bbox[yellow,5px,border:2px solid red]{I_2^{-1}(r_2\times \hat n)\times r_2)}\cdot \hat n}
$$
where:
  \$e\$ is restitution constant
  \$\hat n\$ is a contact normal
  \$v_r\$ is relative velocity of the contact point
  \$m\$ is mass of objects
  \$I\$ is moment of inertia tensor
  \$r\$ is a vector from center of mass to contact point
Note: I've been assigned value 0.0f to the boxed/highlighted terms in the expression when an object collides with plane.
Then update linear & angular velocity as below:
$$
\begin{align}
v'_1&=v_1-\frac{j_r}{m_1}\hat n \\
v'_2&=v_2+\frac{j_r}{m_2}\hat n
\end{align}
$$
$$
\begin{align}
\omega'_1&={\omega}_1-j_rI_1^{-1}(r_1\times\hat n) \\
\omega'_2&={\omega}_2+j_rI_2^{-1}(r_2\times\hat n)
\end{align}
$$
Those expressions are referenced from the Wikipedia collision response entry.
It works well when two objects collide.
However, the box object rotates strangely and continuously glide around when it collides with plane as below:

(red sphere is detected contact point)
I set contact normal as plane normal.
I assume that the expression has to be modified for the case of fixed object (ex. plane).
I've been assigned value 0.0f to the boxed/highlighted terms in the expression when an object collides with plane.
Is this approach right?
If it isn't, how can I fix this?


texts: Transformation order when dealing with Meshes

texts:
I have created a player model out of primitive types. To do this I have created a Model class and  Component (mesh) class. Each model consists of one or more components my problems start when you have to rotate the model as a whole. When you manually create a mesh, you have to also specify it's origin, my problem is that the player is not rotating, before it worked somewhat (it turned each mesh indivialy) but then I changed the order of the Matrices and now it doesn't rotate at all, I think it is my matrix order:

effect.Parameters["World"].SetValue(Matrix.Identity *  Matrix.CreateTranslation(component.RelativePosition) * Matrix.CreateRotationY(player.Rotation.Y) * Matrix.CreateTranslation(player.Position)  * Matrix.CreateTranslation(player.Model.Origin));

How can I fix this?

Edit:

The update code is (I added the "0, 0, -1" so I can actually see it) but it is rotating each component idividally rather then as a whole model:

effect.Parameters["World"].SetValue(Matrix.CreateTranslation(-player.Model.Origin)  * Matrix.CreateRotationY(player.Rotation.Y) * Matrix.CreateTranslation(component.RelativePosition) * Matrix.CreateTranslation(player.Position) * Matrix.CreateTranslation(0, 0, -1));