texts:
I have a bunch of enemies chasing my main-character, and if they intersect I want them to damage him and that's all good. The problem is that right now they damage him as long as they stand around him, every frame! and since it gets called every frame my character's HP reaches 0 almost instantly.

I've tried adding delay and I've tried a timertask, but can't get it to work.

This is the code I use to check for intersection:

private void checkCollision(Canvas canvas) {
    synchronized (getHolder()) {
        Rect h1 = happy.getBounds();
        for (int i = 0; i < enemies.size(); i++) {
            for (int j = 0; j < bullets.size(); j++) {
                Rect b1 = bullets.get(j).getBounds();
                Rect e1 = enemies.get(i).getBounds();
                if (b1.intersect(e1)) {
                    enemies.get(i).damageHP(5);
                    bullets.remove(j);
                }
                if(e1.intersect(h1)){
                    happy.damageHP(5);
                // this is the statement that needs some sort of delay, I want them to damage him every 2 seconds they intersect him.
                }

                if(enemies.get(i).getHP() <= 0){
                    enemies.get(i).death(canvas, enemies);
                    score.incScore(5);
                    break;
                }
                if(happy.getHP() <= 0){
                    score.incScore(-50);
                    //end-screen
                }
            }
        }
    }
}

If anyone knows the logic to do this please do tell.


texts:
I am currently making a game that I was originally planning to sell. It is a simple 2D arcade style game for the PC. I've seen many indie games become popular and generate revenue from advertisements, but the game itself remains free. I need some advice on whether or not I should sell my game, release it for free with advertisements, or ask for donations and keep the game free.

I feel that my game is fun, but of course the graphics aren't tip top because I am a programmer, not an artist. I just take screenshots of 3D models I get from Turbosquid and crop around it to make a sprite. Also, and I could be very wrong about this, it seems that there are more legal issues surrounding selling a game than making it free and generating revenue from advertisement, or asking for donations. If I am wrong, someone please correct me.

Also, I am very interested in generating some revenue for my work, but that isn't at the very top of my list. I am in my last year of high school, soon to be going to college, and I am going to major in computer science/software engineering. So I am trying to gain some preliminary experience at home by coding stuff every day. One way of getting this experience is by making this game.

So what do you think? What route should I take? What has worked well with other indie games?

Thanks in advance.


texts: Handle Input Processor in Device Back Button and Button as Actor

texts:
How to handle a event for both key as well as actor added in the screen? My problem is that at a time only one input processor is available either for button or device back button. How can I set input processor for both back button of device and button which act as actor on the screen.

I implemented following code for button input processor
Gdx.input.setInputProcessor(stage);
button was added in the stage so I implement input processor for the stage.

For device back button
Gdx.input.setInputProcessor(this);
Register actor as input processor

In keyDown event I write
if (keycode == Keys.ESCAPE || keycode == Keys.BACK)
    LevelLoadScreen.flagResume = true;

Other solution also acceptable if it handle both the action listener


texts: Will using a fixed point library in C++ give me 100% deterministic replays?

texts:
I'm working on a scrolling arcade shooter in C++ with SDL2 and I'd like to have a replay function so players can save, share, and replay good runs. I understand that floating point math is not consistent from CPU to CPU, so saving inputs with frame counters won't give you stable replays. I saw someone mention that fixed point math is a possible solution, so I'm currently working on a C++ engine using Libfixmath fix16_t datatypes in place of anything that would be a floating point.
Should this give me 100% deterministic replays across hardware if I save the random seed? From my understanding of how a fixed point math library works that should be the case, but I would like some confirmation before I bank my entire engine around this. Really my only concern is that I'm using literal floats to set the starting values for some things, like fix16_from_float(1.2) to set the player's movement speed and I'm not entirely sure if CPU inconsistency could mess up that initial value and thus defeat the purpose. If so, could I solve the problem by using fix16_from_int() paired with some Libfixmath arithmetic to get the same non-integer values without ever using floats? I don't quite have a complete grasp on how literals are stored into a compiled program.
I am also a tad worried about performance with potentially hundreds of onscreen bullets using high level fixed point math every frame, but I'll have to see how much impact that has when I get to it.


texts: What are the biggest pitfalls to consider when developing a new game?

texts:
I actually just started tracing (thanks David Young for the nomenclature correction) a couple of new web-based games for Facebook a few weeks ago and I have just been inundated with mental blocks and time sucks from re-coding.  I am working on something similar to the turn based (Vampire Wars) style RPG.  I have the skills to code a game but I am slogging through trying to get the design patterns right and make the product match what I see in my mind's eye.

Normally when building a website I like to 'think in code' and I find it faster for me to just change the code/HTML to tweak it in.  This is probably because I am VERY comfortable in what I do and I know what to expect as I've done it over and over again.  At this point with game development I find myself starting on paper again (like I used to with websites) and I wonder if this is just my lack of focus and intuition with game logic or if this is an appropriate way to roll my thoughts out in advance of coding.

I would appreciate some advice on how to correctly attack this problem and keep myself on-task.  I am quickly learning how much differently a game engine is from a standard business website!  Every time I do get something in place it just feels mooshy and incomplete and it's becoming darned frustrating.

Extended

As an example, the battle engine that has been giving me so much issue recently takes a simple attack skill and then makes a random roll between -50% and +50% and then multiplies the original attack skill against that percent.  The same thing is done with defense and then I mesh those to determine if any damage is done against the enemy health.  I guess I should realize I am in over my head when I started asking myself if that is even the right way to do it, or if there even IS a 'right' way.  One major fault I found with this is two characters around the same level can have several 'rolls' where the attack is -50% and the defense is +50% so I end up with some EXTREMELY long battle sequences where nobody does anything.  FAIL

Maybe my post should have been asking for suggested links describing simple game logic.

End Extension

Thank you all in advance!


texts: How can I reward dungeon masters that take risks?

texts:
I am working on a MORPG project featuring essentially two major roles: adventurers and dungeon masters. My concern is about balancing the two roles.

For those who have heard of it, the principle is inspired from the French comics Dungeon. The business model of a dungeon, as stated in the comics, is the following:
dungeon masters place treasures in heavily guarded dungeons, to lure in adventurers seeking fame and fortune. While some of them succeed, most die in the process, dropping valuable items which joins the pile of treasures of the dungeon, further attracting more adventurers.
Dungeon master make a living by collecting the right amount from these drops to create new rooms, pay mercenaries, fetch new creatures, breed dragons and whatnot.

Adventurers are quite classic: they are combat oriented characters that can attack monsters or fellow players and earn XP, items and money in the process, gradually making them stronger.

Dungeon masters are trade oriented. Their difficulty is balancing budgets: treasures and dragons are expensive. Now, I already expect a sort of equilibrium among dungeon masters because dungeons that are either too hard or too easy are naturally penalized (low attempt rate or low kill rate, respectively). DM vs DM balancing: check.

Since PvP combat is enabled in dungeons, there is also a competition  among adventurers pushing weak players to stick to easy dungeons that offer little reward to more advanced players. Adventurers vs advanturers balancing: check.

However there is one specific imbalance between the two roles that I am trying to solve: adventurers have a bias toward attempting dungeons above their league, because even if they die (dropping some items and respawning outside the dungeon), they will have gained some XP in the process. This is good because it rewards risk-takers. On the other hand, dungeon masters do not have any advantage of this kind: if an adventurer completes the dungeon and escapes with their share of the treasure, nothing is gained. This would be a pity if it lead dungeon master to be too cautious about their defenses, killing the probability of ever completing the dungeon. Adventurer vs DM balancing: problem.

Hence my question: what reward mechanism could I introduce that incitates dungeon masters to maintain a small but non-zero winning probability?


texts: Collision resolution moving Point to AABB with raycasting

texts:
This is probably trivial, but I'm having trouble making it work.

I have a 3-coordinate world of particles simulated with Verlet Velocity. I only care for collision between their centers and a few static AABBs.

Essentially, I can't get a clean way of resolving a collision.

For example, say I have a box with coordinates:

min = (0, -1, -384)
max = (512, 1, 0)

Any particle colliding with it should stop moving in the relevant direction, but continue moving in the others - not bounce off.

