texts:
I've been creating a game on my own in LIBGDX, BOX2D and there' s a problem I can' t solve. When two World bodies collide, method "beginContact" is called in MyContactListener class that implements ContactListener interface.

How am I supposed to change player's healthpoints when it's fixture collides with other bodies' fixtures. I know I have to do this somehow through MyContactListener class, but I can' t find the way how to call the method I need..

Note: My player's body and fixture are created in "Player" class and there are methods "setRemainingHealth()" and "getRemainingHealth()".

Here's also some code, which might illuminate this situation.

MyContactListener.java

package utils;

import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.ContactImpulse;
import com.badlogic.gdx.physics.box2d.ContactListener;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.Manifold;

public class MyContactListener implements ContactListener {

@Override
public void beginContact(Contact c) {

    Fixture fa = c.getFixtureA();
    Fixture fb = c.getFixtureB();

    if (fa == null || fb == null) return;
    if (fa.getUserData() == null || fb.getUserData() == null) return;

    if (isTunnelMachineCollision(fa, fb)) {
        // call somehow method "player.setRemainingHealthPoints(player.getRemainingHealthPoints-0.01f)" here
    }

}

@Override
public void endContact(Contact c) {

}

@Override
public void postSolve(Contact c, ContactImpulse arg1) {

}

@Override
public void preSolve(Contact arg0, Manifold arg1) {
    // TODO Auto-generated method stub

}

private boolean isTunnelMachineCollision(Fixture a, Fixture b) {
    return (a.getUserData()) == "terrain" && (b.getUserData()) == "machine";
}

}

TestPlayer.java

package testPackage;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.World;

public class TestPlayer {

private float remainingHealthPoints = 3;

private CircleShape shape;
private CircleShape defenseBarrier;
private Fixture defenseBarrierFixture;
private Fixture mainBody;
private BodyDef bodydef;
private Body body;

private float x;
private float y;
private float width;

public TestPlayer(World world, float x, float y, float width) {

    this.x = x;
    this.y = y;
    this.width = width;

    bodydef = new BodyDef();
    bodydef.type = BodyType.DynamicBody;
    bodydef.position.set(x, y);
    bodydef.fixedRotation = true;
    body = world.createBody(bodydef);

    shape = new CircleShape();
    shape.setRadius(width);
    mainBody = body.createFixture(shape, 1.0f);
    mainBody.setUserData("machine");
}

public float getRadius() {
    return shape.getRadius();
}

public BodyDef getBodydef() {
    return bodydef;
}

public CircleShape getShape() {
    return shape;
}

public Body getBody() {
    return body;
}

public void activateDefenseBarrier(World world) {

    defenseBarrier = new CircleShape();
    defenseBarrier.setRadius(width*1.5f);

    defenseBarrierFixture = body.createFixture(defenseBarrier, 1.0f);
    defenseBarrierFixture.setUserData("defenseBarrier");
}

public void destroyDefenseBarrier() {
    if (defenseBarrierFixture != null) {
        System.out.println("olemas");
        body.destroyFixture(defenseBarrierFixture);
        System.out.println(defenseBarrierFixture);
    }
    else {
        System.out.println("fixture on null");
    }
}

public Fixture getDefenseBarrier() {
    return defenseBarrierFixture;
}

public float getRemainingHealthPoints() {
    return remainingHealthPoints;
}

public void setRemainingHealthPoints(float remainingHealthPoints) {
    this.remainingHealthPoints = remainingHealthPoints;
}

}


texts: Joystick servo control axis value when idle (unity)

texts:
When the joystick servo control is idle (user not moving it) , i don't believe the axis value will be 0 because there's a lot of thing that interfere with the value (such as calibration , inaccuracy , physics problem in real life , ect . . ) . Is anybody have tested at which range the joystick servo control axis value is safe to be considered as idle? (both negative and positive) . I'm looking for constants here.
To anyone confused what does i meant with joystick servo control , picture below :
(ps : not my image, i found it on google)


texts: How can I integrate someone well into my project?

texts:
I am working alone, since over one year on a decent sized project... to speed up things i wanted to incorporate some friends into development, unfortunately i never  did something like this before and so i dont know where to start.

What is important to work as a team ? What should he know, see and understand ? And what shouldnt he be aware of ? And most important, how would you integrate someone into your project ?


texts: Unity 2D graphical glitch cuts sprite diagonally

texts:
While making a game in unity, we found a graphical glitch that only happens on one of our mobile devices (a htc) where the screen will be oddly sliced by a triangle as shown in this image;

I've searched online but found no problem. We're using unity 2D, it only does it on the HTC but we have no idea why.
The background is a 3D quad with a texture wrapped around it (so we can make it move with the character when the character is running, without having one large background).
Any help would be greatly appreciated.
Thanks


texts: I want to make a very simple 2D game, and have been reading a lot of good things about LÖVE, so I want to try it out. However I can't seem to find any good tutorials. The ones on the LÖVE page are rather unstructured, and the other one I found by Mathew Casperson is not very useful. Does anyone know of a better tutorial?


texts: Unity LWRP Sprite Renderer Sorting incorrectly after upgrading

texts:
I'm making a project where every tile is a sprite renderer, this would work fine in the old unity system (from the fact that it used it until recently), but upgrading to the LWRP broke the sorting of the sprite renderers. Previously, I didn't have to change the order at all, but now they phase in and out of each other based on the position of the camera, like the picture shown below. They all use LWRP/2d/Sprite-Lit-Default, as any other of the LWRP materials do not use the texture from the sprite renderer and instead make it all black.

I do not want to use sorting layers because I have meshes sprinkled in, and what i have seen there is no way to control if the mesh is on anything but order 0, besides some hacky way. Even using a box mesh it gets cut off when the floor is closer to the camera.

Here is what it looks like far away, the floor should be there the entire time and not have the darkness of the walls seeping down into them.

I don't think I can use mesh renderers either, as I want a way to control the texture from each individual object, and share a material through all of them. I think if I used a mesh renderer I would have to use a material for each different tile, and I would not be able to tile them like I am doing now.


texts: Can't get world position from reverse Z buffer

texts:
I'm using this solution to render using a reversed Z buffer.

This looks fine and completely fixes all my z-fighting, but it breaks what I use in shader to derive the world position from the depth for various purposes such as deferred lighting and fog (it has worked for a regular projection matrix):

vec4 screenSpacePosition = vec4(texcoord * 2.0 - 1.0, depth * 2.0 - 1.0, 1);
vec4 worldSpacePosition = invProjView  * screenSpacePosition;
vec3 finalPosition = worldSpacePosition.xyz / worldSpacePosition.w;
return finalPosition;

I've thought that this was due to this using a single view projection matrix, so I've also tried this:

vec4 clipSpacePosition = vec4(texcoord * 2.0 - 1.0, depth * 2.0 - 1.0, 1.0);
vec4 viewSpacePosition = invProj * clipSpacePosition;
viewSpacePosition /= viewSpacePosition.w;
vec4 worldSpacePosition = invView * viewSpacePosition;
return worldSpacePosition.xyz;

That must be suboptimal performance wise, but it doesn't work either anyway. Any idea what I'm missing?


texts: Character getting stuck when colliding from the top

texts:
when my character goes onto a box that I am trying to make him collide with he gets stuck. The way I have it configured is that at the end of every frame, the characters x and y values are stored in old x and old y, and if he is colliding with the box his x and y are reverted to old x and old y. This seems to work when walking into the box, but when the character jumps on the box he gets stuck and can't move. I think this has something to do with his x and y being infinitely pushed to oldX and oldY, but I don't know how to fix this. Thanks for the help!

 for(int x = 0; x < collidables.length; x++){
        if(collidables[x] instanceof QuestionBox){
            collidables[x].bottomCollision(mario);
        }

        if(mario.intersects(collidables[x].boxRectangle)){
            mario.setMarioX(mario.oldX);
            mario.setMarioY(mario.oldY);

        }
    }

        mario.oldX = mario.getMarioX();
        mario.oldY = mario.getMarioY();

Here is the code for what happens upon a collision.
Thanks for the help!


texts: iOS: OpenGL ES 2.0 render texture with glScissor performance

texts:
I have drawn image with OpenGL and will redraw tile of its texture (non filled area).

Which case will work faster?

Set glViewport with full texture's rect, draw full texture and use glScissor with updated area's rect.
Set glViewport with updated area's rect and draw tile of texture with calculating its texture coordinates.

I've found in Apple's documentation, that scissor test is called after fragment shader. Does this mean, that fragment shader will work with pixels of full texture? How slower will it be rendered than case 2?

SOLVED:
I've viewed pipeline scheme of OpenGL ES 2.0 here. Scissor test is done before fragment shading and allow to optimise rendering.


texts: In the game loop, apply dt before the loop starts, or after it finishes?

texts:
Say I have a Game class with an update loop that receives a time increment dt by parameter.
I was wondering if it's better or customary to apply this dt before the loop starts or after the loop finishes.

class Game
{
    void Update(float dt);
    float m_time;
}

dt is the delta time from last update loop.

m_time is the total accumulated time since the game started running.

Option 1:

void Game::Update(float dt)
{
    m_time += dt;
    /*
    do stuff
    */
}

Pros: I think it's more clear.
Cons: No update loop is processed at m_time = 0. The very first update loop already has m_time = dt.

Option 2:

void Game::Update(float dt)
{
    /*
    do stuff
    */
    m_time += dt;
}

Pros: The update loop starts at m_time = 0.
Cons: I find it a bit weird that the time is updated after all the processing has finished.

Any advise on which option is better or preferred over the other?


texts: I'm working on a small game library for me and some people I know that just handles the window and nothing special that we weren't gonna use. I know how to use OpenGL and stuff I just don't like having to deal with more then one library at a time like OpenGL and Swing so I want to combine them into something basic. Anyway my question is, is there any way I can use OpenGL's rendering onto Swing? I need a simple answer. I also don't want to have to include other libraries into my library, I just want it to be the only jar in the program that isn't program specific.


texts: In game level editor using AIR or stand alone app using Java or C#

texts:
I'm in the process of choosing technologies to build the level editor of a Flash RPG game.

On one side I can use AIR and build a ingame level editor that's probably going to give the best result. The problem is, I think it will be very hard, I don't have good memories using the UI libraries of AS3. I think that would take at least 3 more times (to build the editor) than the other approach.

Or I can use some mature set of tools to build the editor, like the ones commonly used with C# or Java.

The question is: Is it worth the trouble to build the editor in AIR? Or using a stand alone editor is just fine?

EDIT: Me and my team are the only people using this editor.


texts: libgdx - Problem occurring after collision detected

