texts: Camera relative movement is pushing into/off the ground instead of parallel

texts:
I'm building upon roll a ball tutorial in unity, and I have managed to rotate the camera around the ball just fine with the code below. But there's one problem.

In this code, when I add force to the ball, with W for example, the force will be added in the exact direction the camera is looking at the ball, meaning pushing the ball onto the ground, increasing friction and lowering speed. And if I press S the force will push the ball to the air, lowering friction and making the ball move fast.

So my question is, how can I achieve rotation without this issue?

Code for Camera (CameraController):

public GameObject Player;
private Vector3 offset;
public float cameraSpeed;
private Vector3 point;
static public Vector3 finalMovement;

void Start () {
    offset = transform.position - Player.transform.position;

    point = Player.transform.position;
    transform.LookAt(point);
}

void LateUpdate()
{
    point = Player.transform.position;

    offset = Quaternion.AngleAxis(Input.GetAxis("Mouse X") * cameraSpeed, Vector3.up) * offset;
    transform.position = point + offset;
    transform.LookAt(point);
}

Vector3 movement;
void FixedUpdate()
{
    movement = new Vector3();
    float moveHorizontal = Input.GetAxis("Horizontal");
    float moveVertical = Input.GetAxis("Vertical");
    movement = new Vector3(moveHorizontal, 0f, moveVertical);

    finalMovement = GetComponent<Camera>().transform.TransformDirection(movement);
}

Code for ball:

public float speed;
void FixedUpdate()
{
    rb.AddForce((CameraController.finalMovement) * speed);
}


texts: Import and run LibGDX project in IntelliJ

texts:
I followed this guide to import a demos project, but when I set the class path of the module to the desktop, then click on the button of the main class field and select the DesktopLauncher class, there is no desktop module in the list. I can't run the imported project, because I have to create a custom run configuration named "Desktop" with the module "desktop" and the main class "DesktopLauncher".

How do I import and run a LibGDX project in IntelliJ?


texts:
I'm trying to port an old perfectly functioning ray casting implementation from my lwjgl project (FF pipeline) to a new project using JOGL and shaders.  My problem is that my ray no longer intersects the model at the mouse location although the ray always passes through the mouse location (see image).  Further to this, as soon as I apply any transformation to the model - rotation, movement along x,y or z - the ray is completely off and doesn't pass through the mouse location in any case.  Would anyone know why this would be happening?  As far as I can tell the code is doing exactly what the old project did.  I am currently using FloatUtil.mapWinToRay() although I have also tried FloatUtil.mapWinToObjCoords() with the same results.

Function that creates the testing ray:
I use nearVector and farVector to draw the ray.

public Ray getPickingRay(float[] modelMatrix,
                                float[] projMatrix,
                                int[] viewport,
                                float winx,
                                float winy
                            ) {

    // first the near vector
    float[] mat4Tmp1 = new float[16];
    float[] mat4Tmp2 = new float[16];
    float[] vec4Tmp2 = new float[4];
    Ray ray = new Ray();
    FloatUtil.mapWinToRay(winx, winy, 0, 1,
            modelMatrix, 0,
            projMatrix, 0,
            viewport, 0,
            ray,
            mat4Tmp1, mat4Tmp2, vec4Tmp2);

    nearVector[0] = ray.orig[0];
    nearVector[1] = ray.orig[1];
    nearVector[2] = ray.orig[2];
    farVector[0] = ray.dir[0] * 100;
    farVector[1] = ray.dir[1] * 100;
    farVector[2] = ray.dir[2] * 100;

    return ray;
}

Function that updates the ray position:

private void updateLineData(GL4 gl) throws Exception{

   //container for two ray vertices
   float[] all = {0,0,0,0,0,0};

  //apply same translation to ray as is applied to entire model.
  view3 = translate(view2, transX, transY, transZ);
  //pass the matrix to the line shader
  shaderLine.setUniform(iMVPLine, multiply(projection,  view3),
         Shade.MatDataType.MAT4);

  if (updatePos == true){
    updatePos = false;

    int[] viewport = {0,0,screenWidth,screenHeight};
    float[] dest = new float[3];

     Ray ray = pick.getPickingRay(view3,
            projection,
             viewport,
            mx, my);

    float[] front = pick.nearVector;
    float[] back = pick.farVector;

    all[0] = front[0];
    all[1] = -front[1];
    all[2] = -front[2];
    all[3] = back[0];
    all[4] = -back[1];
    all[5] = -back[2];
    whole.updateLine(gl, all);
  }

}

Update the line data buffer:

  public void updateLine(GL4 gl, float[] pos)
  {

      for (int i=0;i<pos.length; i++){
          vertLineBuffer[i] = pos[i];
      }
      //populate the color buffer
      FloatBuffer fbData = Buffers.newDirectFloatBuffer(vertLineBuffer);

      gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, vboLineHandles[VERTICES_LINE_IDX]);
      gl.glBufferSubData(GL4.GL_ARRAY_BUFFER, 0, fbData.capacity() * 4, fbData);
      fbData.clear(); //don't need this anymore

  }

A final note/clue is that as I click closer to the centre of the screen the intersection point between the ray and the model gets closer to the mousepointer.  It is almost as if the ray always wants to point to 0,0,0.  My expectation would be that I wouldn't be able to see the ray when it is drawn as it would be following my line of sight thru the model.  Then when I translate the view I would be able to see it as I would be looking at a slight angle to the new ray.  Currently when the ray draws I can see it right away as it draws between near the centre of the screen and out in the direction of the mousepointer.  Any help/hints or tips would be greatly appreciated.


texts:
I need to draw a flow dynamically based on some user choices. In that flow I want to draw the choices (blue circles with number) and the directions of that choices (line and arrow). For example: node 1 to node 2.

JSFiddle Example

To draw the direction I draw a arrow in the end of the line but I can't make the arrow rotate around itself.

JS code

$(document).ready(function () {
    drawOnCanvas();
});

function drawOnCanvas() {
    var canvas = document.getElementById('myCanvas');

    if (canvas.getContext) {
        var ctx = canvas.getContext("2d");

        var circle1 = {
            x: 75,
            y: 75,
            r: 15
        };

        var circle2 = {
            x: 225,
            y: 50,
            r: 15
        };

        var arrow =
            {
                h: 5,
                w: 10
            };

        drawCircle(ctx, circle1, "1");
        drawCircle(ctx, circle2, "2");

        var ptCircle1 = getPointOnCircle(circle1.r, circle1, circle2);
        var ptCircle2 = getPointOnCircle(circle2.r, circle2, circle1);
        var ptArrow = getPointOnCircle(circle2.r + arrow.w, circle2, circle1);

        drawLine(ctx, ptCircle1, ptCircle2);
        drawArrow(ctx, arrow, ptArrow, ptCircle2);
    }
}

function drawArrow(canvasContext, arrow, ptArrow, endPt) {

    var angleInDegrees = getAngleBetweenPoints(ptArrow, endPt);

    canvasContext.beginPath();
    // first save the untranslated/unrotated context
    canvasContext.save();

    // move the rotation point to the center of the rect
    canvasContext.translate(ptArrow.x, ptArrow.y);
    // rotate the rect
    canvasContext.rotate(angleInDegrees);

    canvasContext.moveTo(endPt.x, endPt.y);
    canvasContext.lineTo(endPt.x - arrow.w, endPt.y + arrow.h);
    canvasContext.lineTo(endPt.x - arrow.w, endPt.y - arrow.h);
    canvasContext.closePath();
    canvasContext.fillStyle = "rgb(72,72,72)";
    canvasContext.stroke();
    canvasContext.fill();

    // restore the context to its untranslated/unrotated state
    canvasContext.restore();
}

function drawCircle(canvasContext, circle, text) {
    canvasContext.beginPath(); //começa ou reinicia o desenho de algo
    canvasContext.fillStyle = "rgb(43,166,203)";
    canvasContext.arc(circle.x, circle.y, circle.r, 0, 2 * Math.PI, false); //cria arcos
    canvasContext.fill(); //atribui estilos

    drawText(canvasContext, circle, text);
}

function drawText(canvasContext, circle, text) {
    canvasContext.font = '8pt Calibri';
    canvasContext.fillStyle = 'white';
    canvasContext.textAlign = 'center';
    canvasContext.fillText(text, circle.x, circle.y + 3);
}

function drawLine(canvasContext, startPt, endPt) {
    canvasContext.moveTo(startPt.x, startPt.y);
    canvasContext.lineTo(endPt.x, endPt.y);
    canvasContext.stroke();
}

function getPointOnCircle(radius, originPt, endPt) {
    var angleInDegrees = getAngleBetweenPoints(originPt, endPt);

    // Convert from degrees to radians via multiplication by PI/180
    var x = radius * Math.cos(angleInDegrees * Math.PI / 180) + originPt.x;
    var y = radius * Math.sin(angleInDegrees * Math.PI / 180) + originPt.y;

    return { x: x, y: y };
}

function getAngleBetweenPoints(originPt, endPt) {
    var interPt = { x: endPt.x - originPt.x,
        y: endPt.y - originPt.y
    };

    return Math.atan2(interPt.y, interPt.x) * 180 / Math.PI;
}

I think the problem is in drawArrow() method in the lines

canvasContext.translate(ptArrow.x, ptArrow.y);

canvasContext.rotate(angleInDegrees);

I already tried every possible values for the rotation and the translation but arrow still don't rotate properly around itself. Can anyone help me?


texts:
I've got few questions without responses about my game development, can you help me? Here is the questions:

In my game when a large object appear on the screen, the GPU go to his limits, my framerate become very slow. How can I handle that? (I'm working on mobile). (
Currently, I'm sorting object from back to front)
I've read some stuff about batching (How to draw efficiently large number of objects with alpha blending?), how can I handle batching when my game need to draw my scene from back to front with alpha blending?
What is faster: Add a condition to test pixel transparency in fragment shader or enable Alpha blending? (I've got colors around my sprites without alpha blending or condition)

Thanks!


texts: Unity inspector script - making it save the global variables for what it's creating

texts:
I have a script which initialises a bunch of child gameObject(s). I wanted all of this to happen outside of the game, so I created an inspector script which has a button which triggers the method which does all the work. The problem is that when something is initialised it's global variables aren't saved for runtime this even goes so far that when I call a method outside of the one that the inspector script calls it forgets the parameters that were passed in (so they appear as null).

I've tried adding the [Serializable] attribute to the scripts but it doesn't change anything. What do I have to do?


texts: How do I find the angle between two 3D angles represented in this form?

texts:
I have two 3D angles, represented by [a1,a2] [a1,a2] where the a2 is < 180. My coordinates are represented as [X,Y,Z], where X,Y,Z are 64 bit ints (longs in my lang). My direction angles are represented as (Angle1, Angle2) where Angle1 is 360 degrees along the X/Y plane, and Angle2 is 180 degrees along the Z axis.

In this case, I know for a fact that both angles were calculated from a single starting point, so there should be a single angle between them.  However, the math eludes me.  I sure would appreciate some help.

I've read the stuff on calculating the angle between two vectors, which is great, but for me would involve multiplying two longs together, which is
1. not practical, and
2. shouldn't be necessary.

My goal is to determine whether obj1 is moving generally towards obj2.  One of the angles is the direction of movement of obj1, and the other is the direction from obj1 to obj2. Can I get there from here?


texts:
I'm making a 4x space game. I have a procedurally generated galaxy with planets in 3D space. The view is above the planet plane at -45 dec y-up i.e 45 deg isometric. I procedurally generate the planet surfaces on a hex grid which can be viewed 2D / 2.5D when clicking on the planets, ala GalCiv etc by placing meshes for mountains, seas, forest and so on on the hex grid.

For realism, I'd like the textures of the planets when viewed from space to (at least roughly) mirror the view you get in the surface view. I'm struggling to think how this might be achieved in Unity.

I figure I could create a render texture after generating the planet's surface and store it on the users HD. This has a few problems though - taking up HD space and not mapping well to a sphere (unless I always make the poles a uniform colour, which doesn't look good as the rest of the surface is quite highly detailed).

Another idea would be to create many generic textures for the space view of roughly each type of planet generated (blue / green / large continent / archipelago etc) and select a texture which most closely fits the procedurally generated map at run time. As long as the same texture isn't used for planets close to each other and the user doesn't compare the 3D view with the 2D view to closely then hopefully they won't notice!

So, any other ideas of how this might be achieved? I'm not looking for code, just a brainstorm of how I might get a procedural 2D map to be represented on a 3D sphere, or at least create a convincing illusion.


texts: Adding false if statement to pixel shader produces a lag

texts:
One of lines in pixel shader produces a lag (lower fps). I can't understand why.

if (TextureEnabled)
    color *= texDiffuse.Sample(texDiffuseSam, input.UV);

Interesting fact is: TextureEnabled is always false. I have already checked.

// they are null
Texture2D texDiffuse : register(t0);
sampler texDiffuseSam : register(s0);

Is it possible, or i have mistake in other place(?), or is it HLSL so slow?


texts:
I'm trying to calculate deltaTime, but it's not correct.

What's wrong in my code?

//declared outside
private long timeSinceStart = System.nanoTime() / 1000;
private long oldTimeSinceStart = 0;
public static long deltaTime = 1;

while(running)
  timeSinceStart = System.nanoTime() / 1000;
  deltaTime = timeSinceStart - oldTimeSinceStart;
  oldTimeSinceStart = timeSinceStart;


texts: Making abilities (Programming FFG's boardgame Descent)

texts:
I am trying to program Fantasy Flights boardgame "Descent - Journeys in the Dark", but I have hit a wall when dealing with implementing abilities, which are a crucial part of the game.

Abilities are used alot of different places, but are similar most of the time.

For a hero an ability could be:
At the start of his turn, Varikas the Dead recovers 1 fatigue

I have written monsters with abilities like this: Damage 2/Command

Equipment/Treasures look like this: When(TakingDamage):Exhaust&CancelDamage:2, When(MakingAttack(Type=Magic)):Gain:Surge 1 and When(Equipped(State=StartOfTurn))):Discard&Hero.Healt=Hero.HealthMax&Hero.Fatigue=Hero.FatigueMax

My idea is to maybe have some ability factory that will build an ability by reading the string formats, but I do not know how to implement them as a whole, and I am therefor turning to you.

Do any of you have any experience doing stuff like this, maybe when making D&D, Magic the Gathering, or maybe Descent?

Kind Regards
Thediabloman


texts:
I am looking for definitive information on Shaderlab's API and the Cg language. The documentation I have found so far has been by way of example programs rather than a definition of APIs. Also, searching for a specific API term such as Sampler2D didn't turn up anything definitive.

What reference documentation is available or possibly documentation of precursors to Shaderlab and Cg?


texts: What makes scaling pixel art different than other images?

texts:
Recently I was coaching a developer who's new to making pixel art games, and realized there's some "conventional wisdom" around scaling pixel art that's not obvious to a newcomer, and might not be well documented. So, here's an attempt to fix that....

I've heard I should only scale pixel art by 200%, 300% etc. not in-between sizes like 120%

Why is that? Shouldn't scaling "just work" the way it does with other images?
What if I really need to make my character just a fraction larger or smaller to get the right gameplay or look? How do I fix this?

I'm told it's "bad" to use pixel art at different scales in one game - why?

For example, if I scaled up my character so each sprite texel is 4x4 screen pixels, while my background art is scaled up so each sprite texel is 6x6 screen pixels. Isn't a pixel a pixel at the end of the day?


texts: StateMachineBehaviour.OnStateExit is called before StateMachineBehaviour.OnStateEntered is called

texts:
When I start my game I get null-references in my OnStateExit of objects that are initialized in the OnStateEntered. After this it goes smooth, so it only occurs at startup before any conditions for statechanges are met.

How come? My understanding is that OnStateExit is always preceded by OnStateEntered.

My StateBehaviour

public class DuckStateBehaviour : BaseStateBehaviour {

    override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        base.OnStateEnter(animator, stateInfo, layerIndex);
        mMovement.BeginDuck();
    }

    public override void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        if (mMovement != null) mMovement.EndDuck();
        base.OnStateExit(animator, stateInfo, layerIndex);
    }
}

public class BaseStateBehaviour : StateMachineBehaviour {

    protected Transform mTransform = null;
    protected Rigidbody2D mRigidBody = null;
    protected IMovement mMovement = null;

    public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        mTransform = animator.gameObject.GetComponent<Transform>();
        mRigidBody = animator.gameObject.GetComponent<Rigidbody2D>();
        mMovement = animator.gameObject.GetComponent<IMovement>();

        Debug.Assert(mTransform != null);
        Debug.Assert(mRigidBody != null);
        Debug.Assert(mMovement != null);
    }

}


texts: Unreal: Get horizontal angle of velocity-looking direction

texts:
I want to calculate the relative angle of the speed in relation to the direction of view:

For this I do have the "Get Control Rotation" and the "Get Velocity" of the "Pawn"

I am stuck:

Yeah I stole the original image from: https://forums.unrealengine.com/development-discussion/blueprint-visual-scripting/74282-get-angle-offset-from-forward-vector-need-help

But it explains exactly how the "angle" should be.

Positive values if the velocity is "moving to the right" relative to the looking direction and negative values if "moving left".

EDIT:

Using arctan I can compute the negative and positive angle based on the horizontal components of the vector. As I am only interested in horizontal movement and the horizontal "direction" in which my pawn is facing.

As the "forward vector" of the rotator uses a "z" component when looking up/down I figured I could use the "right vector" and rotate it -90 degress (to the left or better say front) around the "z" axis, because it never get's a "z" value.

Unfortunetly if the velocity vector has a "z" value when moving sidewards up or down the hill the angle is +270 instead of -90 and reverse:


texts:
I'm developing a real time strategy game for a computer science course I'm taking. One of the harder aspects of it seems to be client-server networking and synchronization. I've read up on this topic (including 1500 archers), but I've decided to take a client-server approach as opposed to other models (over LAN, for instance).

This real time strategy game comes with some problems. Thankfully, every action the player takes is deterministic. However, there are events that happen on scheduled intervals. For instance, the game is made up of tiles, and when a player takes a tile, the 'energy level', a value on that tile, should grow by one every second after it's taken. This is a very quick explanation that should justify my use case.

Right now I'm doing thin clients, which just send packets to the server and wait for a response. However, there are several problems.