I have one particle at pos that in a single timestep wants to go to newpos (it's being pushed both downward and eastward):

pos = (-0.068037, 0.000000, -58.516845)
newpos = (0.014446, 0.000000, -58.555490)

Clearly, on the X axis there is a collision. My ray collider detects it and pops back the point where the ray intersects the AABB:

intersection = (0.000000, 0.000000, -58.548722)

Now, if I just set the position to that point, at the next time step there will be a collision because the position will be exactly on the border of the AABB.

This makes every particle "stick" to whatever box they collide with. In the previous example, I'd like to have the particle slide down the AABB wall according to its current velocity.

How can I do that?


texts: Method keyTyped in ClickListener is not working

texts:
When im click my SelectBox and press some key, nothing happens.

sbNationality.addListener(new ClickListener() {
    @Override
    public boolean keyTyped(InputEvent event, char character) {
        System.out.println(character);
        return super.keyTyped(event, character);
    }
});

Im doing something wrong?


texts: Why the AnchorPoint doesn't affect the `CCLayer` Positioning?

texts:
I think there is a difference between the CCLayer and CCNode behavior when I change their AnchorPoint.

I will describe what I mean and please somebody explain it.

Scenario:
I start with CCNode

CCNode *node = ...;
node.setContentSize(ccp(W,H));
// 1.
node.setAnchorPoint(ccp(0,0));
node.setPosition(ccp(X,Y); // This line will move the node in a way that its (0,0)-point will be placed at (X,Y).
// 2.
node.setAnchorPoint(ccp(1,1));
node.setPosition(ccp(X,Y); // This line will move the node in a way that its (0,0)-point will be placeed at (X-W,Y-H).
//In other word, this line will move the (W,H)-point of the node to (X,Y)

In addition to the Positioning, all actions (like Rotating, Scaling) are based on this anchor point.

This policy is fair enough and you won't get confused when moving a scaled node (setScale(X)) to some position because the node's position ( and not node's contents!) will not change in the screen after any actions.

( PS: We knew that rotating/scaling a node will rotate/scale internal node contents)

Let's continue with CCLayer:

CCLayer *layer= ...;
layer.setContentSize(ccp(W,H));
// 1.
layer.setAnchorPoint(ccp(0,0));
layer.setPosition(ccp(X,Y); // This line will move the layer in a way that its (0,0)-point will be placed at (X,Y)
// 2.
layer.setAnchorPoint(ccp(1,1));
layer.setPosition(ccp(X,Y); // Unfortunately, This line will move the layer in a way that its (0,0)-point will be placeed at (X,Y).

Although CCLayer also use the anchor point for scaling, rotating and ... purposes, It does NOT use its anchor point for positioning!!!

Question >>>>  WHY? and How can I have the same CCNode-like setPosition() behaviour for CCLayer?

PS: I've also tried ->ignoreAnchorPointForPosition(true) but it didn't help.

(@cocos2d-x version is 2.2.3)


texts: What are some basic zoning guidelines for designing game cities?

texts:
I am planning out a fictional game city. Based on the gameplay and story I have decided on several locations which will need to exist. I'm wondering though to what extent I need to take zoning into consideration when planning everything out. For example, there is an industrial area with processing plants, but there is also a residential area fairly close to this.

It is my understanding that industrial areas need to be a certain distance away from residential areas due to health concerns. This varies of course based on many factors, but I'm wondering to what extent I should be considering this when planning out the city. The game in no way requires realistic city planning, but for the sake of not making it obviously unrealistic I'm wondering if there are any rules of thumbs when planning this.


texts: Tiles in the Tilemap dont overlap properly

texts:
This is my first try making a "proper" game in Unity. I'm using the latest version (2019.2.2 at the time of writing) and I'm writing with C#. This is a project I'm doing for my studies, together with another person (he makes tiles, sound, music and I'm at charge of the programming).

We are making a 2D Roguelike RPG using the Unity tilemap feature.

My algorithm to generate dungeons works really well, but only used one ground tile and one wall tile. We found that to be very boring and changed it.

Now comes the problem. If I let the algorithm pick between fewer than 3 tiles, everything works fine.

If I let the algorithm pick from more than 2 tiles, something strange happens and the some tiles don't overlap properly.

I hope somebody can help me understand why this happens.

Here the important settings of camera and tilemap:

Camera
Grid
GroundLayer
WallLayer

One weird think I have been able to find out: The tiles that don't overlap will change if I change the position of the camera.

As a gif:


texts: Ray Intersecting Plane Formula in C++/DirectX

texts:
I'm developing a picking system that will use rays that intersect volumes and I'm having trouble with ray intersection versus a plane. I was able to figure out spheres fairly easily, but planes are giving me trouble. I've tried to understand various sources and get hung up on some of the variables used within their explanations.

Here is a snippet of my code:

   bool Picking()
 {
  D3DXVECTOR3 vec;
  D3DXVECTOR3 vRayDir;
  D3DXVECTOR3 vRayOrig;
  D3DXVECTOR3 vROO, vROD; // vect ray obj orig, vec ray obj dir
  D3DXMATRIX m;
  D3DXMATRIX mInverse;
  D3DXMATRIX worldMat;

                // Obtain project matrix
  D3DXMATRIX pMatProj =   CDirectXRenderer::GetInstance()->Director()->Proj();
                // Obtain mouse position
  D3DXVECTOR3 pos = CGUIManager::GetInstance()->GUIObjectList.front().pos;

                // Get window width & height
  float w = CDirectXRenderer::GetInstance()->GetWidth();
  float h = CDirectXRenderer::GetInstance()->GetHeight();

                // Transform vector from screen to 3D space
  vec.x =  (((2.0f * pos.x) / w) - 1.0f) / pMatProj._11;
  vec.y = -(((2.0f * pos.y) / h) - 1.0f) / pMatProj._22;
  vec.z = 1.0f;

                // Create a view inverse matrix
  D3DXMatrixInverse(&m, NULL, &CDirectXRenderer::GetInstance()->Director()->View());

                // Determine our ray's direction
  vRayDir.x = vec.x * m._11 + vec.y * m._21 + vec.z * m._31;
  vRayDir.y = vec.x * m._12 + vec.y * m._22 + vec.z * m._32;
  vRayDir.z = vec.x * m._13 + vec.y * m._23 + vec.z * m._33;

                // Determine our ray's origin
  vRayOrig.x = m._41;
  vRayOrig.y = m._42;
  vRayOrig.z = m._43;

  D3DXMatrixIdentity(&worldMat);
  //worldMat = aliveActors[0]->GetTrans();
  D3DXMatrixInverse(&mInverse, NULL, &worldMat);

  D3DXVec3TransformCoord(&vROO, &vRayOrig, &mInverse);
  D3DXVec3TransformNormal(&vROD, &vRayDir, &mInverse);
  D3DXVec3Normalize(&vROD, &vROD);

When using this code I'm able to detect a ray intersection via a sphere, but I have questions when determining an intersection via a plane. First off should I be using my vRayOrig & vRayDir variables for the plane intersection tests or should I be using the new vectors that are created for use in object space?

When looking at a site like this for example: http://www.tar.hu/gamealgorithms/ch22lev1sec2.html

I'm curious as to what D is in the equation AX + BY + CZ + D = 0 and how does it factor in to determining a plane intersection?

Any help will be appreciated, thanks.


texts:
After reading this link I am still unclear as to the shading language support in Vulkan.

As Vulkan only supports SPIR-V is it the case that GLSL is therefore being phased out? Are there any indication of what the next 5 years looks like in terms of the "hot"  language to study in for graphics programming?


texts:
Recently, this question popped up on here, and it made me wonder if there was a better way to earn money from one's game without using microtransactions.

So, What are good alternatives to microtransactions?


texts: Is it possible to place a MenuStrip into a XNA 4.0 project. This project is intended for PC-s only and I already have openFile dialogs, but I cant get the MenuStrip drawn. If this is not possible what would be a good alternative. I've been trying to get find it on create.msdn but it keeps redirecting me to the WinPhone/XBox selection page and I cant access the tutorials at all.


texts: Storing game objects with generic object information

texts:
In a simple game object class, you might have something like this:

public abstract class GameObject {

    protected String name;
    // other properties
    protected double x, y;

    public GameObject(String name, double x, double y) {

        // etc
    }

    // setters, getters
}

I was thinking, since a lot of game objects (ex. generic monsters) will share the same name, movement speed, attack power, etc, it would be better to have all that information shared between all monsters of the same type.

So I decided to have an abstract class "ObjectData" to hold all this shared information. So whenever I create a generic monster, I would use the same pre-created "ObjectData" for it. Now the above class becomes more like this:

public abstract class GameObject {

    protected ObjectData data;
    protected double x, y;

    public GameObject(ObjectData data, double x, double y) {

        // etc
    }

    // setters, getters

    public String getName() {

        return data.getName();
    }
}

So to tailor this specifically for a Monster (could be done in a very similar way for Npcs, etc), I would add 2 classes. Monster which extends GameObject, and MonsterData which extends ObjectData. Now I'll have something like this:

public class Monster extends GameObject {

    public Monster(MonsterData data, double x, double y) {

        super(data, x, y);
    }
}

This is where my design question comes in. Since MonsterData would hold data specific to a generic monster (and would vary with what say NpcData holds), what would be the best way to access this extra information in a system like this? At the moment, since the data variable is of type ObjectData, I'll have to cast data to MonsterData whenever I use it inside the Monster class.

One solution I thought of is this, but this might be bad practice:

public class Monster extends GameObject {

    private MonsterData data; // <- this part here

    public Monster(MonsterData data, double x, double y) {

        super(data, x, y);

        this.data = data; // <- this part here
    }
}

I've read that for one I should generically avoid overwriting the underlying classes variables.

What do you guys think of this solution? Is it bad practice? Do you have any better solutions? Is the design in general bad? How should I redesign this if it is?

Thanks in advanced for any replies, and sorry about the long question. Hopefully it all makes sense!


texts: Marble / Wheel Game Physics - Kinetic vs Static Friction?

texts:
I've read a bit about the "normal force" modeling of friction here. I gather that it isn't a full picture, but a decent approximation, if it fits the needs of what you are trying to model.

It mentions that there's a static friction and a kinetic friction where the static friction is the amount of force that needs to be overcome before an object will begin moving, and then the kinetic friction specifies how much force you need to apply to keep the object moving.

For the case of a ball rolling or a wheel spinning, I know that a little bit of force will cause it to roll, while applying a lot of force will cause it to "slip" and lose contact / friction with the ground and start spinning.

In this case, is it the static friction that determines how much force you can apply to a wheel or a ball before it starts to slip, and then it's the kinetic friction that determines how it acts when it is slipping?


texts: How can I create 2D, sprite-based reflections in HTML5 Canvas?

texts:
I'm trying to create simple reflections in a 2D, sprite-based game using HTML5. I'm looking to recreate an effect like the one you'd often see in GBA games, such as Pokemon Emerald and Mother 3:

These days we don't really get to see many 2D games that pull off this kind of effects.  How could I achieve this with HTML5 Canvas?


texts: How do I use raycast to put a bullet hole on a curved surface?

texts:
EDIT: As of yet I have not been able to find a way to make the bullet hole wrap around the corner of a gameobject.

I am working on a fps game that uses raycast for shooting and so far it works, but the problem is with the bullet holes. So the script will generate bullet holes (not going to explain everything it does) like it is supposed to.

The problem is that if I shoot the corner the bullet hole will just generate on whatever side the impact was closest to. How do I get the bullet hole to spawn on curves and corners? Here is the script:

public class HitFXManager : MonoBehaviour
{

    [Range(1, 200)]
    public int decalsPoolSizeForEachType;

    public GameObject concreteDecal;
    public GameObject woodDecal;
    public GameObject dirtDecal;
    public GameObject metalDecal;

    [HideInInspector]
    public GameObject[] concreteDecal_pool;
    [HideInInspector]
    public GameObject[] woodDecal_pool;
    [HideInInspector]
    public GameObject[] dirtDecal_pool;
    [HideInInspector]
    public GameObject[] metalDecal_pool;

    void Start()
    {
        DecalsPool();
    }

    public void DecalsPool()
    {
        concreteDecal_pool = new GameObject[decalsPoolSizeForEachType];
        var decalsParentObject_concrete = new GameObject("decalsPool_concrete");

        for (int i = 0; i < decalsPoolSizeForEachType; i++)
        {
            concreteDecal_pool[i] = Instantiate(concreteDecal);
            concreteDecal_pool[i].SetActive(false);
            concreteDecal_pool[i].transform.parent = decalsParentObject_concrete.transform;
        }

        woodDecal_pool = new GameObject[decalsPoolSizeForEachType];
        var decalsParentObject_wood = new GameObject("decalsPool_wood");

        for (int i = 0; i < decalsPoolSizeForEachType; i++)
        {
            woodDecal_pool[i] = Instantiate(woodDecal);
            woodDecal_pool[i].SetActive(false);
            woodDecal_pool[i].transform.parent = decalsParentObject_wood.transform;
        }

        dirtDecal_pool = new GameObject[decalsPoolSizeForEachType];
        var decalsParentObject_dirt = new GameObject("decalsPool_dirt");

        for (int i = 0; i < decalsPoolSizeForEachType; i++)
        {
            dirtDecal_pool[i] = Instantiate(dirtDecal);
            dirtDecal_pool[i].SetActive(false);
            dirtDecal_pool[i].transform.parent = decalsParentObject_dirt.transform;
        }

        metalDecal_pool = new GameObject[decalsPoolSizeForEachType];
        var decalsParentObject_metal = new GameObject("decalsPool_metal");

        for (int i = 0; i < decalsPoolSizeForEachType; i++)
        {
            metalDecal_pool[i] = Instantiate(metalDecal);
            metalDecal_pool[i].SetActive(false);
            metalDecal_pool[i].transform.parent = decalsParentObject_metal.transform;
        }

    }
}


texts:
I'm trying to re-create an arcball example from a Nehe, where an object can be rotated in a more realistic way while floating in the air (in my game the object is attached to the player at a distance like for example the Physics Gun) however I'm having trouble getting this to work with UDK.

I have created an LGArcBall which follows the example from Nehe and I've compared outputs from this with the example code.

I think where my problem lies is what I do to the Quaternion that is returned from the LGArcBall.

Currently I am taking the returned Quaternion converting it to a rotation matrix. Getting the product of the last rotation (set when the object is first clicked) and then returning that into a Rotator and setting that to the objects rotation.

If you could point me in the right direction that would be great, my code can be found below.

class LGArcBall extends Object;

var Quat StartRotation;
var Vector StartVector;
var float AdjustWidth, AdjustHeight, Epsilon;

function SetBounds(float NewWidth, float NewHeight)
{
    AdjustWidth = 1.0f / ((NewWidth  - 1.0f) * 0.5f);
    AdjustHeight = 1.0f / ((NewHeight - 1.0f) * 0.5f);
}

function StartDrag(Vector2D startPoint, Quat rotation)
{
    StartVector = MapToSphere(startPoint);
}

function Quat Update(Vector2D currentPoint)
{
    local Vector currentVector, perp;
    local Quat newRot;

    //Map the new point to the sphere
    currentVector = MapToSphere(currentPoint);

    //Compute the vector perpendicular to the start and current
    perp = startVector cross currentVector;

    //Make sure our length is larger than Epsilon
    if (VSize(perp) > Epsilon)
    {
        //Return the perpendicular vector as the transform
        newRot.X = perp.X;
        newRot.Y = perp.Y;
        newRot.Z = perp.Z;

        //In the quaternion values, w is cosine (theta / 2), where
        //theta is the rotation angle
        newRot.W = startVector dot currentVector;
    }
    else
    {
        //The two vectors coincide, so return an identity transform
        newRot.X = 0.0f;
        newRot.Y = 0.0f;
        newRot.Z = 0.0f;
        newRot.W = 0.0f;
    }

    return newRot;
}

function Vector MapToSphere(Vector2D point)
{
    local float x, y, length, norm;
    local Vector result;

    //Transform the mouse coords to [-1..1]
    //and inverse the Y coord
    x = (point.X * AdjustWidth) - 1.0f;
    y = 1.0f - (point.Y * AdjustHeight);

    length = (x * x) + (y * y);

    //If the point is mapped outside of the sphere
    //( length > radius squared)
    if (length > 1.0f)
    {
        norm = 1.0f / Sqrt(length);

        //Return the "normalized" vector, a point on the sphere
        result.X = x * norm;
        result.Y = y * norm;
        result.Z = 0.0f;
    }
    else //It's inside of the sphere
    {
        //Return a vector to the point mapped inside the sphere
        //sqrt(radius squared - length)
        result.X = x;
        result.Y = y;
        result.Z = Sqrt(1.0f - length);
    }

    return result;
}

DefaultProperties
{
    Epsilon = 0.000001f
}

I'm then attempting to rotate that object when the mouse is dragged, with the following update code in my PlayerController.

    //Get Mouse Position
    MousePosition.X = LGMouseInterfacePlayerInput(PlayerInput).MousePosition.X;
    MousePosition.Y = LGMouseInterfacePlayerInput(PlayerInput).MousePosition.Y;

    newQuat = ArcBall.Update(MousePosition);

    rotMatrix = MakeRotationMatrix(QuatToRotator(newQuat));
    rotMatrix = rotMatrix * LastRot;

    LGMoveableActor(movingPawn.CurrentUseableObject).SetPhysics(EPhysics.PHYS_Rotating);
    LGMoveableActor(movingPawn.CurrentUseableObject).SetRotation(MatrixGetRotator(rotMatrix));


texts: Reconstructing Position from Depth - Inverted Y?

texts:
I am currently trying to understand the following wierd result. This is basically from deferred shading in monogame/XNA. For Comparison I also write the ViewSpace Position in a Buffer and the ViewSpace Depth in another buffer like so:

float4 viewPosition = mul(input.Position, WorldView);
depth = viewPosition.z;

(the depth value is sent to a rendertarget with surfaceformat vector2 = 2x32bit float), the position-buffer now looks like so:

(this is basically just a quad with a cube in the middle and some elevation in top left)

What I do now is I calculate the CornerFrustum on the CPU:

Vector3 cfrust = Vector3.Zero;
cfrust.Y = camera.FarClip * (float)Math.Tan(camera.FOV * 0.5f);
cfrust.X = cfrust.Y * camera.AspectRatio;
cfrust.Z = camera.FarClip;

The Fullscreen-quad is aligned with that frustum in mind:

new VertexPositionTexture(new Vector3(1, -1, 0), new Vector2(1, 1)),
new VertexPositionTexture(new Vector3(-1, -1, 0), new Vector2(0, 1)),
new VertexPositionTexture(new Vector3(-1, 1, 0), new Vector2(0, 0)),
new VertexPositionTexture(new Vector3(1, 1, 0), new Vector2(1, 0))

now in the VS I get the ViewRay / ViewDirection like this

output.ViewDirection = float3(-CornerFrustum.x * input.Position.x, CornerFrustum.y * input.Position.y, CornerFrustum.z);

in PS I now try to reconstruct the ViewPosition from ViewRay/Depth

float3 ViewRay = normalize(input.ViewDirection);
float Depth = tex2D(sampler_depth, input.UV).r;
float3 ViewPosition = Depth * ViewRay;

I should now have the ViewPosition of that pixel, right?

I am now converting this back to screen by

float4 ScreenPosition = mul(float4(ViewPosition, 1.0),Projection);
float2 ScreenUV = 0.5 * (ScreenPosition.xy / ScreenPosition.w) + float2(0.5,0.5);

if I now output that position to the screen I get this:

as the colors suggests, the Y-Axis is inverted? (It's negative now, so the corresponding channel is clamped to 0 in the output, basically inverting the colors)

This gives me trouble now, because as a consequence (this is used in a SSAO shader) the SSAO samples (hemisphere) are moved along the inverted y-axis as well.

I fear I am missing something, because the generated UVs are actually correct. As they sample the correct piece. If I use those "ScreenUV" to sample from the PositionBuffer I do get the correct result (the exact same as the first image). I just cannot understand, why the position is inverted in the y-axis (it's now pointing down instead of up.


texts: How can I read .TGA and .BLP image files in C++?

texts: Is there a C++ library that enables reading of .tga and .blp image formats on Windows?


texts: How can I make sure my OpenCL code works correctly on different graphic cards?

texts:
I'm testing on adding some OpenCL code in my game, but I only have a single Nvidia card & I'm not sure the code will run normally on other platforms.

Is there any way to make sure my code runs as expected on different graphic cards without having direct access to the hardware myself?


texts: How to draw a Voronoi Splitscreen view in GMS, where each player's screen area is a polygon shape?

texts:
I'm trying to implement the Voronoi Splitscreen effect that Squirrel Eiserloh described at GDC 2016, and I'm having trouble figuring out how to 'clip' the rendered scene for one player along a diagonal line or polygonal shape.

So how can I draw the scene inside set of points or a shape other than rectangle?


texts: How to create scrollable text in AndEngine?

texts:
I'm creating some tutorial text that the user should be able to scroll.

Is there any way to make vertical scroll in AndEngine so that we can easily view all the content by scrolling up and down?


texts:
I keep getting the following error when i try to drag and drop a script to my gameobject:

I have made sure that both my Script name and the class name is : Soldier as you can see:

public class Soldier : MonoBehaviour
{
    public int Rank;
}

So my question is what have i done wrong?


texts: Questions about Jrpg NPC events (Unity C#)

texts:
So, I'm trying to wrap my head around something. I've got my basic quest system up and running for my rpg style game.

Right now I'm taking a look at NPC events and triggers that as I see it have two distinct styles

The classic floor panel trigger that rpg maker uses or
have a listener class for quest active / event active

My questions are thusly what's the best way to go about activating the event and what's a good way to define the event? Like set movement patterns etc would it be feasible in json? Or should I use scriptable objects?


texts: What elements make a simple game addictive?

texts:
Possible Duplicates:
What should a game have in order to keep humans playing it?
How can I make my score-based game addictive
What makes puzzle games addictive?

I am creating simple game for iPhone like "Bubble Explode". Generally, what elements of game make it addictive and exciting for similar simple games.


texts: Drawing polygons with a repeating texture on iOS

texts: I want to draw a terrain for a 2d game, and this terrain is defined by some rotated rectangles and circles, I want to draw my terrain as if it was a repeating texture clipped by those forms. I already modified the cocos2d draw primitives methods to draw them using a triangle fan, but I'm not sure how to apply a texture on them.


texts: How to create a projectile motion of a cannonball in top down view?

texts:
Objective

To move the bullet with projectile motion to specific destination by touch point.

In the below image is an example of a bullet which has a projectile motion. On my observation, the bullet speed and angle is calculated base on distance.

(source: pixwerk.net)

Where I'm at? (How do I move the bullet to its destination?)

In the below code, is the method I use to move a bullet to its destination. But the problem is I want to create a cannonball bullet which it has a projectile motion. How do I create these tricks to make a cannon ball projectile motion like the image below.

public Vector2 getVelocity(Vector2 currentPosition, Vector2 targetPosition) {
    Vector2 targetDirection = targetPosition.cpy().sub(currentPosition);
    return targetDirection
            .nor();
}

What I have done? (Currently I could move the bullet straight to its destination.)

Bullet is moving straight (It's not problem).

[EDIT]

Drawing a projected trajectory

To get the trajectory point, base on iforced example. I've already have the libgdx box2d version of this.

b2Vec2 getTrajectoryPoint( b2Vec2& startingPosition, b2Vec2& startingVelocity, float n )
  {
      //velocity and gravity are given per second but we want time step values here
      float t = 1 / 60.0f; // seconds per time step (at 60fps)
      b2Vec2 stepVelocity = t * startingVelocity; // m/s
      b2Vec2 stepGravity = t * t * m_world->GetGravity(); // m/s/s

      return startingPosition + n * stepVelocity + 0.5f * (n*n+n) * stepGravity;
  }

Rendering the trajectory point

glColor3f(1,1,0);
  glBegin(GL_LINES);
  for (int i = 0; i < 180; i++) { // three seconds at 60fps
      b2Vec2 trajectoryPosition = getTrajectoryPoint( startingPosition, startingVelocity, i );
      glVertex2f(trajectoryPosition.x, trajectoryPosition.y );
  }
  glEnd();

[Solve]

The answer is to find the angle and speed by the distance by s.tarik.cetin

Another issue encountered (this must be move to another question)

This is the problem, I don't know how do I set the starting velocity. Currently in the below code, to set the startingVelocity and startingPosition where the underlined code is the part that I'm not sure.

    touchPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0);
    camera.unproject(touchPoint);

    Vector2 touch = new Vector2(touchPoint.x, touchPoint.y);
    Vector2 touchDirection = touch.cpy().sub(bulletPosition).nor(); // get the the direction from bullet position to touch point and normalize the value.

    float distance = touchDirection.dst(startingPosition);
    float angle = touch.angle();
    float speed = 6.0f; // currently the speed is fixed. I need to know the speed base on distance

    startingPosition.set(bulletPosition); // current position of the bullet
    startingVelocity.set(touchDirection.scl(speed)); // where the bullet should be


texts: MonoGame/Xna gamepad inputs and joystick

texts:
I've been around xna game development since very recently, and I'm actually developing a sort of Library for my games. But then I want to make an enemy with default Player settings for keys layouts and stuff. I've managed to create one for Qwerty and Azerty but I also want to create one for gamepad Controllers. Here comes the problem. The default XNA Input Framework is very limited (I think) because, from what I saw, it only manages few buttons that do not include Dpad or Joysticks.

So, is there a way to manage them in xna? or do I need an external Library?

Thanks for your help;


texts: Unable Compile Unreal Project into .Exe File

texts:
I'm new to Unreal Engine and I've been looking for an answer online but I don't understand why the project I just started on is unable to compile. I only used the default blueprints. The error logs are below.
UATHelper: Packaging (Windows (64-bit)): Running AutomationTool...
UATHelper: Packaging (Windows (64-bit)): Parsing command line: -ScriptsForProject=C:/Users/belmo/OneDrive/Documents/GitHub/EscapeFromDarksidePenitentiary/EscapeFromDarkSide/EscapeFromDarkSide.uproject BuildCookRun -nocompileeditor -installed -nop4 -project=C:/Users/belmo/OneDrive/Documents/GitHub/EscapeFromDarksidePenitentiary/EscapeFromDarkSide/EscapeFromDa
rkSide.uproject -cook -stage -archive -archivedirectory=C:/Users/belmo/OneDrive/Documents/GitHub/EscapeFromDarksidePenitentiary/EscapeFromDarkSide -package -ue4exe="C:\Program Files\Epic Games\UE_4.26\Engine\Binaries\Win64\UE4Editor-Cmd.exe" -ddc=InstalledDerivedDataBackendGraph -pak -prereqs -nodebuginfo -targetplatform=Win64 -clientconfig=Development -utf8
output
UATHelper: Packaging (Windows (64-bit)): Setting up ProjectParams for C:\Users\belmo\OneDrive\Documents\GitHub\EscapeFromDarksidePenitentiary\EscapeFromDarkSide\EscapeFromDarkSide.uproject
UATHelper: Packaging (Windows (64-bit)): ********** COOK COMMAND STARTED **********
UATHelper: Packaging (Windows (64-bit)): Running UE4Editor Cook for project C:\Users\belmo\OneDrive\Documents\GitHub\EscapeFromDarksidePenitentiary\EscapeFromDarkSide\EscapeFromDarkSide.uproject
UATHelper: Packaging (Windows (64-bit)): ERROR: Cook failed.
UATHelper: Packaging (Windows (64-bit)):        (see C:\Users\belmo\AppData\Roaming\Unreal Engine\AutomationTool\Logs\C+Program+Files+Epic+Games+UE_4.26\Log.txt for full exception trace)
PackagingResults: Error: Cook failed.
UATHelper: Packaging (Windows (64-bit)): AutomationTool exiting with ExitCode=25 (Error_UnknownCookFailure)
UATHelper: Packaging (Windows (64-bit)): BUILD FAILED
PackagingResults: Error: Unknown Cook Failure
LogD3D11RHI: CreateSwapChainForHwnd failed with result 'DXGI_ERROR_INVALID_CALL' (0x887A0001), falling back to legacy CreateSwapChain.
LogEditorViewport: Clicking on Actor (LMB): StaticMeshActor (Cube11)
LogSlate: Window 'Output Log' being destroyed
LogSlate: Window 'Output Log' being destroyed
LogD3D11RHI: CreateSwapChainForHwnd failed with result 'DXGI_ERROR_INVALID_CALL' (0x887A0001), falling back to legacy CreateSwapChain.
LogD3D11RHI: CreateSwapChainForHwnd failed with result 'DXGI_ERROR_INVALID_CALL' (0x887A0001), falling back to legacy CreateSwapChain.
LogD3D11RHI: CreateSwapChainForHwnd failed with result 'DXGI_ERROR_INVALID_CALL' (0x887A0001), falling back to legacy CreateSwapChain.
LogD3D11RHI: CreateSwapChainForHwnd failed with result 'DXGI_ERROR_INVALID_CALL' (0x887A0001), falling back to legacy CreateSwapChain.
LogD3D11RHI: CreateSwapChainForHwnd failed with result 'DXGI_ERROR_INVALID_CALL' (0x887A0001), falling back to legacy CreateSwapChain.
LogD3D11RHI: CreateSwapChainForHwnd failed with result 'DXGI_ERROR_INVALID_CALL' (0x887A0001), falling back to legacy CreateSwapChain.
LogD3D11RHI: CreateSwapChainForHwnd failed with result 'DXGI_ERROR_INVALID_CALL' (0x887A0001), falling back to legacy CreateSwapChain.
LogD3D11RHI: CreateSwapChainForHwnd failed with result 'DXGI_ERROR_INVALID_CALL' (0x887A0001), falling back to legacy CreateSwapChain.
LogD3D11RHI: CreateSwapChainForHwnd failed with result 'DXGI_ERROR_INVALID_CALL' (0x887A0001), falling back to legacy CreateSwapChain.
LogD3D11RHI: CreateSwapChainForHwnd failed with result 'DXGI_ERROR_INVALID_CALL' (0x887A0001), falling back to legacy CreateSwapChain.
LogD3D11RHI: CreateSwapChainForHwnd failed with result 'DXGI_ERROR_INVALID_CALL' (0x887A0001), falling back to legacy CreateSwapChain.
LogEditorViewport: Clicking on Actor (LMB): StaticMeshActor (Cube11)


texts: I am new to game development and I have created simple games with javascript and SFML. Those games are 2D and there I used images as my gaming assets. I was trying to be familiar with OpenGL like 3D modeling APIs. In 3D gaming is all the assets are 3D models or there can be some images like in 2D?


texts: Make an object rotates by an arbitrary angle and rotates toward a target in Unity

texts:
I have an object facing up in Unity. I need it to move from point A to point B, without prior knowledge of where A and B are. So when I place it at point A, I need to rotate it toward point B. I used this:

this.gameObject.transform.rotation = Quaternion.FromToRotation(A.position, B.position);

However, before doing the movement, I also need to rotate the object by 90° around the X axis. I used this:

this.gameObject.transform.rotation = Quaternion.Euler(90.0f, 0.0f, 0.0f);

These two functions worked, but separately. When I try to use these two functions together, the last function called overrides the other.


texts: What PPU should I choose for assets aimed for different resolution

texts:
So I'm trying to make my pixel-art game handle multiple resolutions. I've stumbled upon this article: https://blogs.unity3d.com/2015/06/19/pixel-perfect-2d/ but I don't understand it completely.

Let's base my question on the example from this article.

My base resolution is 1024x768, PPU is 32 and camera ortographic size is 12. How can I calculate the PPU for assets which will handle 1080p resolution?

In the article, the author took a value of 48. But simply I can't understand where did this value come from.

I'd really appreciate if someone would explain this to me.


texts: Are frequent game updates a solution for preventing multiplayer cheating?

texts:
I'm creating a game on Android where the enforcement of rules can only take place on client side (I can't shift it to server side...think aimbotting but in my case I wouldn't even be able to use heuristics to detect it!).

As I've read many times, the client side is impossible to 100% protect from modification/hacking.

I am going to include protections such as ProGuard obfuscation. But also I'm going to use a formula in the code which encrypts data from the client.

Hackers/cheaters can decompile the code and locate this formula eventually.

But how long will it take for them to uncover the encryption formula? A day, a week? Actually, how long in general does it take for a game to be modded for cheating?

Can I release updates to my game so that by the time hackers release modded versions of my app to public, they become obsolete? If I did release updates, I wouldn't require updates for single player mode, but only when they tried to do multiplayer would a message display telling them they must update.

I just really want to make multiplayer fair and not scare off players because they face opponents with uber-awesome hax.


texts:
void OnMouseDown ()
{
    foreach (Button thisButton in buttonArray)
    {
        thisButton.GetComponent<SpriteRenderer>().color = Color.black;
    }

    GetComponent<SpriteRenderer>().color = Color.white;
}

This code results in whichever button I select changing color to white while the rest are black. However, I am not understanding how this works. How does it know to specifically change ONLY the selected button to white while the rest are black. Seems contradictory to me...


texts: How can I find an animation's final compression size in Unity?

texts: I've been looking at animation compression, and the only way I can seem to find it's final size is to create a Build and check it in the Profiler. There must be an easier way?


texts: Gerstner/Sinusoidal wave directional rotation (flow) in regards to ocean currents/trade winds

texts:
I'm trying to create an ocean simulation using Gerstner waves based on the GPU Gems: Effective Water Simulation from Physical Models. So far I've completed the directional wave functionality and currently want to expand it with an ocean current/trade wind system to drive the global wave direction. I'm having trouble understanding how to create flow of a single directional wave based on a sampled flow field.
Current wind is generated by deriving a flow field from Perlin noise:
float2 dir=float2(cos(2Pi * noise(x,y),sin(2Pi * noise(x,y));
When I input this vector into wave direction(D), the wave breaks at time 0 and direction of the wave doesn't match the flow field vector direction at location (x,y).
I'm using Perlin noise for a flow field as a quick and easy testing tool to get wave rotation in place. How the flow field will be generated for end project purposes is irrelevant right now.
The Gerstner function I'm using:
$$P(x,y,t)=\begin{pmatrix}
x+\sum(Q_iA_i*D_i.x*cos(w_iD_i\cdot(x,y)+\varphi_it) )
\\y+\sum(Q_iA_i*D_i.y*cos(w_iD_i\cdot(x,y)+\varphi_it) )
\\\sum(A_isin(w_iD_i\cdot(x,y)+\varphi_it)))
\end{pmatrix}$$
Would I be missing some variable like wave phase offset or some wave rotation rate? How is wave rotation calculated in regards of changing direction vector based on world position?


texts: Simulate movement towards the screen in a 2D world

texts:
I need to create the illusion of someone kicking a ball to the screen. For that, I have a initial position of the ball (about the middle of the screen), and I put the sprite of the ball scaled at 0.2 of his original size. Then, I generate a random position on the screen, and move the ball sprite to it, and at the same time, I increment the scale of the ball, until I reach 1, the real size.

At this point, the ball "hit" the screen. All this works great, but the scale of the ball is not coordinated with the movement of the ball, and, because of it, I must always wait until the scale reaches zero, after the ball is arrived to his destination, or, I must wait until the ball reach his destination, after the ball is already scaled to 1.

The question is, how must I calculate the resize factor of the ball, so it gets to 1 at the same time that the ball reach the desirable coordinates in the screen? The speed of the ball is a random number between a given range, and, of course, I'm using only 2D sprites.


texts: How to position spawned objects in diamond and grid (row x column) arrangements

texts:
I am creating clones of my objects using the code below:

public List<Vector3> clonePositions;
public List<GameObject> cloneObjects;

for (int i = 0; i < clonePositions.Count; i++)
    {

        cloneObjects.Add(Instantiate(clonedObject,
        clonePositions[i], quaternion.identity));

    }

How can I create and position the cloned game objects in a grid/matrix (row x column) arrangement  (with equal spacing between and at equal spacing at the sides)? as seen below:

and also in a diamond shape arrangement as below:

I would like to keep the clones centered around the original game object.


texts:
Is there a generally accepted pattern for performing various actions within a game? A way a player can perform actions and also that an AI might perform actions, such as move, attack, self-destruct, etc.

I currently have an abstract BaseAction which uses .NET generics to specify the different objects that get returned by the various actions. This is all implemented in a pattern similar to the Command, where each action is responsible for itself and does all that it needs.

My reasoning for being abstract is so that I may have a single ActionHandler, and AI can just queue up different action implementing the baseAction. And the reason it is generic is so that the different actions can return result information relevant to the action (as different actions can have totally different outcomes in the game), along with some common beforeAction and afterAction implementations.

So... is there a more accepted way of doing this, or does this sound alright?


texts: I'm trying to have a body move to the player touch and stop once he reaches the destination. I have the player boxed in to prevent him to move out of bounds, I can somewhat do that with translate but with collision, it doesn't work properly, is there a better solution for this?


texts: (2D) Detect mouse click on object with no script attached

texts:
I'm creating a 2D project which does not have a character. So i created an empty gameobject and attached the script to it. In the script, i have declared other objects which are in the scene like this:

public GameObject obj1,obj2,obj3;

How can I know if obj1 or obj2 or obj3 was clicked? Is raycasting the only solution?


texts: ASSIMP skeletal animation with some FBX files has issues - weird node added

texts:
Hi I'm trying to work load fbx files to my OpenGL Renderer using ASSIMP.

However, weird nodes that are not in the original fbx file are added whenever I load the file with the ASSIMP importer.

For example, this is part of the node hierarchy printed while loading the nodes in a DFS matter.

mixamorig:LeftForeArm_$AssimpFbx$_Translation
ㄴmixamorig:LeftForeArm_$AssimpFbx$_PreRotation
 ㄴmixamorig:LeftForeArm_$AssimpFbx$_Rotation
  ㄴmixamorig:LeftForeArm_$AssimpFbx$_Scaling
   ㄴmixamorig:LeftForeArm

However, according to the original file, there should only be mixamorig:LeftForeArm.

This fbx file might be weird since usually in the case of other fbx files, I can get the node's translation, rotation, scaling keyframes directly from aiNodeAnim using the node's name. I never saw a case where the keyframe itself become a node.

Is there a way to resolve this issue?


texts:
I'm looking for a way to read the memory of a N64, while the game is running, in real time.

I have a c# program which hooks into the memory of a running emulator and tracks SSB64 stats. I want to do the same thing with the physical N64. Currently it is possible to read the memory with a gameshark pro, however it's extremely slow, buggy, and not practical for what I am trying to accomplish.

Would it be possible to tap into the gameshark, or the N64 directly, to access the memory in real time?

Thanks!


texts: Intantiating objects across multiple container pages

texts:
I have this script here that generates buttons based on an array and a serialized grid transform
public void InitializeUI()
{
    LevelItem[] levelItemsArray = LevelSystemManager.Instance.LevelData.levelItemArray;
    for (int i = 0; i < levelItemsArray.Length; i++)
    {
        if (i % n == 0) // sets it to 15
        {
            LevelButtonScript levelButton = Instantiate(levelBtnPrefab, levelBtnGridHolder);
            levelButton.SetLevelButton(levelItemsArray[i], i, i == LevelSystemManager.Instance.LevelData.lastUnlockedLevel);
            var page = GameObject.FindObjectOfType<UI.Pagination.PagedRect>();
            page.AddPageUsingTemplate();
        }
    }
}

Now what I'm trying to do is make that array instantiate a new page (calling the page.AddPageUsingTemplate() function which is from another script) once for every 15 items of the array.
I have 75 levels and want to instantiate the buttons on a new game object which has a grid layout group, so it would be 15 buttons on each grid with 5 pages/grids in total.
I do indeed get 5 pages when I run this code, but since the transform is only set to the first one the buttons don't get placed on the other pages.
How can I place buttons after the first 15 on the following pages?


texts: Remove or change graphic of InputField target graphic

texts:
I am working on a game in Unity and I have to use an InputField but I would like it to not have a border. Currently it has a black border with a border radius that needs to go.

Through my initial searching, I came across this question and thought I found the answer to my problems.

However, I cannot seem to change or remove this TargetGraphic. If I use the button to the right to pick a new one and set it to none, it just reverts right back to the default graphic. It doesn't accept images and I even tried to set the target graphic programmatically but it didn't work.

This is the current look of the input, you can see the black border.

I also tried (without really hoping for much) to set it like so:

public InputField inputField;

void Start()
{
    inputField = GetComponent<InputField>();
    inputField.targetGraphic = null;
}


texts: Calculate distance from the centre to the edge of a cube in OpenGL

texts:
I'm trying to calculate the distance between a central point on a cube and anywhere on the surface of the cube, depending on the location of a second 3D point.

I have two vertices in 3D; Q and P. Q is the centre of the cube, P is a random point outside of the cube. I also have a known size of the cube, where distance across is d.

If I have the normalised vector of u,  which is Q->P, how do I calculate the distance from the centre to where it hits the surface of the cube? I could not find the answer to this anywhere,on the Stack Exchange.


texts: How can I apply an effect to a sound to simulate hearing it underwater?

texts:
I'm using XNA 4.0 and trying to reproduce an "underwater effect" for every sound played.

How can I apply an effect to a sound, and what effect should I use to make it sound like as if the player is underwater while hearing it?


texts:
I found a shader code to draw a filled Quadratic Bezier in

https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch25.html

How can I use something similar to draw a Bezier line that follows the same path?


texts: Best Practices for Random Enemy Animations?

texts: For various animations for NPCs (getting hit with projectiles, shooting, dying) I've been creating 2-4 animations each in blender before exporting. Should I be doing this inside Unity with Animation Controllers instead? Either way what would be the best practices to actually randomizing the animations?


texts: Should I do intersection testing in world or object space?

texts:
I'm adding basic ray casting and collision detection for my game, and also adding bounding volumes and collision meshes.

The ray is cast in world space and each mesh's node can track its world transformation. Considering I want to test for intersection between a ray and bounding volume and also bounding volume with other bounding volume, in what space should I perform the intersection test?

Scenarios that I have in mind:

Transform ray into object's local space, perform test, then inverse transform the resulted point.
Transform bounding volume into world space and perform it there, or should I always keep bounding volumes in world space?
Perform bounding/bounding test in world space or one of the objects?

Do things change much between static and dynamic collision regarding used spaces?


texts:
Over every entity system I see implemented in C++, or even in Java/C# (e.g. the Artemis framework). I see components not allocated via a new operator (or something similar, e.g. std::make_shared). For example:

entity.addComponent(new Position(32, 4, 5));
entity2.addComponent(new Position(5, 6, 7));
// those two position components that were just created
// may/may not be together in memory

// or even:
// how can you avoid using new here? (in the implementation)
entity.addComponent<Position>(32, 4, 5);

Doesn't this harm performance, as there would be cache misses (since new can allocate data anywhere from the heap)? How would you implement a system in such a way that the components of each type are allocated contiguously in memory, so you avoid cache misses? I mainly want to know how one would do so in C++.


texts:
The 2D library I have to work with has the following function to draw images to screen:

DrawImage(img, x, y, width, height)

Given this, I'm looking to show the entire image but then "zoom" in on a specific spot over time. I can do the over time part, but to get a zooming effect it's basically increasing the width and height, but to zoom on a specific spot on the image it seems like you have to also modify the x and y at the same time to bring that spot closer to the center of the screen. There is a relationship there that I'm not sure what it is to get the effect.

At some level it seems I should be able to write a function that zooms in on a point in the 2D image, but not sure how to go about that. Any suggestions?


texts:
Here is a video of the problem: https://www.youtube.com/watch?v=6vnDOB1Vk4o (this is the game I've been making for fun/practice).

You notice, in the beginning of the video, I walk off the map and into the black. When I do so the black covers the player.

I draw the player last in my code:

 // Draw the player & the world
public void draw(Graphics g, Graphics graphics, GameStateManager gsm) {
    glClearColor(0, 0, 0, 0);
    System.out.println(player.getPlayerX() + " - " + player.getPlayerY());
    glViewport(-(int)player.getPlayerX() + 350, -(int)player.getPlayerY() + 300, Display.getWidth(), Display.getHeight());
    worldGen.worldGenerator();
    // Draw the player to the screen (60, 60)
    player.draw();

}


texts: Unity GUIText not visible and not WYSIWYG

texts:
I have placed a Guitext in my hierarchy:

At first it was visible, now I can't see it when I run the game.

When it was visible:

When modifying the position on scene, the GUIText appears on one place,
but when I run the game it's somewhere else.

Why?


texts: How do I create a CPU read/write buffer in SlimDX (what are the legal combinations of Usage and CPUAccess flags)?

texts:
Currently, I create a vertex buffer in SlimDX like so:

SlimDX.Direct3D11.BufferDescription Description = new SlimDX.Direct3D11.BufferDescription();

Description.BindFlags = SlimDX.Direct3D11.BindFlags.VertexBuffer;
Description.CpuAccessFlags = SlimDX.Direct3D11.CpuAccessFlags.Write;
Description.OptionFlags = SlimDX.Direct3D11.ResourceOptionFlags.None;
Description.SizeInBytes = _BufferSize;
Description.StructureByteStride = 0;
Description.Usage = SlimDX.Direct3D11.ResourceUsage.Dynamic;

_Buffer = new SlimDX.Direct3D11.Buffer(Parent.Device, Description);

Which I can update:

DataBox box = _Parent.Context.MapSubresource(_Buffer, 0, _BufferSize, SlimDX.Direct3D11.MapMode.WriteDiscard, SlimDX.Direct3D11.MapFlags.None);
box.Data.Position = destStartPosition * _VertexStride;
/* Where T is my vertex structure type */
box.Data.WriteRange<T>(data);
_Parent.Context.UnmapSubresource(_Buffer, 0);

My first question is about the MapSubresource parameter MapMode.WriteDiscard: when the documentation says

  "the previous contents of the resource will be undefined"

, does that mean that if I only update part of the buffer, when it is unmapped the remainder could become anything? Or simply that if I read from the DataStream there is no guarantee what I am reading will be valid?

Second, if I specify MapMode.Write, SlimDX will throw an exception (E_INVALIDARG: An invalid parameter was passed to the returning function (-2147024809)). Why is this? The documentation says that I only need to have a writeable buffer for this to be valid, which I do, because that is the same requirement for WriteDiscard which I can pass successfully.

One last question, if I specify:

Description.CpuAccessFlags = (SlimDX.Direct3D11.CpuAccessFlags.Write | SlimDX.Direct3D11.CpuAccessFlags.Read);
Description.Usage = (SlimDX.Direct3D11.ResourceUsage.Dynamic | SlimDX.Direct3D11.ResourceUsage.Staging);

The same exception is thrown, but this is the only combination of flags I can see that would give me a ReadWrite buffer, how can I create one?


texts:
I got a couple of questions about game trademarks.

When should I submit a trademark for my game if I see that this is a serious project?
Where do I submit a trademark request? Does it have to be local (In my country)?
What do I need to be ready to submit a trademark request?

Thanks!


texts: Help Reading this Data in XML as a List (ContentReader)

texts:
Edit:

So i'm going to rephrase the question a bit, seeing as now i think know how i'm going to read this data. Looking at this example as my guide:
http://forums.create.msdn.com/forums/p/53404/323877.aspx

This is pretty much what i'm currently doing, and to be clear and show you guys:
http://pastebin.com/GxqQcBDg, that's how i'm loading my data.

So looking at that guys example from his post, he has a similar layout, his "Enemies" can equal my element "Animated_Tiles" and then his "Items" could be equal to my "Tile" objects, at least if you compare my data to his they look extremely similar, and yes i did update the Data as Richard Marskell - Drackir suggested,
But i'm wondering if i can have "Type" definitions like the guy has in his example, to show what i mean:

  <Animated_Tiles Type="System.Collections.Generic.List[Namespace.Class]">

Can that be done? Or is it only the "Asset" element that can have the Type definition?
Currently this is what my new data layout looks like:
http://pastebin.com/i42166ZQ

But currently, it seems to start reading it but i get this error by the first "Tile" Element. So the only difference i see between his & my layouts are that he has the Asset containing the List definition whereas i have "Animated_Tiles". So i'm unsure can any element can have the "Type=Blah" definition?


texts:
I do have a pretty wierd problem today.
As soon as I try to change my translation- or rotationmatrix for an object to something else than (0,0,0), the object starts to flicker (scaling works fine). It rapid and randomly switches between the spot it should be in and a crippled something.
I first thought that the problem would be z-fighting, but now Im pretty sure it isn't.

I have now clue at all what it could be, here are two screenshots of the two states the plant is switching between.

I already used PIX, but could find anything of use (Im not a very good debugger anyway)
I would appreciate any help, thanks a lot!

Important code:

D3DXMatrixIdentity(&World);
D3DXVECTOR3 rotaxisX = D3DXVECTOR3(1.0f, 0.0f, 0.0f);
D3DXVECTOR3 rotaxisY = D3DXVECTOR3(0.0f, 1.0f, 0.0f);
D3DXVECTOR3 rotaxisZ = D3DXVECTOR3(0.0f, 0.0f, 1.0f);

D3DXMATRIX temprot1, temprot2, temprot3;
D3DXMatrixRotationAxis(&temprot1, &rotaxisX, 0);
D3DXMatrixRotationAxis(&temprot2, &rotaxisY, 0);
D3DXMatrixRotationAxis(&temprot3, &rotaxisZ, 0);

Rotation = temprot1 *temprot2 * temprot3;

D3DXMatrixTranslation(&Translation, 0.0f, 10.0f, 0.0f);
D3DXMatrixScaling(&Scale, 0.02f, 0.02f, 0.02f);
//Set objs world space using the transformations
World = Scale * Rotation * Translation;

shader:

cbuffer cbPerObject
{
matrix worldMatrix;
matrix viewMatrix;
matrix projectionMatrix;
};

// Change the position vector to be 4 units for proper matrix calculations.
input.position.w = 1.0f;

// Calculate the position of the vertex against the world, view, and projection         matrices.
output.position = mul(input.position, worldMatrix);
output.position = mul(output.position, viewMatrix);
output.position = mul(output.position, projectionMatrix);

I figured the following:
When I delete the line that Transaltes the worldmatrix before sending it to the shader,
the object keeps looking like pic2. So it seems like the worldmatrix doesnt get transposed in some frames. Here is the drawingcode:

D3DXMatrixTranspose(&World, &World);
D3DXMatrixTranspose(&camView, &camView);
D3DXMatrixTranspose(&camProjection, &camProjection);

// Lock the constant buffer so it can be written to.
D3D11_MAPPED_SUBRESOURCE mappedResource;
d3d11DevCon->Map(matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);

cbPerObject* dataPtr;
dataPtr = (cbPerObject*)mappedResource.pData;

// Copy the matrices into the constant buffer.
dataPtr->worldMatrix = World;
dataPtr->viewMatrix = camView;
dataPtr->projectionMatrix = camProjection;
// Unlock the constant buffer.
d3d11DevCon->Unmap(matrixBuffer, 0);
d3d11DevCon->VSSetConstantBuffers(0, 1, &matrixBuffer);


texts:
I created a video that describes the problem since it very hard to explain it. Basically, using physi.js, I am applying random impulse on the object. In the video, at 0:17 the problem begins when the object lands not entirely correct. What am I doing wrong and how this problem can be avoided?
There is the js code:

$(function () {
Physijs.scripts.worker = physijsWorkerFile;
Physijs.scripts.ammo = ammoFile;

var renderer
    , scene
    , camera
    , cylinder
    , clock;

function init() {
    var container = $('#webgl-container');
    width = container.width();
    height = container.height();

    renderer = window.WebGLRenderingContext ? new THREE.WebGLRenderer({ alpha: true }) : new THREE.CanvasRenderer();
    renderer.setSize(width, height);
    container.append(renderer.domElement);

    scene = new Physijs.Scene();
    scene.setGravity(new THREE.Vector3(0, -50, 0));
    scene.addEventListener('update', function () {
        requestAnimationFrame(update);
        renderer.render(scene, camera);
    });

    camera = new THREE.PerspectiveCamera(35, width / height, 1, 1000);
    camera.position.z = 190;
    camera.position.y = 200;
    camera.rotation.x = degToRad(-32);
    scene.add(camera);

    clock = new THREE.Clock();

    initObjects();

    $('#applyImpulse').click(function () {
        var force = new THREE.Vector3(0, getRandomInt(20, 30), 0);
        var offset = new THREE.Vector3(getRandomInt(5, 10), 0, getRandomInt(10, 15));
        cylinder.applyImpulse(force, offset);
    });
}

function initObjects() {
    var surfaceMaterial = Physijs.createMaterial(
                new THREE.MeshBasicMaterial({ color: 0xFF0000, sides: THREE.DoubleSide })
                , 0
                , 0
            );
    var surface = new Physijs.BoxMesh(new THREE.BoxGeometry(200, 200, 4), surfaceMaterial, 0);
    surface.rotation.x = degToRad(90);
    scene.add(surface);
    cylinder = new Physijs.CylinderMesh(new THREE.CylinderGeometry(5, 5, 1, 32), Physijs.createMaterial(
               new THREE.MeshBasicMaterial({
                   color: 0x0000ff
               })
               , 0
               , 0
           ), 1.5);
    cylinder.position.y = 10;
    cylinder.addEventListener('collision', onCoinCollision);
    scene.add(cylinder);
}

function update() {
    var delta = clock.getDelta();
    scene.simulate(delta);
}

function run() {
    init();
    update();
}

function onCoinCollision(other_object, relative_velocity, relative_rotation, contact_normal) {

}

function degToRad(input) {
    return (input * (Math.PI / 180));
};

function getRandomCylinderXRotation() {
    return (degToRad(getRandomInt(0, 2) * 180));
}

function getRandomCylinderYRotation() {
    return (degToRad(getRandomInt(1, 360)));
}

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
};
window.onload = run; });


texts: How can I support component-to-object communication safely and with cache-friendly component storage?

texts:
I'm making a game that uses component-based game objects, and I am having a hard time implementing a way for each component to communicate with its game object.  Rather than explain everything at once, I will explain each part of relevant sample code:

class GameObjectManager {
    public:
        //Updates all the game objects
        void update(Time dt);

        //Sends a message to all game objects
        void sendMessage(Message m);

    private:
        //Vector of all the game objects
        std::vector<GameObject> gameObjects;

        //vectors of the different types of components
        std::vector<InputComponent> input;
        std::vector<PhysicsComponent> ai;
        ...
        std::vector<RenderComponent> render;
}

The GameObjectManager holds all the game objects and their components.  It is also responsible for updating the game objects.  It does this by updating the component vectors in a specific order.  I use vectors instead of arrays so that there is virtually no limit to the number of game objects that can exist at once.

class GameObject {
    public:
        //Sends a message to the components in this game object
        void sendMessage(Message m);

    private:
        //id to keep track of components in the manager
        const int id;

        //Pointers to components in the game object manager
        std::vector<Component*> components;
}

The GameObject class knows what its components are and can send messages to them.

class Component {
    public:
        //Receives messages and acts accordingly
        virtual void handleMessage(Message m) = 0;

        virtual void update(Time dt) = 0;

    protected:
        //Calls GameObject's sendMessage
        void sendMessageToObject(Message m);

        //Calls GameObjectManager's sendMessage
        void sendMessageToWorld(Message m);
}

The Component class is pure virtual so that classes for the different types of components can implement how to handle messages and update.  It also is able to send messages.

Now the problem arises on how the components can call the sendMessage functions in GameObject and GameObjectManager.  I came up with two possible solutions:

Give Component a pointer to its GameObject.

However, since the game objects are in a vector, the pointers could quickly become invalidated (The same could be said of the vector in GameObject, but hopefully the solution to this problem can also solve that one).  I could put the game objects in an array, but then I would have to pass in an arbitrary number for the size, which could easily be unnecessarily high and waste memory.

Give Component a pointer to the GameObjectManager.

However, I do not want components to be able to call the manager's update function.  I am the only person working on this project, but I do not want to get in the habit of writing potentially dangerous code.

How can I resolve this problem while keeping my code safe and cache friendly?


texts: The Direct3D9 debug runtime's debug output does not appear to be working correctly. I linked against d3dx9d.lib instead of d3dx9.lib and defined D3D_DEBUG_INFO and I also set the debug runtime on in the Direct3D control panel. However, there is still no D3D debug spew in the Visual Studio Output window. Any suggestions as to what I'm missing?


texts:
I am semi-experienced .NET developer who has just began working with Unity. I am trying to decide on how to make IoC work in Unity 4.X ( I have not yet tested anything), and I wonder what are the good ways of achieving it.

This post and its answers states that Ninject won't work with Unity, however it is old. Is it still true? If yes, what are other means of achieving IoC in Unity ?

Edit 1 : I am targeting mainly Windows platform. So I don't need platform interoperability, I just need it to work.


texts: How should I structure my classes to allow for multithreaded simulation?

texts:
In my game, there are plots of land with buildings (houses, resource centers). Buildings like houses have tenants, rooms, add-ons, et cetera, and there are several values that have to be simulated based on all these variables.

Now, I'd like to use AndEngine for the front end stuff, and create another thread to do the simulation calculations (perhaps also later include AI in this thread). This is so that one whole thread doesn't do all the work and cause problems such as blocking. This introduces the problem of concurrency and dependency.

The currency problem is my main UI thread and the calculation thread would both need to access all the simulation objects. So I have to make them thread-safe, but I don't know how to store and structure the simulation objects to enable that.

The dependency problem is that in order to calculate values, my calculations depend on other objects' values.

What would be the best way to link up my tenant object in the building with my calculations? Hard-code it into the tenant class? What is a good way to do "store" algorithms so they are easily tweaked?

A simple lazy way would be to bung everything into a class which holds all the object, such as plots of lands (who in turn hold the buildings, et cetera). This class would also hold game state such as the technology available to the user, object pools for things such as sprites. But this is a lazy and dangerous way, correct?

Edit:
I was looking at Dependency Injection, but how well does that cope with like a class that holds other objects? i.e, my plot of land, with a building, which has a tenant and a host of other values. DI looks like a pain in the bum with AndEngine as well.


texts:
I'm working on having a sticky conveyor belt, so that objects can also go around it. But my objects currently get stuck half way, as seen in the picture.

This is the movement code of the conveyor belt.

private void HandleCargo()
{
    var _speed = speed * Time.deltaTime;
    foreach (var cargo in _cargo)
    {
        var change = cargo.Key.transform.right * _speed;
        cargo.Key.transform.Translate(change);
    }
}

And the code taking care of the rotation to the surface.

private void Update()
{
    Debug.DrawRay(transform.position, -transform.up, Color.black);

    if (!Physics.Raycast(transform.position, -transform.up, out var hit, _distance)) return;
    var normal = hit.normal;

    transform.up -= (transform.up - hit.normal) * 0.05f;
}

If someone has pointers as to why this happens, that would be great. I kind of have an idea, since the transform right of the conveyor code is pointing inwards at this angles so the movement doesn't happen around the belt anymore, but I exhausted my attempts to fix it...

Edit: After DMGregory answer a new issue appeared. As soon as the cube starts to adjust to the spheric surface it is not exactly on the mesh anymore, which triggers my on collision exit code and stops movement on the object. I have some code that is supposed to stick the object to the belt, but that doesn't seem to work?

The sticky code

private void Update()
{
    Debug.DrawRay(transform.position, -transform.up, Color.black);

    if (!Physics.Raycast(transform.position, -transform.up, out var hit, _distance)) return;

    transform.rotation = Quaternion.FromToRotation(transform.up, hit.normal) * transform.rotation;
    transform.position = new Vector3(transform.position.x, hit.point.y + 0.5f, transform.position.z);
}


texts: How to Ignore Raycast for Boxcollider2D by layer or boolean?

texts:
How do I ignore raycasts for specific objects?  I want a filter, to ignore raycasts for some objects. As an example, when my player selects the ground, I do not want them to accidentally select bullets.

Is it possible to add boolean to the BoxCollider2D component, to identify raycast targets? I want to make it similar to the Image component.

My problem is that when several objects overlap, I need some of the objects to ignore the raycast.

I can't use Queries Hit Trigger or disable the collider component, because I need them to enter the OnCollisionEnter and OnTriggerEnter methods.

Here is my Update method:

void Update ()
{
    if (Input.GetMouseButtonDown(0))
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, Mathf.Infinity,
                1 « LayerMask.NameToLayer("Object"));

        if (hit)
        {
          Debug.Log(hit.collider.gameObject.name);
        }
    }
}


texts: OpenGL ES respecting alpha for background but not for objects

texts:
I have a problem with the alpha of my game, maybe it is solved in another post but as I am new in OpenGl and Game developemnt I dont understand most of the vocabulary and cant find a solution.

The problem is I have enemies with alpha and coins with alpha that works great, but when an enemy pass through the coin it take seem the background instead of the coin(same with shoots)

there is a image explaining it

There is the code to draw enemys and coins

public void drawEnemy(GL10 gl)
{
    gl.glFrontFace(GL10.GL_CCW); // Front face in counter-clockwise
                                    // orientation
    gl.glEnable(GL10.GL_CULL_FACE); // Enable cull face
    gl.glCullFace(GL10.GL_BACK); // Cull the back face (don't display)

    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
    gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); // Enable
                                                            // texture-coords-array
                                                            // (NEW)
    gl.glTexCoordPointer(3, GL10.GL_FLOAT, 0, texBuffer); // Define
                                                            // texture-coords
                                                            // buffer (NEW)

    gl.glEnable(GL10.GL_BLEND);
    gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);

    // front
    switch (type)
    {
        case 0:
            gl.glBindTexture(GL10.GL_TEXTURE_2D, TextureLoader.textureIDs[0]);
            break;
        case 1:
            gl.glBindTexture(GL10.GL_TEXTURE_2D, TextureLoader.naveEnemigaIDs[0]);
            break;
        case 2:
            gl.glBindTexture(GL10.GL_TEXTURE_2D, TextureLoader.naveEnemigaIDs2[0]);
            break;
    }

    gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);

    gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); // Disable
                                                            // texture-coords-array
                                                            // (NEW)
    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDisable(GL10.GL_CULL_FACE);
    gl.glDisable(GL10.GL_BLEND);
}

public void drawCoin(GL10 gl)
{
    gl.glFrontFace(GL10.GL_CCW); // Front face in counter-clockwise
                                    // orientation
    gl.glEnable(GL10.GL_CULL_FACE); // Enable cull face
    gl.glCullFace(GL10.GL_BACK); // Cull the back face (don't display)

    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
    gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); // Enable
                                                            // texture-coords-array
                                                            // (NEW)
    gl.glTexCoordPointer(3, GL10.GL_FLOAT, 0, texBuffer); // Define
                                                            // texture-coords
                                                            // buffer (NEW)

    gl.glEnable(GL10.GL_BLEND);
    gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);

    // front
    gl.glBindTexture(GL10.GL_TEXTURE_2D, TextureLoader.CointextureIDs[0]);
    gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);

    gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); // Disable
                                                            // texture-coords-array
                                                            // (NEW)
    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDisable(GL10.GL_CULL_FACE);
    gl.glDisable(GL10.GL_BLEND);
}