texts:
I have just implemented collision detection in my little 2d rpg-like game. I'm using Tiled for the maps, mechanism is simple - I have one layer called 'collision' in my tiled map, and while loading this map in game, I'm adding Rectangle objects to the tiles in 'collision' layer.
Therefore, when player's rectangle overlaps tile's rectangle, collision is detected. My problem is - what proper action should be taken after this detection?
Note - my player object has field like (float) movementSpeed, (Vector2) position. By pressing arrow keys player moves in a particular direction, algorithm looks like:
Keys.RIGHT clicked ---> player.position.x += movementSpeed;
Keys.DOWN clicked ---> player.position.y -= movementSpeed;
...and so on.
The REAL problem begins here - after collision has been detected, I'm adjusting player's position, just like in code below.

public void adjustPosition() {
    switch (currentMove) {
        case UP:
            position.y -= movementSpeed;
            rectangle.set(position.x, position.y, playerWidth, playerHeight);
            break;
        case DOWN:
            position.y += movementSpeed;
            rectangle.set(position.x, position.y, playerWidth, playerHeight);
            break;
        case LEFT:
            position.x += movementSpeed;
            rectangle.set(position.x, position.y, playerWidth, playerHeight);
            break;
        case RIGHT:
            position.x -= movementSpeed;
            rectangle.set(position.x, position.y, playerWidth, playerHeight);
            break;
    }
}

But it doesn't work as expected - after spamming arrow keys in different directions near the collision tile, player somehow is put onto the collision tile or is going just through it (and player definitely shouldn't be able to do so).
My question is - what should I do after collision has been detected in such a situation?


texts: Camera follows object and has a target object on the y-axis

texts:
I have two capsule objects in a split screen shooter. At this moment, the first camera follows player one, and has the target player two. The second camera follows player two, and has the target player one.

It feels a bit strange to play, because the game has different platforms with different height. How can I only follow the target along the y-axis?

The followed object shouldn't change at all. It should only look at the target. This is what I have, so far:

using UnityEngine;
using System.Collections;

public class CameraFollow : MonoBehaviour
{
    [SerializeField]
    private float distanceAway;
    [SerializeField]
    private float distanceUp;
    [SerializeField]
    private float smooth;
    [SerializeField]
    private Transform followedObject;
    [SerializeField]
    private Transform target;
    private Vector3 toPosition;

    void LateUpdate()
    {
        toPosition = followedObject.transform.position - target.transform.position;

        GetComponent<Camera>().transform.position
            = followedObject.transform.position + toPosition.normalized *distanceAway;

        transform.LookAt(followedObject);
    }
}


texts: How to implement lockstep model for RTS game?

texts:
In my effort to learn programming I'm trying to make a small RTS style game. I've googled and read a lot of articles and gamedev q&a's on the topic of lockstep synchronization in multiplayer RTS games, but am still having trouble wrapping my head around how to implement it in my own game.

I currently have a simple server/client system. For example if player1 selects a unit and gives the command to move it, the client sends the command [move, unit, coordinates] to the server, the server runs the pathfinding function and sends [move, unit, path] to all clients which then moves the unit and run animations. So far so good, but not synchronized for clients with latency or lower/higher FPS. How can I turn this into a true lockstep system?

Is the right methodology supposed to be something like the following, using the example from above:

Turn 1 start

gather command inputs from player1
send to the server turn number and commands
end turn, increment turn number

The server receives the commands, runs pathfinding and sends the paths to all clients.

Next turn

receive paths from server, as well as confirmation that all clients completed previous turn, otherwise pause and wait for that confirmation
move units
gather new inputs
end turn

Is that the gist of it? Should perhaps pathfinding and other game logic be done client side instead of on the server, if so why? Is there anything else I'm missing? I hope someone can break down the concept, so I understand it better.


texts:
This is the game level prototype I have already implemented. It has few objects per room to allow me to finally add some collision detection/response code into it.

VIDEO

As you can probably see, every object inside has it's own AABB, even the room itself has AABB. Also my player is inside the Room's AABB.

My player will be exactly inside the room, so he would have to collide correctly with those AABBs, so that when he hits any of those objects inside he get's a proper collision response from those AABB's.

Now I would like to hear from you what kind of collision approach should I choose in here?

How do I approach this kind of stuff:

AABB to AABB collision detection then when this is positive go with AABB - Try to find proper plane normal and calculate response ?
AABB to AABB then when positive go with AABB - AABB Side check to find proper plane normal and calculate response?
Anything else?

How do you do this ?

Many thanks.


texts: Flip sprite vertically AND horizontally?

texts:
In Microsoft.Xna.Framework.Graphics.SpriteEffects there is the possibility to flip a texture horizontally or vertically before rendering. But can one do both at the same time?

When I use: spriteEffect = SpriteEffects.FlipHorizontally | SpriteEffects.FlipVertically; with spriteEffect being a parameter of the particle. The method spriteBatch.Draw(spriteSheet,
                        currentPositionForDraw,
                        sourceRectangle,
                        currentColorMultiplied,
                        currentRotation,
                        currentOriginForDraw,
                        Temp.delta,
                        spriteEffect,
                        0); does not draw the particle flipped on both axis.


texts: How can I render a circular progress bar procedurally?

texts:
I'm working in Flash AS3, but pseudo-code or any other language is fine.

How can I make a circular progress bar?  Akin to the ship bars in Pax Britanica, you can see them in the screenshot here.

Apart from making them frame by frame, is there some obvious solution I'm missing here?

I'm seeking the equivalent of stretching a rectangle for a regular progress bar, or using a simple mask (if such a solution exists).