When games between players develop into endgame, there are often over 50 events per second (due to the scheduled events, explained earlier, piling up), and synchronization errors start to show up then. My biggest problem is that even a small deviation in state between clients could mean different decisions the clients take, which snowball into entirely separate games. Another problem (which isn't as important right now) is that there is latency and one has to wait a few milliseconds, even seconds after they make their move to see the result.

I'm wondering what strategies and algorithms I could use to make this easier, faster, and more enjoyable for the end-user. This is especially interesting given the high amount of events per second, along with several players per game.

TL;DR making an RTS with >50 events per second, how do I synchronize clients?


texts: Scaling a sphere to give identical result, regardless of rotation

texts:
how can I maintain a consistent scaling of a sphere regardless of the rotation of the model? For example, take the following (scaled) sphere:

In this image, we start with a sphere, looking at it directly through the Z-azis. The sphere is scaled by 0.7x on the Y (up/down) axis, giving it a 'squashed' appearance.

A 3D vector that describes the scaling of this sphere is [1.0, 0.7, 1.0]. The red dot indicates an arbitrarily chosen point on the surface of the sphere that we will mark as the 'top'.

Now, after the sphere rotates 90 degrees through the Z-axis, the same scaling coefficients [1.0, 0.7, 1.0] when applied will produce a result like this:

My question is as follows:

Given a rotation quaternion Q that represents the rotation of the sphere, how can I use Q to correctly alter the scaling coefficients vector in order to produce a result like this instead:

Notice that the eventual 'oriented shape' of the sphere is the same as in the first image, even though a 90-degree-through-Z rotation has been applied. In this instance, a corrected scaling coefficient vector would be something like [0.7, 1.0, 1.0].

I've tried simply multiplying the scaling coefficients vector by Q but this gives an incorrect result. This is actually trivial to see if you imagine rotating [1.0, 1.0, 1.0] by 45 degrees through any angle. The answer should always remain as [1.0, 1.0, 1.0] but it does not.


texts: c - Starting an user defined function after the current one ends

texts:
The game I am creating displays a menu before starting, the user may select to start the game, or do some stuff. When the user selects an option, I need to call another function which actually does the selected option (start the game, configuration, etc...), the problem is that since I called that function from the menu function all the variables from the menu stay in memory. So I want to finish the menu function and remove all of its contents from memory and then start the function corresponding to the option selected, if the user goes back to the menu then load everything again and unload it when its finished. The problem is I there is no way (that I'm aware of) to tell the menu function which function to call after it finishes.

I though about starting the function corresponding to the option selected in another thread while the menu function finishes (what could possibly go wrong...) like this:

int menu()
{
    Load_menu_stuff_to_memory();

    int quit = 1;
    while(quit)
    {
        if(option_a_selected)
        {
            //the new function will be started in a new thread while the menu one finishes
            quit = 0;
            start_option_a_in_new_thread();
        }else if(option_b_selected)
        {
            //the new function will be started in a new thread while the menu one finishes
            quit = 0;
            start_option_b_in_new_thread();
        }
    }

    Deallocate_menu_stuff();
}

But I'm not sure if the new thread will end when the menu function does or be left like in the limbo or something.

Also I'm not sure if when the menu function ends the program will reach end of main (not to be confused with menu)

So: will my method work?

if not:

how can I call a random function but only after the caller function has finished?


texts: The SFML equivalent of polling to see if a key has been released?

texts:
I'm testing out SFML by trying to make a square move with lerp velocity. The desired result was that when, let's say, D was pushed, the square would accelerate smoothly from velocity.x = 0 to velocity.x = maxVel (20). When
the D key is let go, it decelerates back to 0. The problem is, I can't get it to decelerate! When I let go of D, it keeps on going!

Player.cpp (only relevant code shown):

#include "Player.h"

void Player::input() {
    using Key = sf::Keyboard::Key;
    auto keyDown = [](sf::Keyboard::Key k) {
        return sf::Keyboard::isKeyPressed(k);
        };

    if (keyDown(Key::A)) {

        velocityGoal.x -= 3;
    }
    else if (keyDown(Key::D)) {
        velocityGoal.x += 3;
    }
    if(keyDown(Key::A) != true){
        velocity.x = 0;
    }
    else if (keyDown(Key::D) != true) {
        velocity.x = 0;
    }
    if (keyDown(Key::F)) {
        velocity = velocity; //just a breakpoint cue. Move along.
    }
}
void Player::update(float dt) {

    //interpolating velocity
    velocity.x = Math::interpolate(velocityGoal.x, velocity.x, dt);
    velocity.y = Math::interpolate(velocityGoal.y, velocity.y, dt);

        //capping out speeeeed
    if (velocityGoal.x > maxVel) {
        velocityGoal.x = maxVel;
    }
    if (velocityGoal.x < -maxVel) {
        velocityGoal.x = -maxVel;
    }

    //adding velocity to the player's position
    newPos += velocity;
    rect.setPosition(newPos);
}

void Player::draw(sf::RenderTarget& target) {
    target.draw(rect);
}

My interpolation function:

float Math::interpolate(float goal, float current, float deltaTime){
float diff = goal - current;
if (diff > deltaTime) {
    return current + deltaTime;
}
else if (diff < -deltaTime) {
    return current - deltaTime;
}

return goal;
}

It appears to be a problem with the if statements that set velocity.x to 0. SFML doesn't have anything like keyJustPressed or keyUp, so I just polled to see if keyDown(D) was not true. This evidently is not the right thing to do in this situation.

Does anyone know the right way to do this, or if there is some way I can track a key being released?


texts:
I'm following this tutorial. I cannot get even simple animations to work. Here's a very simple case that was supposed to work but did not:

Add an animator component to the 'player' prefab
Create an animator controller and drag it to the corresponding field in the player animator component.
Open the 'animator' tab (right click on animator controller -> open), and drag an animation clip. This automatically becomes the default state.
Click play. Nothing happens. In the animator tab I can see a blue progress bar in the 'default' state (the only animation I dragged to the state machine). But the game screen shows no animation.

The player prefab inspector:

The very simple state machine

This is driving me nuts.


texts: How do you extract a Vector3 positions only from a world matrix in an array of positions (from Kinect)

texts:
've just started building a physical camera class for the depth data you get from a Kinect. I have a Vector3 array of [imageWidth, imageHeight] describing the LOCAL positions I get in from the kinect (once I project them back at the FOV of the camera lens etc). I then translate, scale and rotate the whole virtual kinect camera in space.

What I'm looking to do is to extract back again the positions of the kinect camera input but in WORLD space, not LOCAL space (i.e. it's gone through the translation, scale and rotation and gives me a Vector3 for each value of the kinect in WORLD space).

Any ideas?


texts: What is a good tool for producing animated sprites?

texts: Has anyone come across a software package that allows you to build animations in a similar way to how you can in Flash (i.e. using techniques such as tweens & bones & easings, etc) and then have the result exported as a sprite sheet?


texts: Convert integer to float while also dividing down the scale, without data loss

texts:
I'm working on a game, and my intent is to avoid use of floating point for unit positions. To that end, I'm using 32-bit integers for all positions, with a millimeter scale.
However, for rendering, I know the GPU expects everything to be float, so I need to convert from millimeter-scale integer to meter-scale float. Sounds simple, but I'd like to know the most efficient way to perform these two conversions at the same time without losing something along the way.
I know I can convert my 32-bit integer to a double and know that it will all fit, before dividing by 1000 to get meters and converting the result to a float:
int i = 1234567890;
double d = i / 1000.0;
f = (float)d;

But I wonder if that's taking more steps than is necessary. The only other option I can think of is to do something like:
int i = 1234567890;
float f = (i % 1000) / 1000.0f;
f += i / 1000;

But that requires multiple divides and more steps than using a double.
Is there perhaps another existing method of performing this sort of conversion? Or are these my only real options?


texts: How do you generate seamless Perlin noise?

texts:
I've done a research and tried implementing for months, but I've gotten nowhere trying to make seamless/tileable Perlin noise.
Here is my current Perlin noise file without seamless implementation. In my program, I am calling FractionalBrownianMotion to generate.
Each of the research articles have given me issues. In FractionalBrownianMotion I change the call from Perlin to PerlinSeamless.
Research Articles

How to make one-axis tileable simplex noise? Produces broken noise using x2, y2 as period; xsize, ysize as map size. Also tried vice-versa.

Added code:
public float PerlinSeamless(float x, float y)
{
    int width = gradientArray.GetLength(0);
    int length = gradientArray.GetLength(1);

    // map size 250
    float x1 = 0, x2 = 50;
    float y1 = 0, y2 = 50;
    float dx = x2 - x1;
    float dy = y2 - y1;

    //Sample noise at smaller intervals
    float s = x / width;
    float t = y / length;

    // Calculate our 3D coordinates
    float nx = x1 + Mathf.Cos(s * 2 * Mathf.PI) * dx / (2 * Mathf.PI);
    float ny = y1 + Mathf.Sin(t * 2 * Mathf.PI) * dy / (2 * Mathf.PI);
    float nz = t;

    return Perlin3D(nx, ny, nz);
}

public float Perlin3D(float x, float y, float z)
{
    y += 1;
    z += 2;
    float xy = perlin3DFixed(x, y);
    float xz = perlin3DFixed(x, z);
    float yz = perlin3DFixed(y, z);
    float yx = perlin3DFixed(y, x);
    float zx = perlin3DFixed(z, x);
    float zy = perlin3DFixed(z, y);
    return xy * xz * yz * yx * zx * zy;
}
private float perlin3DFixed(float a, float b)
{
    return Mathf.Sin(Mathf.PI * Perlin(a, b));
}

How do you generate tileable Perlin noise? hashed = perm[perm[int(gridX)%per] + int(gridY)%per] goes OOB.
3D Perlin Noise Technique does not replicate 2D noise when z value always 0, but using this method for 3D Perlin noise assuming that's the way it's supposed to be

I have also tried various implementations of non-answer accepted comments in these articles to see only broken noise.


texts: Entity Component System: system and components relation

texts:
I'm planning to develop a game in C# (but I don't think that language matters) and I'll be using Entity Component System since I know by design that my game will have a lot of different game items with different twisted behaviours and logics.
I have some experience using Unity ECS which I find very easy and intuitive. I've also programmed games in the past using the old "inheritance approach" and I found that pattern very not scalable.
As far as I know, a pure ECS (which is not what Unity implements) works like this:

A GameObject is just a collection on Components, it may be seen as a wrapper class or as a shared index in some parallel arrays of Components.
A Component is a collection of data (basically a record) which holds the data needed by its relative System to handle it. It does not implements game logic itself.
A System is a world object which loop through each GameObject which has a component it can process and update game logic of that component.

My point is: if the Systems are the ones responsible for the actual game logic update (practically speaking, the game logic code is written inside the system), is there a 1:1 relation between every component and every system ? Let me explain with an example: let's say I have 2 components:

RenderSpriteComponent
RenderLightSourceComponent

The first one does a simple 2D sprite rendering (using OpenGL or whatsoever); the second one send a light source to the rendering shaders. They do similar operations but with some actual differences. My question is: since they behaviour is different, should I implement two different Systems which will handle them separatly? If not, should I add a bunch of IF statements or overloads to handle those two components inside the same System?
From my point of view both ways seem unnecessary, especially if the ECS should improve code scalability. Using one of those approach would force me either to implement a different system for each component I have (implying a lot of GameObjects loops) or either to fill my Systems with if and overloads making them impossibile to understand after a certain point.
Furthermore, from what I can see and understand, Unity implements a different version of this pattern in which every component implements its own logic (in the Update method) and the GameObject is a wrapper class which has an internal list of components to update. Systems don't exist at all (or if they do they do, they do so for other reasons). This implementation looks easier and more "elegant" from my point of view, but I can't understand why it's not so spread and everyone sticks to the "classic" ECS implementation which has those "problems" I've described above. At the same time, I do not have control over the priority of the components updates, which can be useful in some cases.
I understand there isn't an "absolute" better way to design your game structure, but I'd like to know how is generaly implemented. Or which factors would make a way better than the other.


texts: Phaser Game not rendering on normal page

texts:
I made a game with the Phaser game framework on a course, and now I want to add features and build upon that game.  The only problem is that I built the game with the course on webpack, which served the game on localhost:8080  I want to now stop using localhost and put the game on a normal website, but for that, I need to get it off localhost.  I think the problem is in the index.html file where I render the game.  Here is the index.html code:
<head>
 <style>
  body {
    padding: 200px;
  }
 </style>
 <script type="text/javascript
  src="https://cdnjs.cloudflare.com/ajax/libs/phaser/3.52.0/phaser.min.js"></script>

</head>
...
<script type="text/javascript" src="src/index.js"></script>

Please tell me how I can put my game on a normal website.  Thank You!


texts: What are the performance implications of multiple windows with indivdual OpenGL contexts?

texts:
For an engine I'm developing I've decided to allow users to set up multiple windows showing differing views of the same "world."  This is being developed using OpenGL (hopefully aiming for 3.2 core eventually if that affects the ansmer) and SDL 1.3.  The basic structure I've got set up is:

class Window {
    SDL_Window *sdl_window;
    SDL_GLContext context;

    Window(...) {
        sdl_window = SDL_CreateWindow(...);

        // Rest of the setup of world etc.
    }

    gl_init() {
        context = SDL_GL_CreateContext(sdl_window);

        // Set up initial OpenGL settings.
    }

    render() {
        SDL_GL_MakeCurrent(sdl_window, context);

        // Rendering the world.

        SDL_GL_SwapWindow(sdl_window);
    }
}

This all compiles and runs fine with the rest of the demo code I've developed so far, simply showing a pair of slightly offset views.  However, there's no really performance heavy stuff implemented yet.

Is this the correct approach to use?
Are there any major performance implications with switching the context twice (or more) a frame? (other than the expected double (or more) rendering occurring).

For example, does switching contexts force a flush of the graphics memory to the system RAM or something equally frame-rate killing?

Is there an alternative method  that would allow setting up two different viewpoints and rendering them in one pass?
If this is the best way to do it is there a way of sharing data between contexts?  I'm thinking once I switch to VBO's over display lists, if the views overlap in some way they should be sharing VBO's for that portion.


texts: Vertexquads are not being drawn in 2D space

texts:
I started teaching myself DirectX a short time ago and have come across a problem which I can't figure out by myself unfortunately.
I'm trying to build my own font system, so I can draw strings in 2D screenspace. Until now Until now I have managed to create a function to which I just have to pass the string and the screenspace-positions., and it generates all vertices for / sets up the buffers etc (quads that i draw a certain portion of the font texture on).
When I draw these vertices in 3D space, everything looks like it works like it should be.

(Forgot to hide the cube) As soon as I try to switch to 2D, I just get a window filled with the blue backgroundcolor. To switch to 2D I do the following things:

graphics.context->ClearDepthStencilView(graphics.depthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0);
context->OMSetDepthStencilState(depthDisabledStencilState, 1);

WVP = XMMatrixOrthographicLH((float)mWidth, (float)mHeight, 0.0f, 1.0f);
cbPerVert.WVP = XMMatrixTranspose(WVP);
cbPerVert.World = XMMatrixTranspose(World);

context->UpdateSubresource( cbPerVertexBuffer, 0, NULL, &cbPerVert, 0, 0 );
context->VSSetConstantBuffers( 0, 1, &cbPerVertexBuffer );

My Question is now what I am doing wrong here. If the vertices are being genrated and drawn correctly, afaik all I have to do is project them into screenspace and disable the depth buffer, which I did here..  BTW: I randomly tried drawing the cube with my 2D settings and it was properly drawn..  Help is much appreciated :)


texts: How do I test for collisions between two concave shapes decomposed into collections of convex polyhedra?

texts:
I am using convex decomposition with SAT (separating axis theorem) and I generate two arrays of convex pieces, How do I submit my arrays to my collision detection method which only takes two arguments.

public MTV testCollision(BroadPhasePair pair) {
    Entity entity = pair.getBody();
    Entity id1 = pair.getBody();

    List<Convex> entityConvex = ConvexDecomposer.decompose(entity);
    List<Convex> id1Convex = ConvexDecomposer.decompose(id1);
    return null;
}

private MTV testCollision(Convex body,Convex id1) {
    float overlap = Float.MAX_VALUE;
    Vector3f smallest = null;
    Vector3f[] axis1 = body.getAxis();
    Vector3f[] axis2 = id1.getAxis();

    for(Vector3f axis : axis1) {
        Projection p1 = body.project(axis);
        Projection p2 = id1.project(axis);

        if(!p1.overlapps(p2)) return null;
            float o = p1.getOverlap(p2);
            if(o < overlap) {
                overlap = o;
                smallest = axis;

        }
    }

    for(Vector3f axis : axis2) {
        Projection p1 = body.project(axis);
        Projection p2 = id1.project(axis);

        if(!p1.overlapps(p2)) {
            return null;
        }else {
            float o = p1.getOverlap(p2);
            if(o < overlap) {
                overlap = o;
                smallest = axis;
            }
        }
    }

    MTV mtv = new MTV(smallest, overlap);
    return null;

}

I want to be able to somehow submit my array into the testCollision method.


texts: Different collision effects on different objects

texts: I'm a beginner to Corona and game development. I am using a variety of objects in my game. On collision, they all perform the same function. I want them to do different things, and also want some objects to only collide with certain other objects. How would I go about doing this?


texts: In an Entity-Component System, how to represent the world/level/gameboard?

texts:
I am trying to learn more about Entity-Component Systems, and something that kinda stuck out at me was the question of how to represent the world in such a system? More specifically, I'm trying to do a version of Tetris with such a system, and I was wondering how I would put the board, and the fallen pieces in place?

I was thinking of having each piece be an Entity, and it would store a number of Block Components, which would represent the individual blocks that make up the pieces, and it's relative position to the center of the piece. Would it be a good idea to simply transfer this component to some Board Entity, which would hold many of these components in the board?


texts:
I'm trying to implement an atmospheric scattering in my graphics (game) engine based on the GPU Gems article: link. An example implementation from that article uses a skydome. My scene is different - I don't render a whole earth with an atmosphere which can be also visible from the space but some finite flat (rectangle) area with objects, for example a race track. In fact this is the most common scenario in many games. Now I wonder how to render a sky in such case:

What kind of geometry I should use: skydome, skybox or a full screen quad - then I have to move almost all calculations to the fragment shader, but I don't know if it makes sense in terms quality/performance ?
How to place sky geometry on the scene ? My idea: I have a hemisphere (skydome) geometry with radius = 1 and center in vec3(0, 0, 0) - in object space. Those vertices are sent to the atmospheric scattering vertex shader:

layout(location=0) in vec3 inPosition;
Next, In the vertex shader I transform vertex this way:

v3Pos = inPosition * 0.25f + 10.0f;
Uniform v3CameraPos = vec3(0.0f, 10.0f, 0.0f), uniform fInnerRadius = 10.0f, uniform fCameraHeight = 10.0f

Then I have correct an inner/outer radius propotion (10/10.25),right? I also send to the vertex shader a model matrix which sets a position of the hemisphere to the postion of the mobile camera vec3(myCamera.x, myCamera.y, myCamera.z):

vec4 position = ProjectionMatrix * ViewMatrix * ModelMatrix * vec4(inPosition, 1.0);
gl_Position = position.xyww; // always fails depth test.

The hemisphere moves together with the camera (encloses only some space around camera with radius = 1, but it also always fails a depth test.)

Unfortunately a sky color which I get is not correct:

What about a "sky curve"? Here is a picture which demonstrate what I mean:

How should I set a sky curve?

Edit1 - debugging: In the vertex shader I assigned to v3Pos position of the "highest" vertex in  the hemisphere:

vec3 v3Pos = vec3(0.0f, 10.25f, 0.0f);

Now the whole sky contains a color of that vertex:


texts: Sprite Image in Canvas not displaying correctly (distorted)

texts:
I have a problem with displaying images in my Canvas, as they're not displaying exactly like the imported image.

In the image below, the sprite on the left is how it looks when it's imported. The sprite on the right is how it looks in the canvas. Notice that some of the pixels have incorrect colours, like the lighter pink in the center of the staff's top is gone, the eyeball is a darker shade, some of the colouration under the hood is wrong, and other errors.

( The sprite is just a test I took from somewhere else, not what I intend to use as a final product. )

The project is 3D (going for a 2.5D look with billboard sprites) set to 384x224 resolution, orthographic camera size of 3.5, no anistropic textures, no anti-aliasing.

Is there some setting I missed somewhere to ensure that images display 100% exact like the source sprite when used in the Canvas?

EDIT
Sprite in the Inspector
(Seems to also not be correct)

EDIT
Added entire inspector


texts: Diamond-square terrain generation problem

texts:
I've implemented a diamond-square algorithm according to this article:
http://www.lighthouse3d.com/opengl/terrain/index.php?mpd2

The problem is that I get these steep cliffs all over the map. It happens on the
edges, when the terrain is recursively subdivided:

Here is the source:

void DiamondSquare(unsigned x1,unsigned y1,unsigned x2,unsigned y2,float range)
    {
    int c1 = (int)x2 - (int)x1;
    int c2 = (int)y2 - (int)y1;
    unsigned hx = (x2 - x1)/2;
    unsigned hy = (y2 - y1)/2;
    if((c1 <= 1) || (c2 <= 1))
            return;

// Diamond stage
float a = m_heightmap[x1][y1];
float b = m_heightmap[x2][y1];
float c = m_heightmap[x1][y2];
float d = m_heightmap[x2][y2];
float e = (a+b+c+d) / 4 + GetRnd() * range;

m_heightmap[x1 + hx][y1 + hy] = e;

// Square stage
float f = (a + c + e + e) / 4 + GetRnd() * range;
m_heightmap[x1][y1+hy] = f;
float g = (a + b + e + e) / 4 + GetRnd() * range;
m_heightmap[x1+hx][y1] = g;
float h = (b + d + e + e) / 4 + GetRnd() * range;
m_heightmap[x2][y1+hy] = h;
float i = (c + d + e + e) / 4 + GetRnd() * range;
m_heightmap[x1+hx][y2] = i;

DiamondSquare(x1, y1, x1+hx, y1+hy, range / 2.0);   // Upper left
DiamondSquare(x1+hx, y1, x2, y1+hy, range / 2.0);   // Upper right
DiamondSquare(x1, y1+hy, x1+hx, y2, range / 2.0);   // Lower left
DiamondSquare(x1+hx, y1+hy, x2, y2, range / 2.0);       // Lower right

}

Parameters:
(x1,y1),(x2,y2) - coordinates that define a region on a heightmap (default (0,0)(128,128)).
range - basically max. height. (default 32)

Help would be greatly appreciated.


texts: Full map image loading, vs individual tile loading

texts: I want to make a isometric tile game in java, like a lot of strategy games out there. What is the best approach to loading the map for this game? Would it be better practice to load one single image for the whole map, or would it be better to make images for each tile and render each tile using a int array?


texts: Trouble with UV Mapping Blender => Unity 3

texts:
For some reason I am getting nasty grey edges around the edges of rendered 3D models that are not present in Blender.

I seem to be able to solve the problem by reducing the size of the UV coordinates within the part of the texture that is to be mapped. But this means that:

I am wasting valuable texture space
Loss of accuracy in drawn UV maps

Could I be doing something wrong, perhaps a setting in Unity that needs changing? I have watched countless tutorials which demonstrate Blender default generated UV coordinates with "Texture Paint" which are perfectly aligned in Unity.

Here is an illustration of the problem:

Left: approximately 15 pixels of margin on each side of UV coordinates
Right: Approximately 3 pixels of margin on each side of UV coordinates

Note: Texture image resolution is 1024x1024


texts: How is the Unreal rendering pipeline implimented?

texts: I know this seems like a very broad question, but i am just interested in getting to know how the Unreal engine's rendering pipeline looks like, specially how it handles meterials, different types of lighting, and post processing. I know that Unreal4 uses differred shading, but how does it handle things like translucency, reflections, etc. I do not have access to the source code, that's why I asked this question here. You could even direct me to the source of the rendering part if available.


texts: What is the origin of the term "AAA game?"

texts: One often hears the term "AAA" thrown around when talking about top production value games and big releases, but where does the term come from? How was it coined and popularized?


texts:
So I have this code for showing an ad. It is supposed to pause the app while the ad  is showing. It works on android but on iOS it doesn't even seem to be called, judging from the debug msgs shown in Xcode. Here is the code :

IEnumerator ShowAndWaitForAd()
{
    if (Advertisement.IsReady())
    {
        Debug.Log("Add is ready");
        ShowOptions options = new ShowOptions();
        options.resultCallback = AdCallbackhandler;
        Advertisement.Show();
    }
    else {
        Debug.Log("Add is not ready");
        SceneManager.LoadSceneAsync(2);
        GameObject.Find("Canvas").transform.FindChild("Loading").gameObject.SetActive(true);
        Time.timeScale = 1;
    }
    float currentTimeScale = Time.timeScale;
    Time.timeScale = 0f;
    Debug.Log ("From show Ad, current time scale is: " + Time.timeScale);
    Debug.Log ("current status of advertisement is : " + Advertisement.isShowing);
    while (Advertisement.isShowing) {
        Debug.Log ("!!!!!!Ad is showing!!!!!!");
        yield return null;
    }
    SceneManager.LoadSceneAsync(2);
    GameObject.Find("Canvas").transform.FindChild("Loading").gameObject.SetActive(true);

    Debug.Log ("Setting timescale to 1!!!!!");
    Time.timeScale = currentTimeScale;
}

On android this starts loading the level only after the ad has finished or has been skipped. On iOS this load the level while the ad is showing. That means that the line while (Advertisement.isShowing) is being skipped for some reason. Has anyone encountered this before ?