texts: Renderer.material assignment not working

texts:
I have a fairly simple question: I am trying to change an object's material via code with the line

rend.material = NewMat;

where rend is of type Renderer (MeshRenderer to be specific) and NewMat is of type Material. Both variables are public and assigned in the inspector and both are not null.

When I now try to assign the material, nothing happens. I don't event get any error. When I look into the inspector I can see that under Materials on my MeshRenderer the material doesn't even change. The line

Debug.Log(rend.material == NewMat);

outputs false.

What am I doing wrong?


texts: Integration my application with Facebook

texts:
So I recently developed this game which I would like to launch into Facebook but am having a hard time figuring out how on earth do I get the basics right. Like extracting user data i.e friends playing the game. Compile a global leader board and such. Also I was wondering if I want to keep a live update on who has got the highest score on the leader board, how do I go about doing that!?

Any suggestions and links to material explaining Facebook application integration for dummies will be a great help! Thanks...


texts: How to make buttons change in to another button when pressed in Game Maker

texts:
I am trying to make it so that when I click on a button in my games store that the current button changes to a new one right where the old one was and then has its own conditions.

ex. Press the button "Add 1/ps - $50", effects applied and now "Add 5/ps - $500" is now the button which will do the desired effect when clicked with conditions met.

How do I go about doing this?