(Also I can't tag this with circle or progress bar due to lack of rep if anyone could that would be great)


texts:
I' having a problem rotating a body with setTransform(), The body has multiple sensors that should rotate with the player. The rotation works but it rotates around the bodys local 0,0 position instead of the center. Note that the game is in a top-down perspective and the player can go in four different directions, thus I need to rotate him immediately (in one tick) in 90 degrees steps.

Up:

Down:

I can't find a way to set the rotation center.

Here's the code I use to rotate it:

float angle = direction * 90 * MathUtils.degRad; // direction is an int value from 0 to 3
body.setTransform(body.getPosition(), angle);

I also tried body.getLocalCenter().set() and body.getMassData().center.set() but it didn't seem to have any effect. How can I rotate the body around its center?

EDIT (added code to create fixtures):

This is the method to create a fixture:

private Fixture createFixture(FixtureDef fixtureDef, Body body) {
    PolygonShape ps = createPolygon(); // creates a polygon shape from XML config
    fixtureDef.shape = ps;
    Fixture fixture = body.createFixture(fixtureDef);

    if (fc.filter != null) {
        fixture.setFilterData(fc.filter);
    }
}

This is the simplified code to create the fixtures (they are really loaded with xml config but these are the values I set):

FixtureDef sensorDef1 = new FixtureDef();
sensorDef1.friction = 0;
sensorDef1.restitution = 0;
sensorDef1.isSensor = true;
sensorDef1.center = new Vector2(0.8f, 1.6f);
// and some filters

FixtureDef sensorDef2 = new FixtureDef();
sensorDef2.isSensor = true;
sensorDef2.center = new Vector2(0.8f, 1.6f);
// and some filters

FixtureDef sensorDef3 = new FixtureDef();
sensorDef3.isSensor = true;
// and some filters

createFixture(sensorDef1, body);
createFixture(sensorDef2, body);
createFixture(sensorDef3, body);


texts: How to prevent bullets from passing right through entities?

texts:
(sorry for bad english)

I'm making 2D arcade game. I write all of physics stuff myself. The problem involves bullet behaviour. Imagine bullet flying towards some entity. If the bullet's velocity is relatively high and the entity is small, the bullet passes right through the entity which is obviously not what it's meant to do. Here's the gif that shows why that happens (values are exaggerated to better show the process):

As you can see bullet's velocity is simply bigger than the size of the entity. Then I came up with this:

Getting point of impact coordinates means I can check if the distance between the point of impact is smaller than the bullet's velocity. If the distance is smaller then bullet should collide with the entity at the point of impact. But I don't know how to calculate the coordinates of the point of impact. Pls help.


texts: I recently was given this link to a tutorial site from someone who I gave the original OGL Redbook to. The third header down says distinctly to forget glBegin() & glEnd() as the typical render method. I learned via the Redbook's method, but I see some benefit in VBOs. Is this really the way to go, and if so, is there a way to easily convert the render code, and subsequent shaders, into VBOs and subsequent datatypes?


texts: Stop a rotating object at a specified angle?

texts:
I'm working in JavaScript with HTML5 and the canvas. I have an object which is rotating at a certain speed, and I need the object's rotation to slow down gradually and the front of the object to stop at a specified angle. (I'm using radians, not degrees.) I have a variable to keep track of the angle which the object is facing, as it rotates.

How would I go about getting the object to come to rest, facing the direction I want it to?


texts:
So I'v been hobby programming games for a few years now but never released anything.

This year I was thinking about deepening my knowledge of the industry and doing some networking buy going to some trade shows and maybe taking part in a contest.

My first instinct was try E3 but that is not open to the public and is in america :(

So what I want to know is what shows and contest are held in the UK for game development.

I have found this difficult to Google when you as I am not sure what I am even looking for so if anyone has any recommendations. Ideally the show would have elements dedicated to design and development of games instead of just previewing the new releases.

Any information on any game competition would be great no matter the level.


texts:
Im making a game in Java with a few other people but we are stuck on one part of it, making the collision detection. The game is an RPG and I know how to do the collision detection with the characters using Rectangles, but what I dont know how to do is the collision detection for the maps. What I mean by that is like so the character cant walk over trees or water and that stuff but using rectangles doesnt seem like the best option here.

Well to explain what the game maps are gonna look like, here is an example:

Now I could use rectangles to get bounds and stop the player from walking over the trees and water but that would take a lot of them.

But is there another easier way to prevent the player from walking over the trees and obstacles besides using Rectangles?


texts: transform touch/click coordinates(2D) into 3d coordinates

texts:
I would like to convert touch/click input (2D coordinates) to 3D coordinates by dropping the Z axis (would like to move only up/down, left/right (Z is the axis for depth).

The problem is that the coordinates i get from input (2d) aren't corelated with the 3d actual space.

Does XNA provide a way to do this?


texts: How to draw texture with unlit effect on surface base texture

texts:
I am writing a shader to my Unity game and I want to have effect this type of effect:

Base texture, for example, skin of character is a texture that will use shadows, lighting.
Second texture, unlit, it will not be using shadows, it will be moving and changing alpha intensity.
Second texture will be drawn after base texture.

Only unlit or surface shader looks bad, I think I must connect those two shaders, to make nice looking effect.

I wrote something this and I am stuck:

Shader "My/SurfaceUnlitBlend"
{
    Properties
    {
        _MainTex("Base", 2D) = "white" {}
        _MainColor("Main Texture Color", Color) = (1,1,1,1)
        _SecTex("Second Texture", 2D) = "white" {}
        _SecColor("Second Texture Color", Color) = (1,1,1,1)
        _SecTexAnimHSpeed("Second Texture Animation Horizontal Speed", Float) = 0
        _SecTexAnimVSpeed("Second Texture Animation Vertical Speed", Float) = 0
        _BlendValueModifier("Blend Value Modifier", Range(0.5, 2.0)) = 1
        _Glossiness("Smoothness", Range(0,1)) = 0.5
        _Metallic("Metallic", Range(0,1)) = 0.0
    }

    SubShader
    {
        Tags{ "RenderType" = "Opaque" }
        LOD 200

        CGPROGRAM
        #pragma surface surf Standard fullforwardshadows
        #pragma target 3.0

        struct Input
        {
            float2 uv_MainTex;
            float2 uv_SecTex;
        };

        sampler2D _MainTex;
        sampler2D _SecTex;

        fixed4 _MainColor;
        fixed4 _SecColor;

        fixed _SecTexAnimHSpeed;
        fixed _SecTexAnimVSpeed;

        fixed _BlendValueModifier;
        half _Glossiness;
        half _Metallic;

        UNITY_INSTANCING_CBUFFER_START(Props)
        UNITY_INSTANCING_CBUFFER_END

        void surf(Input IN, inout SurfaceOutputStandard o)
        {
            // Albedo comes from a texture tinted by color
            fixed2 moveVector = fixed2(_SecTexAnimHSpeed, _SecTexAnimVSpeed);
            moveVector *= _Time[1];

            //set blend modifier according to time
            float blendLevel = (cos(_Time[1]) + 1.5) * _BlendValueModifier;

            //set colors
            fixed4 col1 = tex2D(_MainTex, IN.uv_MainTex) * _MainColor / 2;
            fixed4 col2 = tex2D(_SecTex, (IN.uv_SecTex + moveVector) / 15) * _SecColor * blendLevel;

            //blend colors
            fixed4 result = col1 + col2;
            o.Albedo = result;
        }
        ENDCG
    }
    FallBack "Diffuse"
}

Because I don't know what to do, to have unlit effect in second texture.


texts: How can I center a WebGL window in Unity?

texts: I have a WebGL build for my game, however, I'm getting frequent requests to center the image. Right now it is left justified. How can I center the WebGL game window?


texts: Going from using XMLSerializer to using the XNA Content Pipeline

texts:
A well known limitation of using the XNA Content Pipeline is that it is not included in the XNA redistributable. So, if you want to create an editor for your game, the designer must download the whole deal: your editor, your engine, XNA Game Studio and Visual Studio Express. Even then, I'm not sure you can compile your XML data into xnb outside of Visual Studio.

So I decided to simply use XMLSerializer, which works fine. However, I'm thinking that, once all the content of my game is done, prior to release, it would be great if I could convert the whole system into using the XNA Content Pipeline. In my mind, I think that the compiled xnb files would load faster than deserializing XML into objects.

Is the conversion possible? More importantly, is it worth it?

Note: my intention is to release the game as an XBOX Live Indie Game.


texts: Field of view settings for first person shooter

texts: Are there any industry standards for setting the field of view (FOV) for FPS games or is it solely based on trial and error? Are there any guidelines for choosing the correct value?


texts:
I'm trying to animate a texture to scroll a static screen for a television, however I'm having some issues.

Just translating within the texture matrix animates all textures in the scene which is obviously a problem. However when trying to push and pop the matrix the texture matrix seems to keep getting reset. So rather than a scrolling texture, the texture just stays at the same translation.

Here's the code snippet.

glMatrixMode(GL_TEXTURE);

glPushMatrix();

glTranslatef(0, 0.03 * dt, 0);

glBindTexture(GL_TEXTURE_2D, staticTexture);

RepeatTexture();

glBegin(GL_QUADS);
glTexCoord2f(0, 0);
glNormal3f(0, 0, 1);
glVertex3f(0.49, 0.205, 0.461);
glTexCoord2f(0, 1);
glNormal3f(0, 0, 1);
glVertex3f(0.49, 1.204, 0.461);
glTexCoord2f(1, 1);
glNormal3f(0, 0, 1);
glVertex3f(-.80, 1.204, 0.461);
glTexCoord2f(1, 0);
glNormal3f(0, 0, 1);
glVertex3f(-.80, 0.205, 0.461);
glEnd();

glPopMatrix();

glMatrixMode(GL_MODELVIEW);


texts:
Im trying to load a effect in SlimDX, but I get a error when I try to get the ShaderSignature.
The error-code:

E_FAIL: An undetermined error occurred (-2147467259)

This is my code:

   EffectTechnique tech = this.effects.GetTechniqueByIndex(0);
   EffectPass pass = tech.GetPassByIndex(0);
   ShaderSignature shaderSignature = pass.Description.Signature;

Any idea?


texts: What is the velocity of a translating projectile in 2D?

texts:
What I'm trying to do.

So I want to have a projectile that starts at point (x1, y1) and head in the direction of my mouse say point (x2, y2).

To clarify I'm pretty sure it's a vector but I don't know much about them.

Language / Librarys

I'm making the game in Java and LibGDX so Java.MathUtils would come in to play i'm pretty sure. If anyone that can answer don't know these languages, psuedocode will be just fine.

How I've tried it

I'm pretty sure the formula is something alongs the lines of
velX := cos(radians) * speed
velY := sin(raidans) * speed

And radians starts out as Pi/2 though the tutorial was pretty rough.

Then it would be x += velx * deltatime  and same with y.

Can anyone help me out with the translation formula


texts: When to call GLBindTexture when using a spite-sheet?

texts:
Originally, I was using individual textures (ie, individual .png files) for my sprite's animation and recently altered my code so that I could put all my animation frames into 1 file (so it basically is like a mini sprite sheet - I say 'mini' because I'm using 1 file per sprite, I'm not using 1 file for all my sprites).

Anyway my question relates to glBindTexture.  Originally, I was switching textures when I wanted to update the animation frame so was calling this in my sprite's draw method:

GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texID);  //texID being the texture ID

However, now what happens is that I work out the texture offset and just point to part of the texture that I require.  The texture itself does not change anymore, so do I still require this line every time I draw?

I tried removing the line from my draw() method and just calling it once when I loaded the texture initially, but the sprite doesn't draw with the correct texture, it uses a completely different, un-related texture.  So what is the correct course of action in cases like this where a sprite-sheet is being used?

At the moment, I'm not sure why this would be any faster than using individual files and switching the texture every frame.  In fact as I'm now having to work out the texture offset (whereas previously it was fixed), there is more overhead.   So I'm guessing the advantage comes from not having to call this glBindTexture line every time I draw (as it's expensive). So how do I correctly choose the texture to assign to this sprite other than within the draw method?

Any help would be appreciate, if you need code please ask I didn't post my whole draw method as I didn't think it was necessary to explain the issue.

This is what I was doing previously

Bind texture 1 (Animation frame 1, textures 1-8 belong to this sprite)
Draw Sprite 1

Bind texture 9
Draw Sprite 2

Repeat binding texture 2, then 3 etc for sprite 1 to animate it

I am now using a single texture for sprite1 which contains all 8 animation frames

Bind texture 1 (all frames)
Draw Sprite 1 (pointing to frames 1, 2, 3 etc)

Bind texture 5
draw sprite 2


texts: What light attenuation function does UDK use?

texts:
I'm a big fan of the light attenuation in UDK. Traditionally I've always used the constant-linear-quadratic falloff function to control how "soft" the falloff is, which gives three values to play with. In UDK you can get similar results, but you only need to tweak one value: FalloffExponent.

I'm interested in what the actual mathematical function here is. The UDK lighting reference describes it as follows:

  FalloffExponent: This allows you to modify the falloff of a light. The default falloff is 2. The smaller the number, the sharper the falloff and the more the brightness is maintained until the radius is reached.

Does anyone know what it's doing behind the scenes?


texts: What are good games to "earn your wings" with?

texts:
I believe that in order to become a good game developer, you need to make games.

From a programmer's perspective, what are some good entry level games to get your hands dirty? What skills and challenges do each of these games teach you?


texts:
Im making a small game in Unity(using c#)

basicly what I have there is each player chooses one Damage Spell or one Shield Spell.and the thing is that the number of combinations is huge. like 100 cases. for example , shadow dmg spell will deal 0 dmg to light shield but will deal 4 dmg to Life shield(just an example) I dont need code, I just need advice, how do I handle all of it withought tons of if statements? Thank you :)


texts: Limiting Rendering in my game loop (Not Game Updates)

texts:
My Gameloop (code below), limits the game updates to 60 ticks per second. However, it renders as fast as the device on which it is being run can handle.

I'm using a fixed time step in my game and I want to be able to limit my rendering to a specified amount (in my particular case, that would also be 60).  However, I need to keep rendering calls uncoupled from game update calls.

I tried lumping the render calls in with the update calls but the problem with this is that they aren't uncoupled.  This could potentially lead to issues if the device can't handle rendering 60 fps.  Lets say it drops to 40fps, then the game updates will also drop to 40 ticks per second. Everything in my game is based on the game running at 60 ticks per second.  So everything will run at the wrong speed. (using a variable time step isn't an option, my whole game is build around a fixed time step)  So basically, if the device drops to 40 rendering calls per second, it should continue running game updates at 60 ticks per second so everything runs OK.

I am quietly confident that (virtually) every device on which my app runs will easily be able to handle 60 ticks (game updates) per second. I've tested this on a very old handset and it copes with 60 ticks no problem.

I would rather limit the rendering because as things stand it's rendering redundant frames and this must have a negative effect on battery life.

Would be grateful for suggestions on how I can limit the frames renders while keeping rendering and game updates separate.

Code

long nextGameTick = System.currentTimeMillis();
//loop counter
int loops;
//This is the amount of frames that we allow our app to skip before logic updating is affected (generally shouldn't happen)
final int maxFrameskip = 5;
//Game updates per second
final int ticksPerSecond = 60;
//Amount of time each update should take
final int skipTicks = (1000 / ticksPerSecond);

    public void onDrawFrame(GL10 gl) {

    //Set/Re-set loop back to 0 to start counting again
    loops=0;

    while(System.currentTimeMillis() > nextGameTick && loops < maxFrameskip){

        SceneManager.getInstance().getCurrentScene().updateLogic();
        nextGameTick+=skipTicks;
        timeCorrection += (1000d/ticksPerSecond) % 1;
        nextGameTick+=timeCorrection;
        timeCorrection %=1;
        loops++;
        tics++;

    }

    render();

}

Please note I've already read Fix your timestep! and the similar Android Game Loops but these articles don't mention how to limit the rendering in a loop like the one I have adapted - just the game updates.

Any help would be appreciated


texts: Is Physics2D.BoxCast a safe alternative to a row of raycasting?

texts:
Raycasting in rows is a common practice.

Is using the Physics 2D BoxCast function a good alternative to using
multiple raycasts spread out (an example use being collision
detection in a custom character controller script)?
There is limited documentation on boxcasting. Would boxcasting be
too intensive or more friendly to call each frame?


texts: Text Mesh Pro Text edges are not smooth form orthographic camera

texts:
I have a minimap camera (orthographic camera) which is rendering text mesh pro but the problem is the text edges are not smooth. Here is the screenshot:
[
The camera orthographic rendering on render texture.
Edit:
Some basic Orthogrphic camera setting are:
transform.localPosition = new Vector3(-26853f, 1165f, 24669f);
            transform.rotation = Quaternion.Euler(90f, -175.45f, 0f);
            miniMapCamera.orthographicSize = 110000;

Here is my text mesh pro, inspector:
[
Text mesh pro font size is 80.


texts: best way to implement movement after A* pathfinding? tile-based movement vs pixel-based?

texts:
I was able to implement the A* pathfinding algorithm to calculate a path from the enemy to player.

After trying to do movement well, I realized I ran into all sorts of problems. I was able to add clearance to the pathfinding, so I'm now going to have sprites of variable size, which leads to even more issues.

I am currently doing movement like -
path[0] is first Tile in path and it is removed when you get to it:

            if (path.Count > 0) {
                if (path[0].isTouching(this))
                    path.RemoveAt(0);
                }
            }

                            if (path [0].getCenterX() > this.getCenterX()) {
                                speedX = speed;
                                speedY = 0;
                                System.Console.WriteLine("moving right");
                            }
                            else if (path [0].getCenterX() < this.getCenterX()) {
                                speedX = -speed;
                                speedY = 0;
                                System.Console.WriteLine("moving left");
                            }

                            if (path [0].getCenterY() > this.getCenterY()) {
                                speedX = 0;
                                speedY = speed;
                                System.Console.WriteLine("moving down");

                            }
                            else if (path [0].getCenterY() < this.getCenterY()) {
                                speedX = 0;
                                speedY = -speed;
                                System.Console.WriteLine("moving up");
                            }

                            this.move(speedX, speedY);

This doesn't work very well for a variety of reasons.

I am certain the pathfinding I implemented calculates the proper path of Tiles. Now I think I have to move from a pixel to pixel movement -> tile to tile in order to have this working better. This would probably help, right? How is movement usually done to work with A*? If the tile-based movement would aid, any tips on implementing this?


texts: Unity3D - How to get highest value for acceleration from Input.gyro

texts:
I'm trying to develop an app that can detect car acceleration, braking and cornering speed. I need to detect device acceleration. Is that acceleration high or low?. Like flo app on Google Play.

I'm using gyroscope and I need to get highest value for user acceleration (x, y, z axises) from gyroscope. Values of x, y and z are changing every frame. I need to achieve highest value of this 3 axis for later use.

Now my current code looks like this

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class NewBehaviourScript : MonoBehaviour
{
 public Text x, y, z;

 void Start()
 {
     Input.gyro.enabled = true;
 }

 void Update()
 {
     x.text = Mathf.Abs(Input.gyro.userAcceleration.x).ToString();
     y.text = Mathf.Abs(Input.gyro.userAcceleration.y).ToString();
     z.text = Mathf.Abs(Input.gyro.userAcceleration.z).ToString();
 }
}

Thanks for any help


texts:
I want to create an abstraction layer between my Jython Script objects and my Game Objects. I am not making the all of the engine in Jython. Most of my game logic is in Java. I just want to expose high level functionality. I am thinking of using these classes.

Jython Object is created using a Jython class and a Java interface that is coerced into java.
Abstracted Object and Abstraced Map are objects with get() functions that limit the exposure of the underlying Game Map and Game Object.
Game Object and Game Map are the underlying Java objects. They are wrapper classes for a component based system.
Action Factory provide functionality to Jython Object. My game is a turn based tactic, so any change in the game board is done by a set of generic actions (move, damage, apply buff, etc).

This is the first time I have tried to implement a scripting system. The goal is be able to design objects and abilities in Jython. Also create a modding system. I have read several places that creating an abstraction layer is a good idea. I am just not sure how to do it.


texts:
Possible Duplicate:
  Famous games written in Python

Is python any good for game development? Can I have some examples of great indie python games.

So I can have an idea what it's capable of?

I'm looking for games which are on a realistic scale for one person.

thanks.


texts: Simple Water surface simulation problems (GDC2008 Matthias Muller- Hello World)

texts:
Im attempting to implement a simple height field water surface simulation outlined in Matthias Muller's GDC 2008 talk. "http://www.matthiasmueller.info/talks/gdc2008.pdf"

I can't seem to see why it my implementation doesnt work. Could anyone help? Any advice or help would be much appreciated.
The main processing loop is below
The obstruction array is initialized as 1. And the source just adds 0.1f to a point.

void wave()
    {
        for( int i = 0; i<size ; i++)
        {
            height[i] += source[i];
            height[i] *= obstruction[i];
        }

        for (int i = 1 ; i<iwidth-1 ; i++)
        {
            for(int j = 1 ; j < iheight-1 ; j++)
            {

                velocityField[indexFind(i,j)] += (height[indexFind(i-1,j)] +
                                                  height[indexFind(i+1,j)] +
                                                  height[indexFind(i,j-1)] +
                                                  height[indexFind(i,j+1)])/4 - height[indexFind(i,j)];

                velocityField[indexFind(i,j)] *= dampening;

                height[indexFind(i,j)] += velocityField[indexFind(i,j)];

            }

        }
    }

    int indexFind(int x, int y)
    {
        return (x + iwidth*y);
    }

This is what happens (height field rendered as a texture on a plane)

This is the page from the link that outlines the algorithm


texts: Smooth movement from point A to point B in a tile-based game

texts:
I'm currently very new to XNA, and I'm trying to get a grasp on movement. Currently, I have a function that checks for keypresses, and moves my character from point A to point B instantly:

private KeyboardState currentKeyboardState;
private KeyboardState previousKeyboardState;

...

public void CaptureKeyboardInput()
{
    currentKeyboardState = Keyboard.GetState();

    // Move the character's sprite to the left on the screen. The movement
    // distance is determined based on the scale of the sprite texture.
    if (currentKeyboardState.IsKeyDown(Keys.A) && previousKeyboardState.IsKeyUp(Keys.A))
    {
        Position += new Vector2(-Scale.X, 0);
    }

    // Move the character's sprite to the right on the screen. The movement
    // distance is determined based on the scale of the sprite texture.
    if (currentKeyboardState.IsKeyDown(Keys.D) && previousKeyboardState.IsKeyUp(Keys.D))
    {
        Position += new Vector2(Scale.X, 0);
    }

    // Move the character's sprite upwards on the screen. The movement
    // distance is determined based on the scale of the sprite texture.
    if (currentKeyboardState.IsKeyDown(Keys.W) && previousKeyboardState.IsKeyUp(Keys.W))
    {
        Position += new Vector2(0, -Scale.Y);
    }

    // Move the character's sprite downwards on the screen. The movement
    // distance is determined based on the scale of the sprite texture.
    if(currentKeyboardState.IsKeyDown(Keys.S) && previousKeyboardState.IsKeyUp(Keys.S))
    {
        Position += new Vector2(0, Scale.Y);
    }

    previousKeyboardState = currentKeyboardState;
}

While this works, it looks very unclean, and feels unnatural as well. Ideally, I'd like to move it from point A to B at a certain speed. I've already looked around, and I've found this question, but I couldn't figure out how to implement it correctly. How can I implement smooth movement from point A to B in my tile-based game with what I have?


texts: How should I pay people who work on my game development project?

texts:
What is the proper way to pay your team for a game development project? For example, how would you pay to a graphics artists or a musician for their work, especially in the context of today's app marketplaces like the Apple App Store or the Android Market?

It is better to pay in advance, or to share the incomes proportionally as an app becomes successful?


texts:
We use svn at work, but the repository is getting pretty large, so checkout times are long, as is update when artists batch process all assets.

The problem is that we also store work in progress, prototypes, small tests, legacy stuff and other 'junk'.

Now theoretically, some of it can remain local and uncommitted until it is ready to be included, and a lot could be deleted and cleaned, but that's irrelevant for this question.

Imagine a new asset, a level for example. The artists and designers want it shared and in version control so several of them can work on it, but everybody else does not need it.

Obviously multiple repositories are an answer: one for artists, one for programmers and one for the main project (for testers, building demo versions and finally the main product), which would be really tight and minimal, with everything needed for the game and no more. And then when an asset or some code is 'mature', it can be copied into the main project and committed.

Here's my questions: is it possible to have multiple repositories overlapping so that the artists can have one with everything they need, likewise for programmers. And only when ready commit the same file into the project repository too? This would eliminate bloat of having multiple copies of files and avoid conflicts between repositories.

I know old svn versions stored invisible files in all directories, so it would be impossible, but new svn versions store all meta data in the root directory right? So it might be possible.

I imaging the answer will be 'impossible', or even if possible, yuck! I suppose it would cause all kinds of headaches. Like checking it out in one repository would mean it would need to be committed/deleted in another.

But how about making a svn_commit script, that overrides svn commit with additional checks and housekeeping?

This is just a thought experiment really. I was wondering if anyone has ever done anything like this, and what would be the issues to be resolved.
Cheers


texts:
Say I have a GameObject class that is being extended by all of the objects in the game that are moving around. (This class provides basic stuff like a sprite, draw method, update method with application of move vector and so on...) I also have a class Asteroid that like I said extends GameObject

Then there are two versions of the game:

Version 1: Somewhere in the game there is a Collection that holds all of the Asteroid-objects. The update Method is something like this:

for(Asteroid a : asteroids)
    a.update(...)

Draw method goes equivalent.

Version 2: I decided to put all of my GameObjects in a single collection, so that all moving stuff is being handled in one single loop like this:

for(GameObject o : gameObjects)
    o.update(...)

Again, draw method goes equivalent.

The problem I am facing with version 2 is that the game loop basically takes twice as long. (The update method as well as the draw method.) I am astonished at the draw method, since in either version there is the exact same amount of object being drawn. So my question is: Does this abstraction in version 2 affect the game's performance in any way? (I can imagine that version 2 requires the JVM to alway cast the GameObject implicitly to it's specific type which it does not have to do when the type is already given like in version one, but I am not sure about that.) (I am using Java with LibGDX if it matters)


texts: How can I draw a small bitmap on a larger bitmap at a particular position? (Canvas / SurfaceView)

texts:
I'm building a game that requires additive blending of colours for certain bitmaps.
Say I have 4 different types object, there are maybe ten of each type on the screen with each type having a distinct colour.
If these objects overlap I want to perform additive blending on the overlapping portions.
After doing some research on the subject I came across this thread about drawing and additive blending.
It has lots of useful information, but it's not using bitmaps.
Then I found another thread about blending pixels from two bitmaps which is also helpful, but is based on same sized bitmaps.

So my solutions to solve this problem is to create four temporary bitmaps, one for each object type / colour, with each of these bitmaps being the same size as the device screen. I want to draw all objects of each colour onto the relevant bitmap, so all the blue objects on one bitmap, all the orange objects on another and so on.
Then when all for bitmaps are ready I'll perform additive blending on the four bitmaps of the same size as per the link above. then draw the result on the canvas.

My only problem is I'm not sure how to position the smaller bitmaps correctly on the larger one. Can anyone advise me on how I might proceed with this?


texts: How could I do a 2d pixel design in game where you can see though the obstacles/upper floors?

texts:
Maybe the question didnt show much... but what I'm trying to do is e.g. if I'm in a train platform with two floors overlapped, or in a place where I'm blocked by some obstacle to see my char. from my view. I want to let my character be visible but have how should I say, have lines? of the obstacles overlapped a bit so i can have an impressing there is an obstacle but you're seeing your char. through, kinda like half-visible, kinda like gradation.

tl;dr - I want to see my character who is normally should be blocked the view from my POV to be visible, while also making the player to see that there's something between the character and the POV. is there a method I can check?

using dots to create this via photoshop.


texts: Level data for Mario or similar platform game

texts:
It has become a widespread to implement a Mario-clone to practise writing platform games or in order to demonstrate how a game engine works.

For that reason I expected it to be easy to find level data for Mario.

Are the levels of Mario in a ready to use format available?

Note: Edited to narrow the scope of the question.


texts: I'm looking for an AI engine for iOS game development (machine learning, path finding).


texts: nullObjectException in OnDrawGizmos Function

texts:
I was studding A* Algorithm and it is showing a nullObjectException in my OnDrawGizmos function whenever it finishes compiling the code.

Here is my code - can anybody tell me what I am doing wrong?

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

namespace PathFinding {
    public class Grid : MonoBehaviour {
        public Transform Startpostion;
        public LayerMask Layer_Mask;
        public Vector2 gridWorldSize;
        public float nodeRadius;
        public float Distance;

        public Node[ , ] grid;
        float NodeDiameter;
        int GridSizeX, GridSizeY;
        public List<Node> FinalPath;

        private void Start () {
            NodeDiameter = nodeRadius / 2;
            GridSizeX = Mathf.RoundToInt (gridWorldSize.x / 2);
            GridSizeX = Mathf.RoundToInt (gridWorldSize.y / 2);
            GridCreator ();

        }
        void GridCreator () {
            grid = new Node[GridSizeX, GridSizeY];
            Vector3 bottomLeft = transform.position - Vector3.right * gridWorldSize.x / 2 - Vector3.forward * gridWorldSize.y / 2;
            for (int y = 0; y < GridSizeY; y++) {
                for (int i = 0; i < GridSizeX; i++) {
                    Vector3 WorldPositionOfCurrentNode = bottomLeft + Vector3.right * (i * NodeDiameter + nodeRadius) + Vector3.forward * (y * NodeDiameter + nodeRadius);
                    bool Wall = true;

                    if (Physics.CheckSphere (WorldPositionOfCurrentNode, nodeRadius, Layer_Mask)) {
                        Wall = false;
                    }
                    grid[i, y] = new Node (Wall, WorldPositionOfCurrentNode, i, y);
                }
            }
        }
        private void OnDrawGizmos () {
            Gizmos.DrawWireCube (transform.position, new Vector3 (gridWorldSize.x, 1, gridWorldSize.y));

            foreach (Node n in grid) {
                if (n.is_Wall) {
                    Gizmos.color = Color.white;
                } else {
                    Gizmos.color = Color.yellow;
                }
                if (FinalPath != null) {
                    if (FinalPath.Contains (n)) {
                        Gizmos.color = Color.red;
                    }
                }
                Gizmos.DrawCube (n.postion, Vector3.one * (NodeDiameter - Distance));
            }
        }
    }
}


texts:
I am currently trying to draw a simple 2D circle and an arc in DirectX but there are no resources online with info on how I can do this. Lines & Points are built into DirectX anyway so that has never been a problem.

Can somebody explain how I can do this? I'm not talking about a sphere or any other 3D geometry. Just a simple 2D Circle and Arc.


texts:
I tried asking in Chat and no one answered, so the question goes here.

Anyone have advice for loading background Sprite maps? I'm trying to do it as efficiently as possible for a grid of 25 locations. So, I'm thinking only have 5 sprite backgrounds loaded at a time, when applicable, for clean transition from location to location. (Like The original Zelda.) So, should I load up all 25 at once, or only keep the minimum up? (I just want to avoid confusion sprite variables are up.)


texts:
At the moment I got the following to simulate the suns direction:

void Sun::Update()
{
    if (!mIsMoving)
        return;

    const auto now = Clock::now();
    const auto timeDiff = now - mTimeStart;
    const float count = std::chrono::duration_cast<Intervall>(timeDiff).count();

    assert(mNightDayRatio <= 1.0f);
    if (count >= 0.5f + 0.5f * mNightDayRatio)
        mTimeStart = now;

    const float angle = count * glm::two_pi<float>() - glm::pi<float>();

    mDirLight.mLightDirection = Vec3(glm::cos(angle), glm::sin(angle), glm::sin(angle));
}

The problem is at the extremes the shadows from the sun (a directional light) become really "distorted"/"too long". I don't need a terribly complex solution just something that gives somewhat realistic sun direction over time.

Any ideas?


texts: How can I improve my collision detection's performance?

texts:
I'm new to programming and want to speed up the collision detection in my C++ 2D platformer game engine.

Currently, only the player's collision detection works: Every frame, the player's update function iterates through every level tile (which is pretty many) and checks if the player hitbox collides with it.

I may be way off on this, but this seems like a really chunky way of doing it. Is this bad practice? If the level gets large enough, is iterating through this list going to take forever like it seems it should?

My second question builds off of that: If I start adding for example enemies into the engine and give them a similar method for collision detection, can I expect performance drops? I'd like some insight from more experienced people on a better way of setting this up. I would just imagine that having ~20 enemies on the screen all iterating through all possible objects for collision with a list could get slow fast.


texts: Why transform.find() does not need actual object[unity]

texts:
I m new to unity and C#.

I suspect that transform.find() function below does not need actual object reference like

  player.transform.find()

because it transform find is already applied to the gameObject the script is attached to? Am I right?
Why transform.find() does not have any game object in front of it?

public class PlayerControl : MonoBehaviour{

private Transform groundCheck ;

void Awake()
{
    groundCheck = transform.Find("groundCheck");
}


texts: How to desing an RPG system with regard to PVP

texts:
When you design a RPG system focused on PVE, one usually goes "mob of level X has Y hp and Z damage". How about when we do PVP with multiple classes?

Lets say we go Diablo, so we have STR/DEX/INT/VIT, how do you balance those between classes? Do I say:

I want a fight to last 10 rounds on average (lets assume its turn based)
barb starts with 300 hp, demon hunter 250 hp, wizard 200 hp

And now try to manipulate DPS / health using stats/skills so it matches the "10 round on average" by giving mage a mana shield an a lil bit more damage per fireball than barbarians melee attack? How would You approach this?


texts: Draw a line/curve for the path an object has taken

texts:
Hello I am making a game in libgdx. I want to draw a line/curve of the path a object have taken.

First a thought I could save all positions of the objects each iteration and draw line between them using the Shaperenderer. This is however inefficient because the number of saved positions for a object becomes really large, and I have alot of objects.

My second thought was to draw a line between only the previous position and the current position on to a pixmap, and then draw the pixmap to the screen. This way I only need to save the old position because I don't clear the pixmap. The problem is that the world is infinitely big, and the pixmap cant cover the entire world (and it is bad to make a really big pixmap?). Also when I zoom out of the world the lines becomes really small and I cant see them. When I use the shaperenderer, the lines are always one pixel wide independent of the zoom.

So is there a smart way where I can draw the path my objects have taken without saving all previous positions, and where the line stays constant width?


texts:
When Unity builds a NavMesh, you can see it in the scene view if you have the Navigation window open and select "Show NavMesh" in the Navmesh Display box. I'd like to use the exact same overlay in a camera view. Is this accessible in any way? Can it be rebuilt during runtime? Since the navMesh isn't an actual mesh, I can't seem to find a way to make this happen.

EDIT: This is what I'm trying to work with right now:

public class NavMeshToCamera : MonoBehaviour {

    NavMeshTriangulation triangles;
    Mesh mesh;

    void Awake () {
        triangles = NavMesh.CalculateTriangulation();
        mesh = new Mesh();

        mesh.vertices = triangles.vertices;
        mesh.triangles = triangles.indices;
    }
}

I have this script attached to a secondary camera that will be enabled while holding down a button to see an overlay of a minimap of the current dungeon.  I'm not quite sure what to do with the mesh data to provide a mesh visible to the camera.  Since no mesh exists initially, I suppose I'd have to take the new mesh, apply a layer to it, and have only that layer visible to the camera.  But I'm having some difficulties with this.


texts:
I'm currently trying to generate a path along an array of points (Vector3)
This is the result I'm currently getting:

The dark gray points are the given path
The red points are the generated vertices
And the triangles are obviously the mesh I failed to generate correctly

And from the bottom it looks like this, which is odd, because I'd expect all the missing triangles to be at the bottom. But some of them just don't exist:

here's the code i wrote that generates the path mesh

//Removed code since there's no need in showing something that doesn't work

And here's a quick example of what it looks like when I drag a path:

SOLUTION FOUND

As the accepted answer states, I was skipping triangles in my triangle for loop.
Here is my new working code:

public static Mesh extrudeAlongPath(Vector3[] points, float width){
    if (points.Length < 2)
        return null;
    Mesh m = new Mesh();
    List<Vector3> verts = new List<Vector3>();
    List<Vector3> norms = new List<Vector3>();

    for (int i = 0; i < points.Length; i++) {
        if(i != points.Length-1){
            Vector3 perpendicularDirection = new Vector3(-( points[i+1].z-points[i].z ), points[i].y, points[i+1].x -points[i].x).normalized;
            verts.Add (points[i]+perpendicularDirection*width);
            norms.Add (Vector3.up);
            verts.Add (points[i]+perpendicularDirection*-width);
            norms.Add (Vector3.up);
        }else{
            Vector3 perpendicularDirection = new Vector3(-( points[i].z-points[i-1].z ), points[i].y, points[i].x -points[i-1].x).normalized;
            verts.Add (points[i]+perpendicularDirection*-width);
            norms.Add (Vector3.up);
            verts.Add (points[i]+perpendicularDirection*width);
            norms.Add (Vector3.up);
        }
    }
    m.vertices = verts.ToArray ();
    m.normals = norms.ToArray ();

    List<int> tris = new List<int> ();
    //Changed i+=3 to i++
    for(int i = 0; i < m.vertices.Length-3; i++){
        if(i%2 == 0){
        tris.Add(i+2);
        tris.Add(i+1);
        tris.Add(i);
        }else{
            tris.Add(i);
            tris.Add(i+1);
            tris.Add(i+2);
        }
    }
    m.triangles = tris.ToArray ();

    m.name = "pathMesh";
    m.RecalculateNormals ();
    m.RecalculateBounds ();
    m.Optimize ();
    return m;
}


texts:
Code:
SDL_Surface* tmpSurface = IMG_Load("Assets/Player.png");
playerTex = SDL_CreateTextureFromSurface(renderer, tmpSurface);
SDL_FreeSurface(tmpSurface);

Rendering the Texture:
SDL_RenderCopy(renderer, playerTex, NULL, NULL);

I did check to see if any of them returned null and playerTex is still null even though it is being set to a texture, im not sure why can anyone help


texts: In a ES system, how one would implement/ deal with Modifiers?

texts:
Given the normal entity-component-system architecture, lets say we a component that give the entity Strength. Now on the game flow I want to give +4 strength do to the wielded weapon.
What would be the best way to do this, considering that.

BaseValue => 10; Weapon => +4; Weaken Spell -2 (Temporary); CurrentFinalValue => 12

I could have many modifiers, positive or negative;
I would like to know for a given entity attribute "Strength", what are the modifiers sum;
I could add or remove modifiers and they should not remove from the base "Strength";

I could add as a component (StrengthModifierComponent) and apply the change to the StrengthComponent, then to be able to calculate the CurrentFinalValue, I would have to discover every component that affects "Strength" somehow and sum it with BaseValue. This might be easier if I have complete control of the system, but if I am building the system for general purpose this would have to be dynamic and there for complicated, making it possibly "slow".

I cannot put in the entity since the entity is usually just an identifier (int,Guid,SomeUniqueName).

I could make a ModifiableComponent which accept a list of Modifiers and would allow an easier interaction when making all the calculus. But wouldn't this break the ES architecture?

Thanks you.


texts: Shader inputs in a general purpose engine

texts:
I'm not familiar with SDKs like Unity or UDK that much, so i can't check this offhand. Do general purpose engines allow users to create custom uniform variables? The way i see it, and the way i have implemented it in an engine i'm writing to learn 3D, is that there is a "set" of uniforms provided by the engine and if you want to write a custom shader then you utilize uniforms you need to create a wanted effect.

Now, the thing is, first of all i'm not an artist, second of all, i didn't have a chance to create complex scenes yet. So my question is, is it common practice to define variables that the engine provides and only allow the user to work with what they're given?

Allowing users to add custom programs and use them where they want is not hard, but i have issues imagining how you'd go about doing the same for uniforms.


texts: Calculating the weight of an object irrespective of the triangle or vertices count in Unity

texts:
I have a meat piece which I want to weigh. Now there can be anything like fish, cheese, or other items that we can cut and measure. I want the weight to be determined by myself instead of determining from getting the surface of the item as it varies with different tris count.
Currently, I am calculating the weight from the following code.
public static float CalculateSurfaceArea(Mesh mesh)
{
    var triangles = mesh.triangles;
    var vertices = mesh.vertices;

    double sum = 0.0;

    for (int i = 0; i < triangles.Length; i += 3)
    {
        Vector3 corner = vertices[triangles[i]];
        Vector3 a = vertices[triangles[i + 1]] - corner;
        Vector3 b = vertices[triangles[i + 2]] - corner;

        sum += Vector3.Cross(a, b).magnitude;
    }
    // weightMultiplier is a constant value for getting a reasonable weight value.
    return (float)(sum / 2.0) * weightMultiplier;
}

So if there's a meat piece like bellow and I want it to be a weight of let's say 3kg(6.6lb)

then when I cut it into half it should give me values respectively (1.5kg).

So I want the weighing factor to be in my control so that if in the future we have really detailed high poly items the weight shouldn't get affected by that.


texts: How to make an event appear after one event has been activated on RPG MAKER VX ACE?

texts:
I am trying to create my first RPG, and I having some difficulty to make an event appear after an event had been activated, and then disappear later, only to reappear after the player activated an event (to cut off an area during certain times).

How would I do this in RPG Maker?


texts: What is an example of a binary 3d file format?

texts:
I'm new to GD so if this is too broad I apologize. I'm looking for some quick information.

What binary file format supports the basic game rendering information?

raw position vertices
Texture/UV
(or) Color
Normals
Animation keyframes

I'm aware that .obj and .dae have all of the above, however these files are in ascii. What file type supports these and is in binary?

And is it common to make custom 3d model format for one's game engine?


texts: Drawing "Stenciled" Sprites and making them glow

texts:
Currently, in my game - I'm not using XNA's SpriteBatch to render anything(I am using Farseer Physic's Debug View), and I was wondering how I would render something like this:

only using XNA. My second question is once I have drawn these stenciled sprites , how would I give the "stenciled" lines a glow effect like so:

I haven't done anything like this before so It is a very confusing experience for me. Any pointers?


texts:
V,A and B are 3 points in 3D space and We have d0 (distance of V from (AB)line).

I want to calculate question mark point in the image above!


texts: Two UBO's end up containing the same data

texts:
I have two separate UBO's for different types of lights (for a light stage in a deferred rendering system).

These are defined as follows:

//Pointlight UBO
m_pointLightBlockIndex = glGetUniformBlockIndex(shader.getShaderHandle(), "PointLights");
glGetActiveUniformBlockiv(shader.getShaderHandle(), m_pointLightBlockIndex, GL_UNIFORM_BLOCK_DATA_SIZE, &m_PointLightBlockSize);
glUniformBlockBinding(shader.getShaderHandle(), m_pointLightBlockIndex, 0);

//Spotlight UBO
m_splBlockIndex = glGetUniformBlockIndex(shader.getShaderHandle(), "SpotLights");
glGetActiveUniformBlockiv(shader.getShaderHandle(), m_splBlockIndex, GL_UNIFORM_BLOCK_DATA_SIZE, &m_SpotLightBlockSize);
glUniformBlockBinding(shader.getShaderHandle(), m_splBlockIndex, 0);

//create the buffers
glGenBuffers(1, &m_SLBuffer);
glGenBuffers(1, &m_PLBuffer);

glBindBuffer(GL_UNIFORM_BUFFER, m_SLBuffer);
glBufferData(GL_UNIFORM_BUFFER, sizeof(SpotLightData)*m_MaxSpots, nullptr, GL_DYNAMIC_DRAW);

glBindBuffer(GL_UNIFORM_BUFFER, m_PLBuffer);
glBufferData(GL_UNIFORM_BUFFER, sizeof(LightData)*m_MaxPoints, nullptr, GL_DYNAMIC_DRAW);

glBindBuffer(GL_UNIFORM_BUFFER, 0);

To populate the UBO's I use the following:

void LightUniformBuffer::updatePointLights(int numLights, const LightData * data)
{
    glBindBuffer(GL_UNIFORM_BUFFER, m_PLBuffer);
    glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(LightData)*numLights, data);
    glBindBuffer(GL_UNIFORM_BUFFER, 0);
}

void LightUniformBuffer::updateSpotLights(int numLights, const SpotLightData * data)
{
    glBindBuffer(GL_UNIFORM_BUFFER, m_SLBuffer);
    glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(SpotLightData)*numLights, data);
    glBindBuffer(GL_UNIFORM_BUFFER, 0);
}

And finally to bind them:

void LightUniformBuffer::bindPointLights()
{
    glBindBufferBase(GL_UNIFORM_BUFFER, m_pointLightBlockIndex, m_PLBuffer);
}

void LightUniformBuffer::bindSpotLights()
{
    glBindBufferBase(GL_UNIFORM_BUFFER, m_splBlockIndex, m_SLBuffer);
}

These buffers are represented as arrays of lights in GLSL, like so:

layout (std140) uniform PointLights
{
    LightData points[MAX_NUM_POINT_LIGHTS];
};

layout (std140) uniform SpotLights
{
    SpotLightData spots[MAX_NUM_POINT_LIGHTS];
};

Now, when I populate the buffers and use the shader, I found, through using Nsight, that both buffers are using the same set of data, i.e. the spotlight buffer is filled with point light data, and so is useless.

Why is this happening, and how can I fix it?


texts:
Does anyone know a formula, way, ... to make a FPS player feel like an object has the same size on different FOVs (given that it's at the same distance of the player, of course)? I know that this can't be done perfectly, because of the distortion various FOVs cause and the position of the object (near the edges of the FOV = more distortion).
Let's ignore these distortions, and aim for a same size feel for objects that are directly in front of the player (so in the exact center of the FOV).

To clarify things a bit further: I want 1 object in my game to have the same scale feel on different FOVs, not my entire game world.

I've tried giving it a percentage of the frustrum height, but that doesn't seem to give me consistent results.

Note: I'm using vertical field of view in my game.


texts: How can I lerp between two numbers setting the lerp time each 0.3f seconds?

texts:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BlendShapesController : MonoBehaviour
{
    private SkinnedMeshRenderer bodySkinnedMeshRenderer;
    private bool randomizeNumbers = true;

    // Start is called before the first frame update
    void Start()
    {
        bodySkinnedMeshRenderer = GetComponent<SkinnedMeshRenderer>();
        StartCoroutine(RandomNumbers());
    }

    // Update is called once per frame
    void Update()
    {
        if(randomizeNumbers == true)
        {
            StartCoroutine(RandomNumbers());

            randomizeNumbers = false;
        }
    }

    IEnumerator RandomNumbers()
    {
        int rand = Random.Range(0, 23);
        bodySkinnedMeshRenderer.SetBlendShapeWeight(0, rand);

        yield return new WaitForSeconds(0.3f);

        randomizeNumbers = true;
    }
}

Now I'm using a random number betwen 0 and 23 every 0.3f seconds.
I want to change it so it will lerp in the SetBlendShapeWeight at index 0 but instead rand it will lerp from 0 to 23 then from 23 to 0 when done stop waiting seconds.
So the time or speed should be set for the lerp and according to that how much time to wait.
For example if the lerp will take 5 seconds from 0 to 23 and then back from 23 to 0 then after 5 seconds start the Coroutine again.
The idea is to make some kind of mouth talk fake/cheat. So I want to mouth to be open/close smooth between 0 and 23 and then 23 to 0 before starting the new Coroutine and to be able to decide how much time it will take to make the lerp from 0 to 23 and 23 to 0.
In the screenshot when the blendshape of the mouth is set to 0 the mouth is open at 23 or 27 the mouth is closed.  So I want to simulate mouth talking between this range of numbers for example each 0.3f make the mouth close/open then after 0.3f again mouth close/open and so on.


texts:
How can I load a GIF animation in pygame? With a web search, I found a severely outdated library called GIFImage. I tried it to do it with 2 pictures but I'm getting stuck because I'm a beginner. I also found something about making animations with Sprites, but no tutorial...

How do I do this?


texts: I'm trying to generate normal map on the fly in fragment shader. The implementation I've found is using dFdxFine function, which can't be used in WebGL, is there any alternative for dFdxFine in GLSL ES 2.0?


texts:
I am able to get a fairly smooth zooming function going on in my project.

However I'm hoping to achieve a non-linear function.

I've tried using the smoothstep function but it doesn't feel smooth (Could have been an improper implementation of mine).

If anyone can provide any suggestions, that will be greatly appreciated.

An example of what I'm trying to achieve is that of the spectator camera, where it zooms in/out, in Dota2.

using UnityEngine;
using System.Collections;

public class Pan : MonoBehaviour {

    public float zoomSpeed = 20f;
    public float smoothTime = 0.3f;

    private float refSpeed = 0.0f;

    void Update () {

    if(Input.touchCount == 1)
        {
            panUpdate();
        }

    if(Input.touchCount == 2)
        {
            zoomUpdate();
        }

    }

    void panUpdate()
    {

    }

    void zoomUpdate()
    {

        // Store both touches.
        Touch touchZero = Input.GetTouch(0);
        Touch touchOne = Input.GetTouch(1);

        // Find the position in the previous frame of each touch.
        Vector2 touchZeroPrevPos = touchZero.position - touchZero.deltaPosition;
        Vector2 touchOnePrevPos = touchOne.position - touchOne.deltaPosition;

        // Find the magnitude of the vector (the distance) between the touches in each frame.
        float prevTouchDeltaMag = (touchZeroPrevPos - touchOnePrevPos).magnitude;
        float touchDeltaMag = (touchZero.position - touchOne.position).magnitude;

        // Find the difference in the distances between each frame.
        float deltaMagnitudeDiff = prevTouchDeltaMag - touchDeltaMag;

//        float into = GetComponent<Camera>().fieldOfView + deltaMagnitudeDiff; //* ZoomSpeed

       // float smoothDiff = Mathf.SmoothDamp(GetComponent<Camera>().fieldOfView, deltaMagnitudeDiff, ref zoomSpeed, smoothTime);

        // Otherwise change the field of view based on the change in distance between the touches.
        GetComponent<Camera>().fieldOfView = Mathf.SmoothDamp(GetComponent<Camera>().fieldOfView, GetComponent<Camera>().fieldOfView += deltaMagnitudeDiff * zoomSpeed, ref refSpeed, smoothTime);

        // Clamp the field of view to make sure it's between 0 and 180.
        GetComponent<Camera>().fieldOfView = Mathf.Clamp(GetComponent<Camera>().fieldOfView, 59.9f, 119.9f);

    }
}


texts: How to design a useful scripting system?

texts:
I have decided to use the Squirrel (probably doesn't matter much for this question) scripting language in my C++ project. I'm wondering how game developers usually handle scripting in their games. I've managed to run scripts, bind functions etc. - that is not the problem. I'm just not sure how a scripting system is actually implemented in a sensible way.

So far I have got a singleton ScriptManager, which owns a virtual machine and can interact with it.

Some specific questions:

Does every functionality, that you want to control with scripts, need to be bound manually or can you somehow make all functions/classes available to your scripts? (I do not intend to use scripting everywhere in the final game, but it would make the development  process a whole lot easier.)
How should squirrel scripts be structured? Should they represent some kind of library, that you load, or just a set of commands that get executed whenever a game object wants to? If the former approach is better, how would such a library look like and how would the execution of the script be triggered?

I would be great if you could point me into the right direction!
Thanks!


texts: GameMaker Android project crashes on IAP

texts:
I'm trying to implement a simple IAP in my GameMaker project for Android.
The "store" is a simple room with a button, with this code linked to the "Left mouse button released" event:

if iap_status() == iap_status_available
{
    var product = "donation";
    if ds_map_find_value(global.purchaseMap, product) == 0
    {
        iap_acquire(product, "");
    }
}
else
{
   show_message_async("Store is not available.");
}

and another object with this code linked to the "IAP" event:

var val = ds_map_find_value(iap_data, "type");

switch (val)
{
    case iap_ev_purchase:
        var map = ds_map_create();
        var purchase_id = ds_map_find_value(iap_data, "index");
        iap_purchase_details(purchase_id, map);
        if ds_map_find_value(map, "status") == iap_purchased
        {
            var product_id = ds_map_find_value(map, "product");
            ds_map_replace(global.purchaseMap, product_id, 1);
            switch(product_id)
            {
                case "donation":
                    iap_consume(product_id);
                break;
            }
        }
        ds_map_destroy(map);
    break;

    case iap_ev_consume:
        var product_id = ds_map_find_value(iap_data, "product");
        if ds_map_find_value(iap_data, "consumed")
        {
            ds_map_replace(global.purchaseMap, product_id, 0);

        }
    break;
}

ds_map_secure_save(global.purchaseMap, "iap_data.json");

The IAP is correctly called when the button is pressed, but when the transaction is completed, the game crashes and then crashes at every launch. If I cancel the transaction it doesn't crashes, so I was suspecting the case iap_ev_consume: part to be at fault.

I followed this tutorial: https://help.yoyogames.com/hc/en-us/articles/216755198-In-App-Purchases-Example

Why does my game crashes when an IAP is performed?


texts: Prediction of collision place and time in Unity

texts: I have two moving objects. I have chosen trajectories for objects that they would definitely collide if they don't change speed or trajectory. Is there easy way to check at which point and time the objects will collide with given parameters (current object positions, their velocity vectors and speeds or any other parameter accessible from Unity)?


texts: XNA 2D Board game - trouble with the cursor

texts:
I just have started making a simple 2D board game using XNA, but I got stuck at the movement of the cursor.

This is my problem:

I have a 10x10 table on with I should use a cursor to navigate. I simply made that table with the spriteBatch.Draw() function because I couldn't do it on another way.

So here is what I did with the cursor:

public override void LoadContent()
{
    ...
    mutato.Position = new Vector2(X, Y); //X=103, Y=107;
    mutato.Sebesseg = 45;
    ...
    mutato.Initialize(content.Load<Texture2D>("cursor"),mutato.Position,mutato.Sebesseg);
    ...
}

public override void HandleInput(InputState input)
{
    if (input == null)
        throw new ArgumentNullException("input");

    // Look up inputs for the active player profile.
    int playerIndex = (int)ControllingPlayer.Value;

    KeyboardState keyboardState = input.CurrentKeyboardStates[playerIndex];

    if (input.IsPauseGame(ControllingPlayer) || gamePadDisconnected)
    {
        ScreenManager.AddScreen(new PauseMenuScreen(), ControllingPlayer);
    }
    else
    {
        // Otherwise move the player position.
        if (keyboardState.IsKeyDown(Keys.Down))
        {
             Y = (int)mutato.Position.Y + mutato.Move;
        }
        if (keyboardState.IsKeyDown(Keys.Up))
        {
            Y = (int)mutato.Position.Y - mutato.Move;
        }
        if (keyboardState.IsKeyDown(Keys.Left))
        {
              X = (int)mutato.Position.X - mutato.Move;
        }
        if (keyboardState.IsKeyDown(Keys.Right))
        {
             X = (int)mutato.Position.X + mutato.Move;
        }
    }
}

public override void Draw(GameTime gameTime)
{
    mutato.Draw(spriteBatch);
}

Here's the cursor's (mutato) class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Battleship.Components
{
    class Cursor
    {
        public Texture2D Cursortexture;
        public Vector2 Position;
        public int Move;

        public void Initialize(Texture2D texture, Vector2 position,int move)
        {
            Cursortexture = texture;
            Position = position;
            Move = move;
        }

        public void Update()
        {
        }

        public void Draw(SpriteBatch spriteBatch)
        {
            spriteBatch.Draw(Cursortexture, Position, Color.White);
        }
    }
}

And here is a part of the InputState class where I think I should change something:

public bool IsNewKeyPress(Keys key, PlayerIndex? controllingPlayer,
                                       out PlayerIndex playerIndex)
{
     if (controllingPlayer.HasValue)
     {
           // Read input from the specified player.
           playerIndex = controllingPlayer.Value;

           int i = (int)playerIndex;

           return (CurrentKeyboardStates[i].IsKeyDown(key) &&
                   LastKeyboardStates[i].IsKeyUp(key));
     }
}

If I leave the movement operation like this it doesn't have any sense:

X = (int)mutato.Position.X - mutato.Move;

However if I modify it to this:

X = (int)mutato.Position.X--;

it moves smoothly. Instead of this I need to move the cursor by fields (45 pixels), but I don't have any idea how to manage it.


texts: How to use batch rendering with an entity component system?

texts:
I have an entity component system and a 2D rendering engine. Because I have a lot of repeating sprites (the entities are non-animated, the background is tile based) I would really like to use batch rendering to reduce calls to the drawing routine. What would be the best way to integrate this with an engtity system?

I thought about creating and populating the sprite batche every frame update, but that will probably be very slow. A better way would be to add a reference to an entity's quad to the sprite batch at initialization, but that would mean that the entity factory has to be aware of the Rendering System or that the sprite batch has to be a component of some Cache entity. One case violates encapsulation pretty heavily, while the other forces a non-game object entity in the entity system, which I am not sure I like a lot.

As for engine, I am using Love2D (Love2D website) and FEZ ( FEZ website) as entity system(so everything is in Lua). I am more interested in a generic pattern of how to properly implement that rather than a language/library specific solution.

Thanks in advance!


texts:
Hi :)
I want to ask what is the best way to deal with "mini-states" in game? For example I making game like Simcity, i can build buildings, roads, rails, or I can change something in economy.
I am making something like:

enum
{
  ROAD_CONSTRUCT,
  BUILDING_CONSTRUCT
  VIEW_MAP
  etc..
}

and in the game loop big switch. But the code is getting big. Is there some solution for all popular languages? I am asking because I am writing in C++, AS3 and sometimes in C.


texts:
I have script for my agent enemy where he should choose one random point and goes to it. But what he did is hesitating !

private NavMeshAgent mAgent;
public GameObject[] dead_point;
public float dist;
public int direction_point;

void Start()    {
    mAgent = GetComponent<NavMeshAgent>();
    player = GameObject.FindWithTag("Player");
    dead_point = GameObject.FindGameObjectsWithTag("dead_point"); // 3 points
} // end start

void enemy_dirction()    {
    farPoint = Random.Range(0, dead_point.Length);
    mAgent.destination = dead_point[farPoint].transform.position;
}

// Update is called once per frame
void Update()    {
    dist = Vector3.Distance(transform.position, player.transform.position);
    if (dist <= 20)
    {
        mAgent.destination = player.transform.position;
    }
    else
    {
        enemy_dirction();
    }

}// end update

update 1,
I used this new script and solved my problem.

    private NavMeshAgent mAgent;
public GameObject[] dead_point;
public float dist;
public int direction_point;

void Start()    {
    mAgent = GetComponent<NavMeshAgent>();
    player = GameObject.FindWithTag("Player");
    dead_point = GameObject.FindGameObjectsWithTag("dead_point"); // 3 points
    enemy_dirction()
} // end start

void enemy_dirction()    {
    farPoint = Random.Range(0, dead_point.Length);
    mAgent.destination = dead_point[farPoint].transform.position;
}

// Update is called once per frame
void Update()    {
    dist = Vector3.Distance(transform.position, player.transform.position);
    if (dist <= 20)
    {
        mAgent.destination = player.transform.position;
    }
    else
    {
        if (mAgent.remainingDistance <= 0.5f) {
            mAgent.destination = dead_point[farPoint].transform.position;
            print(farPoint);
        }
    }

}// end update


texts:
How would one go about creating a lamp shade material that lets light through from a light inside the object. I have read that turning of shadow casting for that object should work, however I have turned off Cast Shadows but it doesn't work.

Here are some pictures:

Light off:

Light on:

The lampshade remains dark. How can I fix this?


texts: When setting Stage as inputProcessor, Shaperenderer shapes are drawn stretched

texts:
I am working on making a falling sand simulation using libgdx. For drawing the individual elements I am using a ShapeRenderer and drawing rectangles.

I have begun to implement a dropdown menu to allow selection of elements to place. The functionality of the dropdown menu is working. I am able to set the inputProcessor as the stage and upon selecting the element type set the inputProcessor back to CreatorInputProcessor and I am able to successfully place elements again. The functionality is all working as expected.

However, when I set the stage with the dropdown as inputProcessor, the element rectangles become stretched. The resolution and pixel width of the window stays the same. It is not zooming in or anything. When the inputProcessor is set back to the CreatorInputProcessor the rectangles stay stretched.

Here are the things I have tried to fix this issue:

Use every kind of ViewPort passing in both a new OrthographicCamera and also the same camera used for the game view
Disposing of the stage after input processor is set back to CreatorInputProcessor
Setting the projection matrix on the camera every frame just before drawing or after drawing.

I found this stack exchange question which is similar to my issue but the marked answer does not solve my problem (setting the projection matrix every frame): LibGDX - why are the shapes from my ShapeRenderer resizing with my viewport?

I am looking for some advice on how I can resolve this issue. Thanks!

Here is the relevant code snippet: https://github.com/DavidMcLaughlin208/FallingSandJava/blob/master/core/src/com/gdx/cellular/InputManager.java#L357-L399


texts: I'm working on a test project to learn some basic OpenGL. Right now I'm trying to work on a "camera" with gluLookAt. My camera object is really simple, I have two vectors, one for the position and the other for the rotation (x, y and z on both). I'm having trouble with the target point gluLookAt receives, how can I find a target point using only the position and camera angle?


texts: Applying statements to a single instance in Game Maker?

texts:
I'm currently in the process of making a platformer, and am currently in the process of creating "depth" into my game, by making Up/Down-W/S control your depth. (Come closer to screen, go further).

The reason I chose to do this is so I can walk around stairs, go behind tables, etc.

But I have run into a problem.

When I call in my player code, if (depth == oWall.depth) {//code}, it is applying to every single wall ever. Is there a way to only make it apply to the object you are currently touching?

Here is my code so far:

/// Collision

// TODO: Make "depth" apply to a singular instance.
//   \/          \/
if (depth == oWall.depth) {

    /*
        Colliding with a wall on the Horizontal Axis, causes the player to stop moving.
    */

    if (place_meeting(x + h_speed, y, oWall)) {
        while(!place_meeting(x + sign(h_speed), y, oWall)) {
            x += sign(h_speed);
        }
        h_speed = 0;
    }

    /*
        Colliding with a wall on the Vertical Axis, causes the player to stop moving.
    */

    if (place_meeting(x, y + v_speed, oWall)) {
        while(!place_meeting(x, y + sign(v_speed), oWall)) {
            y += sign(v_speed);
        }
        v_speed = 0;
    }
}

Hope you understand what I'm asking.


texts: How to set up a key press to start the game

texts:
I've tried to create a simple start menu for my game which informs the player to press a key to start the game but the problem is that it works only if the key is pressed all the time...i'm not sure what would be the right way to deal with this.
Here is my code:

   if (Game.keysPressed[KeyBindings.S]) {

        if (game.livesLeft != 0) {
            game.createEnemies();
            game.update();
            game.draw();
            requestAnimationFrame(game.gameLoop);
        }
        if (game.livesLeft == 0) {
            game.drawLostGame();
        }
    }

Basically if the S key is pressed the game works, but when you release the key Game.keysPressed[KeyBindings.S] becomes false and the if statement won't be executed anymore, so that's why i need to find a way that by pressing only once the if statement will be executed until the player loses.
I've tried with while(true) and similar things but it didn't work.
Help would be appreciated! Thanks


texts: Why does OpenGL seem to ignore my glBindTexture call?

texts:
I'm having problems making a simple sprite rendering. I load 2 different textures. Then, I bind these textures and draw 2 squares, one with each texture. But only the texture of the first rendered object is drawn in both squares. Its like if I'd only use a texture or as if glBindTexture don't work properly. I know that GL is a state machine, but I think that you only need to change active texture with glBindTexture.

I load texture with this method:

 bool CTexture::generate( utils::CImageBuff* img )
 {
  assert(img);
  m_image = img;
  CHECKGL(glGenTextures(1,&m_textureID));

  CHECKGL(glBindTexture(GL_TEXTURE_2D,m_textureID));
  CHECKGL(glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR));
  CHECKGL(glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR));
  //CHECKGL(glTexImage2D(GL_TEXTURE_2D,0,img->getBpp(),img->getWitdh(),img->getHeight(),0,img->getFormat(),GL_UNSIGNED_BYTE,img->getImgData()));
  CHECKGL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img->getWitdh(), img->getHeight(),
   0, GL_RGBA, GL_UNSIGNED_BYTE, img->getImgData()));

  return true;
 }

And I bind textures with this function:

void CTexture::bind()
 {
  CHECKGL(glBindTexture(GL_TEXTURE_2D,m_textureID));
 }

Also, I draw sprites with this method

void CSprite2D::render()
 {
  CHECKGL(glLoadIdentity());
  CHECKGL(glEnable(GL_TEXTURE_2D));
  CHECKGL(glEnable(GL_BLEND));

  CHECKGL(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));
  m_texture->bind();

  CHECKGL(glPushMatrix());

  CHECKGL(glBegin(GL_QUADS));
  CHECKGL(glTexCoord2f(m_textureAreaStart.s,m_textureAreaStart.t)); // 0,0 by default
  CHECKGL(glVertex3i(m_position.x,m_position.y,0));

  CHECKGL(glTexCoord2f(m_textureAreaEnd.s,m_textureAreaStart.t)); // 1,0 by default
  CHECKGL(glVertex3i( m_position.x + m_dimensions.x, m_position.y, 0));

  CHECKGL(glTexCoord2f(m_textureAreaEnd.s, m_textureAreaEnd.t)); // 1,1 by default
  CHECKGL(glVertex3i( m_position.x + m_dimensions.x, m_position.y + m_dimensions.y, 0));

  CHECKGL(glTexCoord2f(m_textureAreaStart.s, m_textureAreaEnd.t));  // 0,1 by default
  CHECKGL(glVertex3i( m_position.x, m_position.y + m_dimensions.y,0));

  CHECKGL(glPopMatrix());

  CHECKGL(glDisable(GL_BLEND));
 }