Edit the problem seems to be that Advertisement.isShowing is always returning false even when the ad is showing.


texts:
I have an animation of a bullet but it seems to be going much faster than i was expecting.

I currently set it to 0.5 pixels per second yet it seems to be moving way over hundreads of pixels per second.

Not quite sure where my logic is going wrong:

This is inside my gameLoop which im using to calculate it:

var deltaTime = (new Date().getTime() - started) / 1000; // divide to get seconds
var position = deltaTime * bulletVelocity; //bulletVelocity is 0.5

var vectorX = destinationX - startX;
var vectorY = destinationY - startY;
var distance = Math.sqrt(vectorX * vectorX + vectorY * vectorY);

var x = startX + (vectorX * position);
var y = startY + (vectorY * position);

if (x < destinationX && y < destinationY) {
    ctx2.drawImage(pulse, x, y); //draw the sprite on canvas
}

Have i got my logic wrong here i cannot work out why its moving so fast.


texts: Is my calculation of chances correct for my AI?

texts:
I'm working on a turn based game where one part is pretty much like playing "Memory": remember where a specific card is located in a grid.

My AI works like this:

If a card is peeked (turned around and looked at) -by the player or AI - the AI remembers the location of this card 100%.
If the next card is peeked, a "dementia" factor will be applied to all the previous remembered cards. This means, card one is now only remembered with 80%, card two with 100%.
This information is kept in an array. Over time, chances to remember a card location decreases.

Now in order to figure out if the AI remembers a specific card X, I get the chance for the card X from the array, let's say the chance is 60%, or 0.6.

I then generate a random float number between 0 and 1. If the random float is lower than or equal to 0.6, I let the AI remember the location.

Is this a valid approach? I'm assuming here that the randomization in .NET is uniformly distributed.


texts: GameLoop architecture for local multiplayer

texts:
I'm writing a game for Android to which I want to add a mulitplayer mode (local multiplayer via WiFi/Bluetooth, not online multiplayer via server). I stored the exchange-code between the client devices and the host device in th methods getInput() and pushInput(). I'm currently using a single-threaded gameLoop like this in my singleplayer mode:

public void mainLoopIteration(Canvas c, float deltaTime){
    compute(deltaTime);
    render(c);
    ...
}

My question is which of the following ways is the better implementation of the multiplayer "add-ons":

Adding exchange-calls to mainLoopIteration():

public void mainLoopIteration(Canvas c, float deltaTime){
    pushInput();
    getInput();
    compute(deltaTime);
    render(c);
    ...
}

creating a second thread that handles all the exchange stuff:

public void run(){
    while(mainLoopIsRunning){
        pushInput();
        getInput();
        //???Thread.sleep(...);
    }

}

Which solution you'd suggest or maybe do you suggest a completely other way?

Thx and regards Lisa


texts: Application stops working when I add two fonts

texts:
I created a game that has two fonts.
Being precise, the two fonts are PRESS_START_2P with the difference only in size. One of the fonts serves to write the title and the other for all other things.
The problem occurs after building the application (apk). As it is a special font I click on the option "copy to project" for it to be exported to the cell phone.
Image of the two fonts:

A detail is that the program does not recognize the original source directory, so I need to copy the source to the desktop to be able to copy it to the project.
Image demonstrating the problem:

Adding any of the fonts (alone), the game works. The problem happens when I add the second font.
Before posting here, I posted on the official engine forum, but I still haven't gotten any response.
LINK:
https://forum.yoyogames.com/index.php?threads/application-does-not-work-when-i-export-2nd-font.83968/


texts:
Problem:

Been trying for hours to set a simple png of a cross hair as a texture (so I could later stick in the middle of the view like a normal cross hair), without luck.

I'm coding in Java with JOGL.

P.S Also need to make the background of the texture transparent. But that's another problem.

Code:

public void display(GLAutoDrawable gLDrawable) {
    final GL2 gl = gLDrawable.getGL().getGL2();
    gl.glClear(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT);
    gl.glLoadIdentity();  // Reset The View
    gl.glTranslatef(0.0f, 0.0f, -5.0f);

    gl.glTexParameteri ( GL2.GL_TEXTURE_2D,GL2.GL_TEXTURE_WRAP_T, GL2.GL_REPEAT );
    gl.glTexParameteri( GL2.GL_TEXTURE_2D,GL2.GL_TEXTURE_WRAP_S, GL2.GL_REPEAT );
    texture.bind(gl);

    gl.glBegin(GL2.GL_QUADS);
    // Front Face
    gl.glTexCoord2d(0, 0);
    gl.glVertex3d(0, 0, 0);
    gl.glTexCoord2d(0, 1);
    gl.glVertex3d(0, 1, 0);
    gl.glTexCoord2d(1, 1);
    gl.glVertex3d(1, 1, 0);
    gl.glTexCoord2d(1, 0);
    gl.glVertex3d(1, 0, 0);
    gl.glEnd();
}

public void init(GLAutoDrawable drawable) {
    final GL2 gl = drawable.getGL().getGL2();
    gl.glShadeModel(GL2.GL_SMOOTH);              // Enable Smooth Shading
    gl.glClearColor(0.0f, 0.0f, 0.0f, 0.5f);    // Black Background
    gl.glClearDepth(1.0f);                      // Depth Buffer Setup
    gl.glEnable(GL2.GL_DEPTH_TEST);              // Enables Depth Testing
    gl.glDepthFunc(GL2.GL_LEQUAL);               // The Type Of Depth Testing To Do
    // Really Nice Perspective Calculations
    gl.glHint(GL2.GL_PERSPECTIVE_CORRECTION_HINT, GL2.GL_NICEST);
    gl.glEnable(GL2.GL_TEXTURE_2D);
    gl.glEnable(GL2.GL_BLEND);
    try {
        String filename = "resources/misc/crosshair.png";
        texture=TextureIO.newTexture(new File( filename ),true);
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
    gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_MIN_FILTER, GL2.GL_LINEAR);
    gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_MAG_FILTER, GL2.GL_LINEAR);
}

Result:

Original png:

Edit

Changed code above according to comments, here's the new result:

Another Edit

Had to add this line after glBlend, everything works after that:

gl.glBlendFunc(GL2.GL_SRC_ALPHA, GL2.GL_ONE_MINUS_SRC_ALPHA);


texts:
I'm trying to load .obj files in my little game. I decided to use assimp as tool to import those models. But it seems that assimp does not import them correctly.

I looked for a simple cube mesh online and found this one:
http://cs.wellesley.edu/~cs307/tw/objects/cube-textures.obj

But when importing the model the number of faces is only 11 instead of 12. I then tested to load the model in the model viewer provider by assimp. But the problem is the same, one face is missing.

Is there anything I'm missing? Here is my loading code:

const aiScene* AssimpScene = this->AssimpImporter.ReadFile("C:/cube.obj",  aiProcess_CalcTangentSpace);


texts: Creating HTML5 Canvas Objects in Javascript

texts:
I'm currently trying to learn how to make HTML5 Canvas games with JavaScript. I would like to use object oriented JavaScript to manage the elements of the game, but i'm having trouble. I've done a lot of research already, but there seems to be a million ways of doing everything and no one source has been able to provide me with the information I think I need in order to get the result I think I want. More specifically I'm having trouble utilizing object prototypes. I've started out by creating the canvas in my code like so

var body = document.getElementsByTagName("body")[0];
var canvas = document.createElement('canvas');
body.appendChild(canvas);

My thought process has lead me to thinking that I should make an object out of this so I can use this dynamically later on if needed. So i've implemented it like so.

var gamearea = function(){
this.generate = function(){
  var body = document.getElementsByTagName("body")[0];
  var canvas = document.createElement('canvas');
  body.appendChild(canvas);
}

I know that I will probably need multiple contexts of the canvas element going forward, so I'm thinking that I should create a prototype for this like so.

var context = function() {
  return canvas.getContext('2d');
}

My thinking is that I can then ceate the objects for the context I need by instating them with there prototypes like so.

var background = Object.create(context);
var foreground = Object.create(context);

But in order to assign IDs to these objects so I can reference them for drawing on later, I need to assign IDs to them. I found a blog that indicated the proper formatting would mean implementing the following.

var background = Object.create(context, {id: {value: 'background'} });
var foreground = Object.create(context, {id: {value: 'foreground'} });

So my question is this. Is there a way to incorporate more unified formatting to all of this? Id like to establish this prototypes with their id's beforehand like I did with the gamearea object. I want to avoid giving objects properties inline. I am doing this right? Is there a better way? I'm I a complete idiot?

Thank you very much for your time on this guys, I really appreciate it. :)


texts: jquery ondrag map load only what has not been viewed

texts:
When a person mouse down, moves the mouse, and mouses up the system gets the different in the mouse down coord and the mouse up coords and loads in the new map items. However, the problem is it loads them every time so I want a way to track what has been loaded without too much work on checking or storing checks.

Most promising. Came up with while typing this. Section the screen into 250x250 sectors and check if that sector has been loaded.
Keep track of each corner of the screen and see if there is an area of those that have not loaded.
Keep a record of the corners of the screen. When mouse up coords are greater then load the different. Problem is if they are at coord 10,000 then it will load from -10k to 10k positive and that is a lot of items to load.
Check every item on the page to see if it is loaded. If I do this I might as well reload the whole page.

If anyone has some suggestions; feel free to pass them on.


texts: How can I make location-based spells which create soil patches on the ground?

texts:
I'm making a spell that'll place a soil patch on the ground in skyrim, and I cannot get it to work. I would like some help. When I tested the spell in game, no soil patch appeared on the ground. I tried doing it on different terrains and different levels of hills, mountains, etc. with no luck. I'm not sure what I am missing. I'm using the soil patches that are functional in the HearthFire DLC.

Here is what I've done thus far:

I made an activator "marker" with a script attached to it that is supposed to summon a soil patch at its location. This is the current script for it:

ScriptName maSpawnSoilPatchActivatorScript Extends ObjectReference

ObjectReference refMarkerPosition

Event OnInit()

   refMarkerPosition = Self.PlaceAtMe(Game.GetForm(0x02008240))

EndEvent

After, I made a "dummy" explosion that is supposed to place the activator at the location where the spell hits, so that it can spawn the soil patch in that location.

I then added the dummy explosion to a new magic effect, and then attached the magic effect to the conjuration spell I created.


texts: Use FlxAnim to Animate a FlxSprite in Flixel on FlashBuilder

texts:
I am trying to animate a FlxSprite, whose image I loaded from an embedded sprite sheet. I instantiate the sprite like this:

// embedding a png file given a relative path
[Embed(source="../Images/BatGraphic.png")] public var Bat_Enemy:Class;
override public function create():void
{
//instantiate bat sprite
bat = new FlxSprite(FlxG.width/2-5,FlxG.width/2);
bat.loadGraphic(Bat_Enemy,true,false,30,12,false);

//add animation to bat
var frames:Array = new Array(12);
AddAnimationToSprite(bat,frames,"batAnimation",30);
//add bat enemy to screen
add(bat);

I use this function to add the animation to the sprite, it essentially just calls the Flixel API:

public function AddAnimationToSprite(sprite:FlxSprite, frames:Array,animName:String,frameRate:int):void
{
   var animation:FlxAnim = new FlxAnim(animName,frames,frameRate,true);
   sprite.addAnimation(animName,frames,frameRate,true);

}

Then, in the update function, I call the FlxSprite play method to animate the sprite:

public function update:void()
{
/*animate relevant sprites*/
bat.play("batAnimation",true);
/*end animation*/

/*update screen based on player position*/
super.update();
}

Yet, the sprite does not animate. Is there a step I am missing? How do you use FlxAnim to animate a FlxSprite?

Update:
I altered the code so that the FlxAnim.play() is called in the create as suggested as follows:

//instantiate bat sprite
bat = new FlxSprite(FlxG.width/2-5,FlxG.width/2);
bat.loadGraphic(Bat_Enemy,true,false,30,12,false);

//add animation to bat
var frames:Array = new Array(12);
//AddAnimationToSprite(bat,frames,"batAnimation",30);
var batAnim:FlxAnim = new FlxAnim("batAnim",frames,30,true);

add(bat);
bat.play("batAnim");

However, still nothing happens. Potentially, I don't have the right number of frames, since I only wanted to use the first row of sprites in the sheet to animate. But even if the number of frames were off, it should still be animating in some fashion right? Like flickering between two sprites?  What am I missing here? Is 30 the appropriate fps for Flixel animations?


texts: Pause Tiled animation during game in LibGDX

texts:
I’m using Tiled with LibGDX and I have some animated tiles. When the game is paused I would like their animation to be paused as well. Is this possible?

The map is drawn with mapRenderer.render() and if I'm not mistake, this is the class responsible for getting the corresponding animation. There doesn't seem to be a way to freeze time. Any help appreciated, I've been searching for a couple of hours and cannot find anything.


texts:
To advance those coding language and enhance the combination of gameplay device.

Here are a file extension with ".d"

Any compilers would I find for checking if it's able to run?


texts: SDL and OpenGL resize window event question

texts:
So basically my question is im making a 2D game with openGL and SDL.

So what im trying to do is resize the game and have the openGL quad scale to the size my window becomes.

void CApp::OnResize(int w, int h){

textureWidth = (float)w;
textureHeight = (float)h;

SDLWindow::SetGLWindow(w, h, Surf_Display);

}

bool SDLWindow::SetGLWindow(int width, int height, SDL_Surface * Surf_Display)
{
if((Surf_Display = SDL_SetVideoMode(width, height, 32, SDL_HWSURFACE | SDL_OPENGL | SDL_RESIZABLE)) == NULL) {
    return false;
    }

glClearColor(0, 0, 0, 0);
glClearDepth(1.0f);

glViewport(0, 0, width, height);

glMatrixMode(GL_PROJECTION);
glLoadIdentity();

glOrtho(0, width, height, 0, 1, -1);

glMatrixMode(GL_MODELVIEW);

glEnable(GL_TEXTURE_2D);

glLoadIdentity();

return true;

}

So this works just fine. However while resizing the window, the image isnt scaling. It only scales after i release the mouse button. I am curious if i can scale the image at the same time?


texts: How to balance GPU compute usage against render usage?

texts:
The GPU's primary purpose, obviously, is to render the scene.

However, if we use compute capabilities on the very same GPU, how do we partitition and control these calls such that they do not interfere with render throughput, i.e. manage load balancing? Is there standard practice in this regard?


texts:
What is the best method for creating user definable or user changeable keys in a flash game?

Edit: I meant, user changeable keys. Not user changeable flash buttons. Why would a user need to change the graphic of a button in a game?


texts: RawInput -- Getting the system default mouse and keyboard

texts:
I'm using RawInput for device management, in a project that I have been working on for some time.  It works great, really, but...

After some hardware changes on my development system, including the addition of a second Wacom device, I'm having difficulty getting RawInput to enumerate the default mouse and keyboard input devices without going in and plugging hard values into the enumeration code.

When I call GetRawInputDeviceList  and sort through the device instances based on their RawInput DeviceType, I have 5 keyboard devices and 6 mice, along with a slew of non-specific HID devices.  Usually, the first keyboard device returned is the real default system keyboard -- but not always.  Adding or removing USB devices between application runs almost always breaks it.

Digging deeper into the enumerated device instances, I thought that examining the RawInputDeviceInformation structure would help.  For some devices, especially older input devices, there's a value that allows you to identify which device instance is a real physical device and not one of those phantom/pseudo devices.  DeviceInformation structures on keyboard device instances all report a differing number of keys, with all the other significant values -- vendor, usage page, usage, etc. being identical.  Unsurprisingly, the reported number of keys doesn't even reflect the actual number of physical keys on the keyboard.

DirectInput identifies the default system mouse and keyboard, and although it's based on RawInput, does it use RawInput to achieve this?  Switching away from RawInput is not an option for me because of the other devices I am operating with it (Wacom, Logitech G19 etc).   Any advice on how to straighten this out would be gratefully received, with thanks!


texts: A name that describes this type of turn-based battle system

texts:
I am thinking of a turn-based battle system that follows this workflow:

While True
  Get next character
  Determine character's action
  Execute action
  Check Battle Status
end

This is a straightforward battle system: there's a queue of battle characters, and on each iteration, it grabs the character at the front of the queue and has it perform an action. Once the action is performed, it gets pushed to the back of the queue.

Everyone gets an equal opportunity to perform an action and it simply rotates through all the participants.

When the loop breaks, end-battle processing occurs (eg: victory, defeat, escape, etc)

Is there a name for this particular type of turn-based battle system?


texts: When should iOS gamecenter authentication be called?

texts:
I'm integrating GameCenter leaderboards into my iOS game. The game has a home screen with a play and "High Scores" button, the game screen itself, and a finished screen with you score, another "High Scores" button, and some other stuff.

When installing the GameCenter package it recommended that you call the authentication function as soon as the device is ready. In this case, if a user that is logged into GameCenter opens the app it immediately says "Welcome back XX" and the player can continue like normal. However, if a user is not logged in, as soon as they open the app they are greeted with the GameCenter login page, which to me is a bad user experience.

The alternative is to only do the initial authorization when the user clicks to see the high scores, if they are logged in it takes them to the leaderboard, if not it prompts them to log in. The problem with this is if they don't try to view high scores until the game is over it would not have saved their score to the leaderboard (as I have it automatically submit if logged in on Game Over).

Which of these two choices is the best? I don't see the first option occur too often as I'm rarely/never greeted with a GameCenter login as I enter a game. Although number 1 is recommended by the plugin I installed. Should I have a dedicated "Sign in" button?


texts: How to send an int array and struct via ENet?

texts:
I've been using the ENet library for networking and so far it's been working ok. I have established a connection between my client and server. On the client side all it does is send all user input to the server. On the server side I have an array int map[24][24] that stores all of the map tiles. I also have a struct for each player. After I get all of the user input, do all the calculations, and update the map, how would I send the map back to the client? Right now the function I've been using supports sending chars. Would I convert my int array and struct objects to char and send them? How should I accomplish this, also should I send the map and player structs in one packet, or send each in a separate packet? This is my first to experimenting with multiplayer so I apologize if this is a simple mistake or stupid question.

This is my function for sending packets:

void send_packet(int channel, char pack[11]) {
    ENetPacket *packet = enet_packet_create(pack, strlen (pack) + 1, ENET_PACKET_FLAG_RELIABLE);
    enet_peer_send(peer, channel, packet);
    enet_host_flush(host);
}


texts: All libGDX input statements are returning TRUE at once

texts:
I'm fooling around with Box2D and libGDX and running into a peculiar problem with polling for input. Here's the code for the Screen's render() loop:

@Override
public void render(float delta) {
    Gdx.gl20.glClearColor(0, 0, .2f, 1);
    Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT);
    camera.update();
    game.batch.setProjectionMatrix(camera.combined);
    debugRenderer.render(world, camera.combined);
    if(Gdx.input.isButtonPressed(Keys.LEFT)){
        Gdx.app.log("Input", "Left is being pressed.");
        pushyThingyBody.applyForceToCenter(-10f, 0);
    }
    if(Gdx.input.isButtonPressed(Keys.RIGHT)){
        Gdx.app.log("Input", "Right is being pressed.");
        pushyThingyBody.applyForceToCenter(10f, 0);
    }
    world.step((1f/45f), 6, 2);
}

And the constructor is largely just setting up the World, Box2DDebugRenderer, and all the Bodies in the world:

public SandBox(PhysicsSandboxGame game) {
    this.game = game;
    camera = new OrthographicCamera(800, 480);
    camera.setToOrtho(false);

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

    BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyType.DynamicBody;
    bodyDef.position.set(100, 300);

    body = world.createBody(bodyDef);

    CircleShape circle = new CircleShape();
    circle.setRadius(6f);

    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = circle;
    fixtureDef.density = .5f;
    fixtureDef.friction = .4f;
    fixtureDef.restitution = .6f;

    fixture = body.createFixture(fixtureDef);
    circle.dispose();

    BodyDef groundBodyDef = new BodyDef();
    groundBodyDef.position.set(new Vector2(0, 10));
    groundBody = world.createBody(groundBodyDef);
    PolygonShape groundBox = new PolygonShape();
    groundBox.setAsBox(camera.viewportWidth, 10f);
    groundBody.createFixture(groundBox, 0f);
    groundBox.dispose();

    BodyDef pushyThingyBodyDef = new BodyDef();
    pushyThingyBodyDef.type = BodyType.DynamicBody;
    pushyThingyBodyDef.position.set(new Vector2(400, 30));
    pushyThingyBody = world.createBody(pushyThingyBodyDef);
    PolygonShape pushyThingyShape = new PolygonShape();
    pushyThingyShape.setAsBox(40f, 10f);
    FixtureDef pushyThingyFixtureDef = new FixtureDef();
    pushyThingyFixtureDef.shape = pushyThingyShape;
    pushyThingyFixtureDef.density = .4f;
    pushyThingyFixtureDef.friction = .1f;
    pushyThingyFixtureDef.restitution = .5f;
    pushyFixture = pushyThingyBody.createFixture(pushyThingyFixtureDef);
    pushyThingyShape.dispose();
}

Testing this on the desktop. Basically, whenever I hit the appropriate keys, neither of the if statements in the loop return true. However, when I click in the window, both statements return true, resulting in a 0 net force on the body. Why is this?


texts: "Acrobatic" and "fluid" combat system (i.e. Spider-Man 2018)

texts: Like it says in the title, I like the way that Spider-Man Has a dynamic and fluid feeling combat system. I can't exactly put my finger on a few key aspects, though, and I don't have any way I can think of to recreate it in a game engine. Why does it feel good to play, and how could I apply that to my game?


texts: How can I use Cross Platform Input in Unity 2019?

texts:
I am trying to use CrossPlatformInput in Unity 2019 to follow this tutorial to use it on iOS:

https://www.youtube.com/watch?v=Auj1mrsfXDE