texts:
I want be able to move my texture in GLSL I have set my texture to wrap S and wrap T but not sure why it wont move

my fragment shader looks like this at the moment

uniform sampler2D  n_mapTex;
uniform sampler2D  n_mapTex2;

varying mediump vec2  TexCoord;
varying mediump vec2  TexCoord2;

//This gets updated within the main code
uniform mediump float vTime;

void main()
{

    gl_FragColor =  texture2D(n_mapTex, vec2(TexCoord.x + vTime, TexCoord.y + vTime));
}

within my code I have a made a function to calculate FPS and I use the delta time of that function to pass into the fragment shader

void OGLESIntroducingPVRTools::timer(){
/*This method records to the time to start rendering a frame and hold that value
in another variable we then start to count again.  To get delta time we subtact
the current time from the previous time this will give us in milliseconds how
long it took for a frame to render.  We then divide this by 1000 this converts
it from ms per frame to FPS*/

FrameCount++;

p_Time = c_Time;
c_Time = PVRShellGetTime();

elapsed = c_Time / 1000.0f;
DT = ((float)(c_Time - p_Time)) / 1000.0f;

fCount += DT;

if(fCount >= 1.0f) //if time is over 1 second reset counters and recount
{
    FPS = FrameCount;
    FrameCount = 0;
    fCount = 0;
}

}