Edit:
I bring also the check error code:

int CheckGLError(const char *GLcall, const char *file, int line)
{
    GLenum errCode;

    //avoids infinite loop
    int errorCount = 0;
    while ( (errCode=glGetError()) != GL_NO_ERROR && ++errorCount < 3000)
    {
        utils::globalLogPtr log = utils::CGLogFactory::getLogInstance();
        const GLubyte *errString;
        errString = gluErrorString(errCode);
        std::stringstream ss;
        ss << "In "<< __FILE__<<"("<< __LINE__<<") "<<"GL error with code: " << errCode<<" at file " << file << ", line " << line << " with message: " << errString << "\n";
        log->addMessage(ss.str(),ZEL_APPENDER_GL,utils::LOGLEVEL_ERROR);
    }
    return 0;
}


texts:
Possible Duplicate:
  How should I go about learning XNA?

so I would like to get into Xbox game development (indie games.) The problem is I cant find ANY documentation or place to get started online. I was hoping someone here could point me in the right direction (tutorials or documentation.) I was also hoping someone could direct me to some kind of online course? (Paid or free.) I appreciate your time, thanks.


texts: Can I change the tile size of a 2D isometric game in the middle of development?

texts:
First things first:

This is just a side project.
It's going to be my first "real" game.
In real life I'm a full time web developer (ASP.Net) with several years of experience.
I also have some basic knowledge of working in Unity 3D from several courses and small demos I've built.
My pixel art skills still suck, but I'm working on it.