However, I have no item in the top bar for "Mobile View" like in the tutorial, and I do not know how to enable it. I have Standard Assets imported already. Is there an example project I can download with CrossPlatformInoput that works with iOS or a way for CrossPlatfromInput to work in modern versions of Unity?


texts: How to avoid banding with raymarched fog?

texts:
I have a raymarching shader for fog.
It works well but It creates artifacts in the form of banding:

I understand the problem: The step size is too large and the sample points above the ground are not hitting the floor until the distance is bigger again.
However, How can this be reduced/ avoided?
My Shader looks like this:
float4 PS(PixelShaderInput input) : SV_TARGET {
    float3 rayStart = input.WorldPos.xyz;
    float3 viewDirection = normalize(input.WorldPos.xyz-CamPositionWS.xyz);
    float depth = linearize_depth(DepthTexture.Sample(DepthSampler, input.UV).x, NearPlane, FarPlane);
    float4 result = float4(FogColor, 0);
    float stepSize = 300;
    float stepAmount = ((NoiseTexture.Sample(Sampler, input.UV * 64).x)) * 64;
    [unroll(96)]
    while (stepAmount < depth) {
        float3 samplePos = rayStart + (viewDirection*stepAmount);
        stepAmount += stepSize;
        float fogDist = distance(samplePos, FogCenter);
        if (fogDist > FogRadius)
            continue;
        result.a += density(fogDist,FogRadius)*FogDensity;
        if (result.a >= 1) {
            result.a = 1;
            break;
        }
    }
    result = saturate(result);
    return result;
}


texts: Is developing for non-retina iPod Touch/iPhones still worth it for deployment?

texts:
We're a couple of guys making games for iPod Touch and iPhone. I personally have an iPhone 4 with the retina display and I'll be using this as my main test device. I have an opportunity to purchase a cheap 2nd generation non-retina iPod Touch and was thinking that would be good to have as another test device. But is it worth the purchase?

There is still a huge amount of people on non-retina hand devices? Is a 2nd generation iPod Touch just too old to worry about and maybe I should look into getting a new generation?


texts:
I am following this tutorial https://lodev.org/cgtutor/raycasting.html

  When deriving deltaDistX geometrically you get, with Pythagoras, the formula "sqrt(1 + (rayDirY * rayDirY) / (rayDirX * rayDirX))", but this can be simplified to abs(1 / rayDirX). [thanks to Artem for spotting this simplification]
  Similarly, deltaDistY is "sqrt(1 + (rayDirX * rayDirX) / (rayDirY * rayDirY))" which can be simplified to abs(1 / rayDirY).
  The variable perpWallDist will be used later to calculate the length of the ray.

In the calculation that involves Pythagoras, why is a "+1" involved? I thought the equation was a^2+b^2=c^2? I feel dense... Also, I do not understand how the simplification to abs(1/rayDirX) works.


texts: How to create a seamless cubemap noise texture?

texts:
I have, so far, been able to create the vertices and UV coords etc for a sphere that would be textured with a cube map. I have also successfully loaded a cube texture from file and applied it to my sphere and it looks awesome.

So now, I want to randomly create a noise cube texture map to apply to my sphere.

I have a class which can create 1d, 2d, 3d and 4d noise. My problem is I don't know the math needed to sample a sphere map out of the cube, and then how to translate this to the 6 textures that make up with my cubemap.

I guess first I need to know how to first sample the points of a sphere in 3d; and then how to translate these to x,y,z coordinates for the 6 sides. I can probably work it out from there.

I would have thought this would be simple enough to Google, but I'm not finding what I need.

SOLUTION

For whomever comes along next, here's the answer. @Jason has the right idea below. Here's how I solved it:

March through each of the faces of the cube and each UV coord for that face
Normalize each position vector
Multiply by the radius of your sphere. You now have the coordinates of the sphere edge
These coordinates can be used to sample from your 3D noise function

You'll end up with each faces UV coordinates being filled with the noise that is at the spherical equivalents position in the noise.

(I hope that was in english). I will try to remember to update this later with full code once I've cleaned it up.


texts: Light levels - How to determine if a character should be spotted

texts:
Our team is trying to develop a stealth system with the UDK. Part of this will involve lighting.

The idea being that if you're hiding in a dark corner of the room, the armed goons will not start attacking you.

I've been looking for a few hours now. And while I can't say I have no leads it seems that now is a good time to start asking for help.

At the simplest level, I'm looking for a way to determine how brightly lit an actor is (primarily the player right now).

A bit beyond that, what they are wearing might also be a factor. Someone wearing solid dark clothing is going to be harder to spot than someone in a loud Hawaiin t-shirt covered in (given the stealth context probably stolen) diamonds.

The lighting will be dynamic, so the solution needs to be dynamic. As an example, a guard might get rather upset, grab a torch on the wall and throw it in your direction.


texts: My runtime (game) won't reset back to how it was?

texts:
I increase the scale of the objects when it passes a certain time or in this case, my "difficulty"
    //Spawn Size
float spawnSize = 8;