and in my renderscene method which updates I have this code to pass the value to the uniform within the fragment shader

glUniform1i(glGetUniformLocation(m_ShaderProgram.uiId, "vTime"), DT);


texts: Peculiar problem rendering specific triangles

texts:
I've encountered a strange problem with a peculiar [not quite] solution. This problem is that certain polygons aren't rendered unless I run 'fraps'. Needless to say, I would much rather my program to run without 3rd party programs. So I was wondering what part of my directx 11 code would be the cause of this.

Thanks in advance, please ask for code fragments if they're needed!


texts: How can I sample from a normal distribution in HLSL?

texts:
I need to 'distort' individual pixels inside a compute shader node of an Unreal material. Specifically, the pseudocode for this per-pixel operation looks as follows.

pol = // analyze the pixel values here to output either +1 or -1
C = (pol > 0) ? Cp : Cm;
sigma_C = (pol > 0) ? sigma_Cp : sigma_Cm;
if(sigma_C > 0)
{
    C += sampleNormalDistribution(0, sigma_C);   // zero-mean normal distribution
}

How can I sample from a normal distribution through HLSL to achieve this?


texts: What is a good practice for deciding when to use transforms instead of applying force?

texts:
I was making several games.  I don't understand when I should use addTorque instead of rotate.
AddForce instead of position