So, I'm working on a game design for quite some time now (years) and just completed the latest draft of the design document. It's going to be a 2D isometric tile-based game.
I adore the pixel art of Undungeon in terms of character proportions, and want to aim for a similar style.

Here's my problem: I'd love to just get started with implementing my game, but I have no assets yet.

Is it a reasonable approach to just start coding using placeholder assets, even if the whole grid size / character proportions are uncertain and probably going to change at some point?
(Let's say my main characters sprite is 16x16 but I change it to 32x16 later on.)
Should I just abstract everything away that deals with pixel sizes?
Or bite the bullet and settle with a grid size from the very beginning?

I hope this isn't too broad of a question. Thanks for your help!


texts: html5 libgdx project: war to be deployed in a servlet container or only part of the contents to a web server

texts:
I am new to compiling games with libgdx to be played on the web and I have some doubts perhaps someone can point me in the right direction:

Using the new gradle setup I wrote a simple game to learn how to deploy a game to be played on the web, but I am not sure what files have to be uploaded to my server.

1) Where is the compiled code I should deploy?: In some places I found that the "war" directory has the files I need to deploy. In other places I found that the "build/dist" (generated running gradle's dist task) has the files.

2) What files should I deploy: The war directory gives me the hint I should deploy everything into a servlet container like Tomcat because, besides of the name, I have a war directory structure (it has a WEB-INF sub-dir). But in the badlogic info I found it says I only need to deploy Assets, html, and the index.html file to a WEBSERVER.

Note: Both ways work, so perhaps the deployment of the full war is to be done under certain conditions. So which would these conditions be?

3) I've read about the SuperDev mode to debug the app. When I run the application I get a SuperDev blue button in the browser. When I compile using GWT (I understand this generates production mode) I stilll get the blue SuperDev button. Do I have to remove it manually, or am I doing something wrong?

Please, can someone put a bit of light on this?