void Update()
{
    if (Time.time > nextSpawnTime)
    {
        float SpawningInBetween = Mathf.Lerp(spawnsMinMax.y, spawnsMinMax.x, Difficulty.GetDifficultyPercent());
        print(SpawningInBetween);
        nextSpawnTime = Time.time + SpawningInBetween;

        if(Difficulty.GetDifficultyPercent() > 0.7f)
        {
            fallingRockPrefab.transform.localScale = Vector2.one * spawnSize;
        }

Then as expected, the object increases the size after it passed that conditions so i want to revert back to its previous state so i remove:
  if(Difficulty.GetDifficultyPercent() > 0.7f)
    {
        fallingRockPrefab.transform.localScale = Vector2.one * spawnSize;
    }

but when I saved it and go back to unity, the object still in its "increased" size right at the start. What's happening?


texts:
I have been trying to get my shader code (HLSL) to draw a simple circle but after a day and a half I am getting nowhere.  It seems people are using $$x^2 + y^2 = r^2$$ and remap texcoords but I only get a white quad.

    struct VertexShaderStruct
{
    float4 Position : POSITION0;
    float2 Tex0 : TEXCOORD0;
};

VertexShaderStruct VertexShaderFunction(VertexShaderStruct input)
{
    VertexShaderStruct output;

    float4 worldPosition = mul(input.Position, World);
    float4 viewPosition = mul(worldPosition, View);
    output.Position = mul(viewPosition, Projection);
    output.Tex0 = input.Tex0;

    return output;
}

float4 PixelShaderFunction(VertexShaderStruct input) : COLOR0
{
    float dx = 2 * input.Tex0.x - 1;
    float dy = 2 * input.Tex0.y - 1;
    float hyp = (dx * dx + dy * dy);

    return (hyp == 1)? circleColor : otherColor;
}

I define circleColor as blue and otherColor as white, so it seems hyp==1 always fails.


texts: GuiSan | SDL2 - Setting colour key of render target results in having an black screen

texts:
At the moment i am experimenting with guisan within my little project. Everything is done sofar with SDL_Texture except Guisan which utilize SDL_Surfaces instead SDL_Texture for rendering itself.

Per sé this is absolutly fine. When guisan has finished rendering stuff on its SDL_Surface target I simply convert this Surface into an SDL_Texture or to be more precise I Update an pre-existing SDL_Texture and then Render this specific SDL_Texture. This works perfectly.

Till here everything is fine. I can interact with my GUI and the rest of my application. Then i thought at some point why not use an colour key (0xff00ff) to make the target of guisan transparent except for the parts it is drawing his stuff.

So i started calling:

 SDL_FillRect(guisanTarget,NULL,*0xff00ff*);

To Fill my Target with the colour key i am about to hide away, with this call:

SDL_SetColorKey(guisanTarget,SDL_TRUE,SDL_MapRGB(guisanTarget->format,0xff,0x00,0xff));

And here is where my problem occurs... if i try to set my colour key the result will be a black screen. No visible GUI to interact with. If I DO NOT set the colour key via SDL_SetColorKey then i get my GUI with the background colour i filled my Target via SDL_FillRect.

I have no clue why... If anyone has an idea what the reason for this behaviour is please let me know i would appreciate it a lot. see my issue


texts: Can a high FPS negatively affect how a program runs?

texts:
Yeah I know this is a broad question and will get down rated, I'm just hoping for some answer before it gets closed.

Anyway, I'm using Slick 2D/Java to play around with graphics. I'm having some trouble with trying to move an image. The weird thing is, the code works just fine on my laptop, but the image sporadically moves to (0,0) and stops on my desktop. The only difference between the two is that it says the FPS is about 500 on my laptop and 6600 on my desktop. Can that affect it or does someone have any ideas for what to check on?


texts: Pathfinding with differently-sized objects on tile map

texts:
It's my first RTS game and I'm having trouble finding out how to make infantry take less space than tanks.

Right now I have 1 tank and 1 infantry type ready with sprites, pathfinding, selection and movement mechanics all ready, up and running.  The infantry unit is 16x16 and the tank is 32x32 which the size of one tile in my map.  How can I make a foot soldier stand or walk with another foot soldier in the same Tile?  Should I use 2 versions of the map for each of the unit types to make their pathfinding?  In which case there would be problems with coordinates when these 2 types interact with each other like attack and defend which i haven't yet coded.

I'm even starting to question whether a tile based map is even a good choice for a 2D rts game, which is obviously a rediculous question xD.


texts: How can I bake several variations of a substance?

texts:
I have a substance (sbsar) that I'm using to generate a procedural material .  I have applied this texture to reversi pieces.  It works well, but all the pieces look identical.  I addressed this by using a script to change the $randomseed property and then call the RebuildTextures method for each piece.  The effect is exactly what I want: each piece has a slightly distinct marble pattern.

The problem is that the process of rebuilding the textures for 64 pieces takes about 20 seconds.  For a simple Android game, this is not acceptable performance.

The designer has the option to "bake" the material under Load Behavior, but this only works for one variation.  Is there a way I can bake many different random seeds?  I'd be OK with pre-generating a batch of non-procedural materials from the substance and picking randomly from that batch at runtime, but I'm not sure how that can be done.


texts: Android collision detection of a 3d object based on a 2d projection

texts:
I am writing a game for android. We have an orthographic view setup, but the characters (ships, projectiles, etc). The enemies / characters will be able to rotate about the x axis. The problem is that I want to do the collision detection as if it were in 2d using sprites, meaning that if i have a ship with a top down view of

---------
--------------
-----------------
--------------
---------

it might rotate to look like

-----
--------------
---

and i want to do all of the collisions based off of the appearance of a top down view. I was originally thinking of using glReadPixels, until I read that was unbelievably slow. Then I was thinking about using pre-rendered bitmaps, but that seems like a pain and not very great since some of our ships won't be 'normal' enough to just say "Have a bitmap for every 45 degrees of rotation about the X". Does anyone have any suggestions?


texts: How to prevent clients from stuttering while keeping the game in sync in multiplayer Pong?

texts:
I wrote Pong in multiplayer. The clients all run their own game, but I have an authoritative server which enforces its ball position onto the clients.

The game is in sync and playable, however, there is some stuttering on the client side even with a fast connection. I've read that clients could be configured in a way that shows a smooth experience to the player, while in fact the connection may be lagging.

I was thinking about not directly correcting the ball position when a server position update comes in, but to increase or decrease the ball's velocity based on the difference. I didn't manage to get this working properly yet.

Am I thinking in the right direction? How would I make a calculation that shows a smooth experience to the players, while keeping the game in sync?


texts: Swapping axis labels between 2D and 3D coordinates

texts:
My game world is 3D.

The map is only 2D, however.

It is natural to think of the map as having an X and Y axis.

And it is natural to think of the world has having an X, Y and Z axis, where Y is upwards.

That is to say, X Y in 2D map coordinates is X Z in 3D coordinates.

What conventions and approaches do you have to keeping things straight at a code level to make mapping between them natural?

(Is Y usually upwards in 3D?  Or do you have X and Z in map coordinates, or?)


texts: Combine n Gaussian Probability Sets in a limited float range

texts:
I've got a fixed solution space defined by a minimum and maximum float which has no divisible slice.

You then have 0..N Gaussian distribution probability sets which I need to combine.

In the end I neeed

Method to define probability set with a numeric range (not sliceable) and 0..N Gaussian functions
A function which can generate a random number in the range as defined by the calculated probabilities.

Also I know it is possible that some combinations will generate a zero solution space.

Now I'm thinking the way to do it is take the normalised probability density functions and multiply them to get a new space then normalising the result. I just can't seem to break it down into algorithmic form.

Any ideas?


texts: Unreal editor warns that Xcode is not installed on MacOS 10.14

texts:
I'm running MacOS 10.14.6. When I launch Unreal v4.25.0, I get the following warning:

Xcode was not detected on this Mac.
Metal shader compilation will fall back to runtime compiled text shaders, which are slower. Please install latest version of Xcode for best performance, and make sure it's set as default using xcode-select tool.

When I try to install XCode, I'm told I need to upgrade to MacOS 10.15.
I can't do this due to other software dependencies.
Is there a way to compile Metal shaders from the previous version of XCode somehow? If I can't install Metal, does it matter?


texts:
Is there someone who know/have an algorithm which can perform terrain triangulation like on the example image right under (there is a secondary image as well).

The reason I say "Dynamic" is because I want it to support Dynamic changes to the terrain, like if one was to dig into the ground or into the side of a mountain, then it should be capable of triangulating the new changes without destroying the old terrain which doesn't need changes.

Ignore the things like the trees, etc. This is only about the style of the terrain itself.

Click here for fullscreen picture
Secondary Image

I've tried using the Marching Cubes Algorithm, though it didn't give me that triangle'ish feeling, like in the image(s) above (While ignoring the normal rendering in my example).

Bottom Line

Does anybody know/have an algorithm, or any idea of how to...

Triangulate terrain so it have that style like in the above example image(s).
Support dynamic changes like Marching Cubes does, but with this triangle'ish style.

Note: All the "points" would be in an unsorted list, where the "points" of course is all the vertices, which should be used to generate all the triangles from.

  Disclaimer: I usually answer and sometimes ask question on Stack Overflow, so if anything is wrong with my question here I apologize, though comment and I will fix whatever is wrong.


texts:
I'm a newcomer to XNA, and I'm evaluating some libraries. The Hilva Graphics Engine looks interesting, and I'm trying to run their tutorials.  However, all of them give me errors.

For example, if I download the ParallaxMappingSample demo, and try to build it, I get

Error   1   Error loading pipeline assembly "C:\Users\Me\Desktop\ParallaxMappingSample\Hilva.Content.dll".  ParallaxMappingSample

I get similar errors for all of the samples.  Unfortunately, this error isn't very enlightening.  I can see the Hilva.Content.dll in the appropriate directory.  I tried removing and readding the reference from the content project, but I get the same error.

I'm not sure it's relevant, but I'm on Windows 7, I'm using Microsoft Visual Studio 2010, and XNA 4.0.

Is there an easy (or difficult) solution?

EDIT: If you happen to try this, even if you don't have a solution, let me know about it in a comment.  Whether it works for you, or if you get the same problem...either result would be something that might let me know if it's just a problem with the tutorial, or if it's on my end.


texts: Loading Texture2D is extremly slow on XBOX360

texts:
I have ~100 sprites for each level im my XNA game. On windows it takes ~2 seconds to load them all. Unfortunately on XBOX360 it takes ~30-60 seconds. Am i doing something wrong? Essentially the loading code ist just like this:

Texture2D sprite1 = levelContent.Load<Texture2D>("images/level_1/my_sprite_1");
...
Texture2D sprite100 = levelContent.Load<Texture2D>("images/level_1/my_sprite_100");

(i use an own content manager for each level to release all level-specific textures at once)
Of course i can reduse the ammount of sprites using a spritesheet, but it's extremly painfull for me now. Do i have a better option? And just curious - why is there such huge difference in image loading time?


texts: Help Decide between C#/XNA client or Java

texts:
The game runs on a client/server architecture currently setup for TCP, and the client code was built in AS3 to be web based.

What we're running into is 3 problems for the client.

AS3 has no hardware acceleration so we are having some issues with slowdown when implementing some features
TCP is really frustrating for a sidescroller when you're talking with a server. I'm having a heck of a time with the interpolation/extrapolation to make everyone else look smooth while minimizing lag. I would much rather be able to use UDP and throw in something similar to the age old Quake interpolation/extrapolation.
No right click

I work professionally with C#, and I did all my University (almost 2 years ago) with Java. Java really appeals to me because of the compatability while C# appeals to me because I've heard so much good about XNA and I love visual studio.

For a Client/Server based MMOish sidescroller in your opinion should I stick with AS3 and the TCP protocol, or should I abandon some of my audience, ramp up the graphics and hit C#, or journey back to the land of Java.

Thanks :D


texts:
Using Openfl for a game using hexagonal tiles

Working out the problem of walkability in a game, and I've run into an issue with my Hexagonal tiles.
I think it is an odd rounding error of sorts.  When heading down on the left side of tile, for a moment the nearest returns the coordinates of the tile on the right side. So the coordinates I get from the bellow nearest causes the "no walk" area for each unwalkable (water in this case) tile to be the area in red on this image.

public function nearest(pos:Point):Point
{
  var real_x:Float = pos.x + character.xOffset;
  var real_y:Float = pos.y + character.yOffset;
  var pos_y:Float = ((real_y + yOffset) / tileHeight)+1;
  var pos_x:Float = ((real_x  + xOffset - ( pos_y%2 * tileWidth/2) ) / tileWidth);
  return new Point(Math.round(pos_x),Std.int(pos_y));
}

For reference, this is how my map is laid out, later the map data will be read in from a file and not hard coded into the application.

public function createMap()
{
  map.push([0,0,0,0,0,0,0,3,0,0]);
  map.push([ 0,0,0,0,0,0,3,0,0,0]);
  map.push([0,0,0,0,0,0,3,0,0,0]);
  map.push([ 0,0,0,0,0,3,0,0,0,0]);
  map.push([0,0,0,0,0,3,0,0,0,0]);
  map.push([ 0,0,0,0,3,0,1,1,0,0]);
  map.push([0,0,0,0,3,0,1,2,1,0]);
  map.push([ 0,0,0,3,0,0,1,1,0,0]);
  map.push([0,0,0,3,0,0,0,0,0,0]);
  map.push([ 0,0,3,0,0,0,0,0,0,0]);

  walkMap.push([true,true,true,true,true,true,true,false,true,true]);
  walkMap.push([true,true,true,true,true,true,false,true,true,true]);
  walkMap.push([true,true,true,true,true,true,false,true,true,true]);
  walkMap.push([true,true,true,true,true,false,true,true,true,true]);
  walkMap.push([true,true,true,true,true,false,true,true,true,true]);
  walkMap.push([true,true,true,true,false,true,true,true,true,true]);
  walkMap.push([true,true,true,true,false,true,true,true,true,true]);
  walkMap.push([true,true,true,false,true,true,true,true,true,true]);
  walkMap.push([true,true,true,false,true,true,true,true,true,true]);
  walkMap.push([true,true,false,true,true,true,true,true,true,true]);

  tileData = [];
  for (row in 0...map.length)
  {
    for (cell in 0...map[row].length)
    {
      tileData = tileData.concat(
        [
          (tileWidth * cell + ((row%2) * (tileWidth/2))) - xOffset,
          (tileHeight * row) - yOffset,
          map[row][cell]
        ]
      );
    }
  }
}

What is causing the issue, where is my math off that I'm getting this odd effect?

Update:

The tile mapping from the above code should look like (realizing that I haven't taken the corners into account yet):

But instead look like:

They are not diagonal at all (like DMGregory suggests in his answer), the the top of them where the corners live is shifted by 1/2 a tile width, and I don't see why.

I could force the the tops to the right half a tile after (and that might be what I end up doing), but the code above should work, and I don't see where it is off by half a tile.

The bit DMGregory is doing at the bottom of his answer is what I was starting to work on to try and solve the corner problem (except the corners are at the top, not the bottom), when I realized what the shifting bug that's really going on really is.


texts: Waiting for object's Awake() after loading a new scene synchronously

texts:
I have a GameScene with an initially active GameObject in it, which has a singleton component:

public static ObjectiveManager Instance;

public void Awake()
{
    if (Instance != null && Instance != this)
    {
        Log.Info(this.GetType(), "Instance of this class already exists! CRITICAL");
    }

    ObjectiveManager.Instance = this;
}

Now, when I call:

private void StartGameScene(){
    SceneManager.LoadScene("GameScene");
    ObjectiveManager.Instance.SomeFunction(); // << singleton not initialized
}

I get an error, because ObjectiveManager is not set to an instance of an object.

As LoadScene is a synchronous operation so my guess was that Awake() is called immediately, synchronously. As I can see now, it's not.

Is there any way to determine that all of the objects on the scene have their Awake() already called, without checking each of them with some custom IsReady?


texts:
I have recently started using Java, but have been programming in javascript, and actionscript 3 for a while.

I am used to the language giving me the ability to simply do something like:

private function Update(){
//stuff
}

or something similar to that.

I am looking for something similar in Java, and I want to make sure I am doing it correctly.

I started following a tutorial, and they said to do something like this:

 long lastTime = System.nanoTime();
        double amountOfTicks = 60.0;
        double ns = 1000000000;
        double delta = 0;
        long timer = System.currentTimeMillis();
        int frames = 0;
        while(running){
            long now = System.nanoTime();
            delta += (now - lastTime) / ns;
            lastTime = now;
            while(delta >= 1){
                tick();
                delta--;
            }

            if(running)
                render();
            frames++;

            if(System.currentTimeMillis() - timer > 1000){
                timer += 1000;
                System.out.println("FPS: " + frames);
                frames = 0;
            }
        }

This seems to be every second calling the tick() function, not the same as every frame though, and while things tend to happen in less time than a second, I would much rather use the same old frame by frame method i was using. (Unless someone can give me a reason not to, always up for an opinion)

So I am wondering, why not just do something like:

while(running){
Update();
}

I believe this would call every frame. Am I doing something completely crazy here? is there a much better method?

Thanks in advance