The latest game was a pinball game. I wasn't sure the best way to active the flippers.


texts: What's the best way to handle slopes for a platfomer game using Box2D

texts:
I would like to know if there is any known solution for handling the player's movement on slopes using Box2D engine.

I tried to do it using a circle as the player. Everything was fine until I tried to walk on slopes, the main problem is that due to gravity, the circle does not stop on the slope.

Please if somebody has tried this before I'll appreciate it. If you have a better solution without the physics engine would be fine for me too.

Thank you.


texts: I'd like to draw an arc between two specific angles. For example, "draw an angle between 0 and 90 degrees" and it will draw only that part of the circle and ignore the rest.


texts: Use Mathf.PingPong() from current position

texts:
I am trying to use Mathf.PingPong() from the current x, y and z coordinates and let it move along the x axis however now it moves too far and too fast. I know how I can speed down but what about the distance?

       transform.position = new Vector3(transform.position.x + Mathf.PingPong(Time.time * speed, 1), transform.position.y, transform.position.z);


texts: Use an external sprite or image file in flixel game in flashbuilder

texts:
Is there any way to use an external image/sprite file for the graphic of a FlxSprite instance?

Say I declare my player FlxSprite as follows:

player = new FlxSprite(FlxG.width/2 - 5);
player.makeGraphic(10,12,0xffaa1111);

How could I instead instantiate the FlxSprite using my own spritesheet or image?
I have seen others do it in the Flixel demos , and in the featured games.


texts:
I have a character controller.  I am primarily using FSM with the animations and blends.  However, I am running into some trouble with the fall.

I walk up to a ledge and walk off...sometimes I will make it off the edge and the falling animation will play...but sometimes I get stuck halfway off the edge.

Also, the falling animation completely disregards any motion vectors I had prior to transferring to the falling state.

Is there a way to transition to fall, retaining the current x-y velocities?

In an effort to fix this, I tried giving the attached rigidbody a force vector slightly up and in the direction of travel so that the character gets a little hop over the edge...but again, no luck.


texts:
I have a system of bunkers underground, and I need to fill all the free space where there are no buildings - with earth. Yes, I can manually add a ground texture to the plane, but I have procedural level generation.
I thought there might be some kind of filter on the camera that I don't know about. Or maybe there are some other solutions?


texts: How to make image bigger than the screen to be slideable in the screen in monogame for windows phone 8?

texts:
(Idk if my title is correct, because when I google it, there is no related result I guess)

I am not sure how to explain it correctly, but I am making a plain 2D, tile based, tactic game in windows phone 8 using monogame. I want to make my map is "slideable". With "slidable" I mean I can draw larger images (in total) than my screen and then slide it so I can view a certain area of the drawn images

Example : I have a screen which dimension is 1280x720. I have a 1500x1500px image, which consists of 15 tiles, which is 100x100px each, which each tiles is redrawn each times the "Draw" is called. If the image is larger than the screen, the displayed area will be trimmed and of course, making a 220x780px area that is unseenable. The only way to see all of it is through "sliding" the screen around, so I can see all the area.

My question is : How to make that happen? Because in default, the screen is unslideable and the image remains trimmed.

Sorry if my question and explanation is not clear enough. Clarify it as much as you like. Thank you.


texts: Unity - How to match camera bounds to width

texts:
While stretching camera bounds, changing width adds black offset while changing height stretches image.
How can I achieve opposite behavior and match the bounds to the width instead of height ?


texts: Splitting Pygame functionality between classes or modules?

texts:
I am attempting to make my pygame application more modular so that different functionalities are split up into different classes and modules.
I am having some trouble getting pygame to allow me to draw or load images in secondary classes when the display has been set and pygame.init() has been done in my main class.

I have typically used C# and XNA to accomplish this sort of behavior, but this time I need to use python.

How do I init Pygame in class1, then create an instance of class2 which loads and converts() images.

I have tried pygame.init() in class 2 but then it tells me no display mode has been set, when it has been set in class1. I am under the impression I do not want to create multiple Pygame displays as that gets problematic.

I am probably missing something pythonic and simple but I am not sure what. How do I create a Display class, init Python and then have other modules do my work like loading images, fonts etc.?

Here is the simplest version of what I am doing:

class1:
    def __init__(self):
        self.screen = pygame.display.set_mode((600,400))
        self.imageLoader = class2()

class2:
    def __init__(self):
        self.images = ['list of images']

    def load_images():
        self.images = os.listdir('./images/') #get all images in the images directory
        for img in self.images:
            #read all images in the directory and load them into pygame
            new_img = pygame.image.load(os.path.join('images', img)).convert()
            scale_img = pygame.transform.scale(new_img, (pygame.display.Info().current_w, pygame.display.Info().current_h))
            self.images.append(scale_img)

if __name__ == "__main__":
    c1 = class1()
    c1.imageLoader.load_images()

Of course when it tries to load an convert the images it tells me Pygame has not been initialized, so I throw in a pygame.init() in class2 (I have heard it is safe to init multiple times) and then the error goes to:

  pygame.error: No video mode has been set


texts: How does a single non-artistic programmer make a game?

texts:
I'd like to try my hand at making games. In making some simple ones, I realised I can't do art!

I've tried to find others to help: Most existing teams wouldn't want me because of my limited experience (I'm in high school) and I've been unable to find an available local artist with an appropriate skillset.

How do you guys do it? Do I have to wait until college to see if I like working in games? Is there a way to get free art so I can start messing around on my own? Or am I just having bad luck or looking in the wrong places for others interested?


texts: Stroring components in arrays (entity component system)

texts:
I'm looking for ways to improve my ECS and I've seen many people suggest storing components in arrays. This seems great, considering fast access for a component using entity id and more importantly, fast iteration over elements of array (because systems do this all the time) and fewer cache misses than if I store components in Entity or use:

std::map<int,std::shared_ptr<Component>> components // where int is a component id

But I have some questions about this approach.

1) Do I have to create array for each component? Something like:

PositionComponent positionComponents[MAX_OBJECTS];
HealthComponent healthComponents[MAX_OBJECTS];
...

Or is there a better way to store different components contiguously in memory?

2) How can I get components using entity id if I do this?

I'd like to implement some function like this:

template <class T>
T* getComponent(int entityId) const {
    ... // ??
}

so I can then use it like this:

PositionComponent* pc = getComponent<PositionComponent>(entityId);


texts: Box2dMapObjectParser isometric map - bodies have wrong position and size

texts:
I'm using Box2dMapObjectParser to load Tiled objects layer onto my IsometricTiledMapRenderer'ed TiledMap.
It works OK with a UnitScale of 1 but the position is wrong and some shapes have weird rotation and size.

Map in Tiled:

Map in game:

I've found another similar question but the answer is unfortunately far from being clear, at least to me.

Relevant code:

mParser.load(mWorld, mMap);
mRenderer = new IsometricTiledMapRenderer(mMap, mParser.getUnitScale());

Notice the 'Ellipse' is not drawn at all, the Rectangle is way off and Polygons/Polylines are just not positioned right.

Did anyone experience the same issue and/or have any idea how to fix this?


texts: Diagonal Movement with Pygame Rect Class

texts:
I have been using pygame and have been struggling to understand how to implement vectors and the pygame rect class to make an image move diagonally on the screen at the correct speed.I know it must be normalised else it moves at 2x the correct speed.I don't know how to implement vectors with pygame.rect.x and pygame.rect.y

This is the code I have so far

class Player(pygame.sprite.Sprite):

def __init__(self, location, *groups):
    super(Player, self).__init__(*groups)
    self.image = pygame.image.load('player.png')
    self.rect = pygame.rect.Rect(location, self.image.get_size())

    # movement in the X direction; positive is right, negative is left
    self.direction = 1
def update(self, dt, game):

    # take a copy of the current position of the player before movement for
    # use in movement collision response
    last = self.rect.copy()
    clock = pygame.time.Clock()

    # handle the player movement keys
    key = pygame.key.get_pressed()
    if key[pygame.K_LEFT]:
        self.rect.x -= 300 * dt
        self.direction = -1
    if key[pygame.K_RIGHT]:
        self.rect.x += 300 * dt
        self.direction = 1
    if key[pygame.K_UP]:
        self.rect.y -= 300 * dt
    if key[pygame.K_DOWN]:
        self.rect.y += 300 * dt

Thanks


texts: Where do I begin if I want to write a C++ 2d game?

texts:
I am a C# web developer and I want to expand my skillset and have some fun while doing it. I know some of the basics of C++ and I would love to write a simple 2d game/game engine for myself using C++. What other libraries or SDKs do I need and where would I find some tutorials and informational resources to move forward?

I've already looked into XNA with C#. There are a lot of resources for that but I would rather use non Microsoft products. The point of this is to have a little fun while becoming a better rounded programmer.

Please note that I'm not asking for the best place to start. I'm just asking for a place to start.

Thanks for any help!


texts: Difference between integral and accumulator?

texts:
I'm trying to build a bouncing-ball effect, and a newbie to calculus things...

For the ball-drop, it's straightforward - since there's no initial velocity and acceleration is constant.

For the bounce-up, it seems that what I want to do is integrate the velocity changes over time (since there's some transfer of energy upon impact, and that drives the ball upwards with a sortof fade-off as it fights against gravity?)

This leads me to some questions, one generic and one specific (with a more detailed followup):

Is this correct- that I need to use integration and not just a straight kinematic equation for the bounce-up?
I'm not quite sure about the difference between integration and accumulation. Ideally I would like to have a function y = f(t) where various other properties are known such as the initial velocity upon impact, but I do not want to accumulate anything every tick. I.e. it'd be nice to just have a pure function that pre-loads all the info it needs on impact, and then can be run with any time as an input. Can someone please explain the difference between integration and accumulation in light of this?
A bit more specifically, it seems like maybe there are rules of integration that allow for solving at any t such as the "power rule", but then integrators like Euler/Verlet operate more like accumulators. This is confusing and speaks to the above point.

Thanks!


texts: Does a basic game engine prototyping tool exist, for common game types?

texts:
There are a lot of classic game engines out there (Real Time Strategy, Turn Based, etc), of which you can find countless variations. All of them have a basic starting point which involves units, buildings that produce units, unit/building parameters like health, damage, etc, a map canvas. These can be simulated at a very basic level, no graphics, no animations.

I want to build a Tower Defense type of game, and it would be great if i could build a very basic prototype just to simulate parameters like health, damage, speed, range, etc.

Does such a tool exist?


texts: How to deal with standing/walking models?

texts:
I'm developing a game using bullet for the physics logic, but rendering using my own isometric algorithm (sprites). I'm currently dealing with the issue of how the physics object of the player would work when they're standing and walking. Standing is easy enough, the model basically just looks like a rounded rectangle. Handling walking is more difficult.

I have a couple of options on how I can handle walking.

Keep the object the same. However, problems arise when the sprite the player sees doesn't match the player's movement (e.g. the player's leg might appear to go 'into' a wall).
Alternate between two objects, one standing, one with legs spread as far apart as they would when walking. So, at a certain point in the walking animation, the object would switch to the latter. However, if the player walks into a wall, they would constantly oscillate against the wall.
Same as option 2 but have the object where the legs are spread apart active whenever the player walks. This removes the problem with option 2 (as the player would never touch the wall whilst standing), but this is a disadvantage in itself; the player would not be able to climb up walls (assuming I use a system where the player has to be touching said wall), for example.

I'm pretty stuck as to what other options are available, any ideas would be great.