texts: Problem animating in Unity/Orthello 2D. Can't move gameObject

texts:
I have a enemy npc that moves left and right in a corridor.
It's animated with 2 sprites using Orthello 2D Framework.

If I untick the animation's play on start and looping, the npc moves correctly.
If I turn it on, the npc tries to move but is pulled back to his starting position again and again because of the animation loop.
If I turn looping off during runtime, the npc moves correctly again.

What did I do wrong?

Here's the npc code if needed.

using UnityEngine;
using System.Collections;

public class Enemies : MonoBehaviour
{
    private Vector2 movement;
    public float moveSpeed = 200;
    public bool started = true;
    public bool blockedRight = false;
    public bool blockedLeft = false;
    public GameObject BorderL;
    public GameObject BorderR;

    void Update ()
    {
        if (gameObject.transform.position.x < BorderL.transform.position.x)
        {
            started = false;
            blockedRight = false;
            blockedLeft = true;
        }
        if (gameObject.transform.position.x > BorderR.transform.position.x)
        {
            started = false;
            blockedLeft = false;
            blockedRight = true;
        }

        if(started)
        {
            movement = new Vector2(1, 0f);
            movement *= Time.deltaTime*moveSpeed;
            gameObject.transform.Translate(movement.x,movement.y, 0f);
        }
        if(!blockedRight && !started && blockedLeft)
        {
            movement = new Vector2(1, 0f);
            movement *= Time.deltaTime*moveSpeed;
            gameObject.transform.Translate(movement.x,movement.y, 0f);
        }
        if(!blockedLeft && !started && blockedRight)
        {
            movement = new Vector2(-1, 0f);
            movement *= Time.deltaTime*moveSpeed;
            gameObject.transform.Translate(movement.x,movement.y, 0f);
        }
    }
}


texts: Creating a glitch effect similar to Watch Dogs

texts:
I'm currently working on a LibGDX game. When a user does something wrong, I would like all the graphics on the screen to jitter very similar to the glitch/distort effect seen in the game Watch Dogs (See Below).

My question is this: can this effect be achieved in real time by writing a shader? If so are there any references online on how to do this? (I've had a quick Google but all I could find is how to achieve this effect in Photoshop/After Effects).

Thank you for your help.

Screen jitter: https://www.youtube.com/watch?v=EYkqC9uI8Nc

Text glitch effect: https://www.youtube.com/watch?v=Wj26Wp2AH-U


texts: How do I draw an object that I always want to appear in the same place on screen on a scrolling orthographic camera using lib gdx?

texts:
So I want to make an endless scroller game and the orthographinc camera is scrolling downward so i want the character to stay with the camera. I'm not sure how to aproach this i've been looking a lot online but couldn't find anything that works. The 2 ways I thought about doing it is to either make the object scroll at the same speed as the camera or in someway draw the object on the cameras "graph". This is the first game i'm making with libgdx so any help or suggestions are appreciated. :) Thanks

This is the gamescreen:

package com.ounceoftech.mygame;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector3;

public class GameScreen implements Screen
{
 OrthographicCamera camera;
 SpriteBatch batch;
 Vector3 touch;
 ship ship;
 Game game;

 public static int ship_x = 540 - 26;

 public GameScreen(Game game)
 {
    this.game = game;
    camera = new OrthographicCamera();
    camera.setToOrtho(false, 1080, 1920);
    batch = new SpriteBatch();
    touch =new Vector3();
    ship = new ship();
 }
 @Override
 public void render(float delta)
 {
    Gdx.gl.glClearColor(255F, 255F, 0F, 1F);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    camera.position.y -= 5;
    camera.update();
    generalUpdate(touch, camera);
    batch.setProjectionMatrix(camera.combined);
    batch.begin();
    //Rendering Code
    batch.draw(ship.image, ship_x, ship.bounds.y);
    batch.end();
 }
 public void generalUpdate(Vector3 touch, OrthographicCamera camera)
 {
    ship_x -= Gdx.input.getAccelerometerX() * 2;
    if(ship_x < 0) { ship_x = 0; }
    if(ship_x > 1027) { ship_x = 1027; }
 }
}

This is the object/player:

package com.ounceoftech.mygame;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector3;

public class ship
{
 public TextureRegion image;
 public Rectangle bounds;

 public ship()
 {
   image = Assets.spriteShip;
   bounds = new Rectangle(GameScreen.ship_x, 1600, 53, 256);
 }
}


texts: Clamping the camera isn't so smooth when moving the camera around. Is there a way to make the clamping smoother?

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

public class CamerasManager : MonoBehaviour
{
    public CinemachineFreeLook playerCameraCloseLook;
    public CinemachineFreeLook playerCameraGameplayLook;
    public float timeBeforeSwitching;
    public float clampMin;
    public float clampMax;
    public float pitch;
    public float speed;

    private float brainBlendTime;

    // Start is called before the first frame update
    void Start()
    {
        brainBlendTime = Camera.main.GetComponent<CinemachineBrain>().m_DefaultBlend.m_Time;

        StartCoroutine(SwitchCameras(timeBeforeSwitching));
    }

    // Update is called once per frame
    void LateUpdate()
    {
        if (playerCameraGameplayLook != null)
        {
            pitch += speed * Input.GetAxis("Mouse Y");
            pitch = Mathf.Clamp(pitch, clampMin, clampMax);
            playerCameraGameplayLook.GetRig(1).GetCinemachineComponent<CinemachineComposer>().m_TrackedObjectOffset.y = pitch;
        }
    }

    IEnumerator SwitchCameras(float TimeBeforeSwitching)
    {
        yield return new WaitForSeconds(TimeBeforeSwitching);

        playerCameraCloseLook.enabled = false;
        playerCameraGameplayLook.enabled = true;

        PlayerLockManager.PlayerLockState(false);

        StartCoroutine(BlendTime());
    }

    IEnumerator BlendTime()
    {
        yield return new WaitForSeconds(brainBlendTime);

        PlayerLockManager.PlayerLockState(true);
    }
}

I can look around up down left right using Cinemachine CinemachineFreeLook but when using the clamping in this script and then when moving the camera around with the mouse it looks like the camera is a bit stuttering/jittering.
Without the clamping, in the LateUpdate the camera will work fine but then I can't move the camera up down left right only to the left and right.
The reason I'm trying to do the clamping on my own is that in the FreeLookCamera in the Axis Control > Y Axis if I set the speed to 100 or 300 when I move the camera up and down it will also zoom in/out on the player and I don't want that zooming but there is no option to remove/disable the zooming.


texts: Unreal Engine 4.18 - Knife (Weapon) collides with character capsule collision

texts:
I have a character and he has a knife in his hand. When Run / Walk action happens hands move and so does knife, its collision collides with character's capsule collision and causes issue in movement.

More info:
Component Hierarchy looks like


texts:
In my 2D game I have TileSet class that loads the texture and creates Rectangle[] array which stores each tile coordinates. Pretty basic stuff. Now I'd like to also calculate and store the average color of each tile. How do I do that in XNA/C#?

My goal is to tint the tile with the color based on its value when highlighted. Or maybe there is some other way to achieve similar effect?


texts: Unity look at rotation on one axis only problem

texts:
Hey I would like an object to look at another object only at one axis, when I rotate the white cube all around the gray cube (gray has look at script), the gray cube flips as soon as the target passes the middle and is on the right side. How can I fix this, so that rotation is normal.

Below is when the cube (target, white).

Below is what happens when the cube (target) passes on the other side, as you can see by the texture the gray cube flips horizontally.

Below is how it should be (texture shows difference)

Code:

    Quaternion lookAngle = Quaternion.LookRotation(targetPos, Vector3.up);

Thanks in advance!


texts: Directx: HLSL Texture based height map. (Shader 5.0)

texts:
I'm trying to implement a GPU based height map the simplest (and fastest) way that I know how. I passed a (.png, D3DX11CreateShaderResourceViewFromFile()) texture into the shader, and I'm attempting to sample it for the current pixel value. Seeing a float4, I'm currently assigning a color value from a channel to offset the y value.
Texture2D colorMap : register(t0);
SamplerState colorSampler : register(s0);

...

VOut VShader(float4 position : POSITION, float2 Texture : TEXCOORD0, float3 Normal : NORMAL)
{
    VOut output;

    float4 colors = colorMap.SampleLevel(colorSampler, float4(position.x*0.001, position.z*0.001, 0,0 ),0);
    position.y = colors.x*128;

    output.position = mul(position, WVP);
    output.texture0 = Texture;
    output.normal = Normal;

    return output;
}

The texture is imported correctly, and I've inserted another texture and was able to successfully blend the texture with another texture (through multiplication of values), so I know that the float4 struct contains values of a sort capable of having arithmetic performed on it.
In the Vertex function, attempting to extract the values yields nothing on a grid:

The concept seemed simple enough on paper...


texts: Finding distances between sprites in an array

texts:
i'm new to java and was hoping if anyone can help me out. So my game has meteors which spawns off screen and sometimes as they spawn, they overlap each other which I don't want. I want them to spawn from a certain distance from each other.

From pseudo code I know what I want which is to find the centre point of sprite, find other meteors on screen and calculate the distance and then spawn from a certain distance from each other. I know the distance to point formula (distance = Math.sqrt(Math.pow(x2 - x1, 2) + (Math.pow(y2 - y1, 2)));), but how do I do that within an array. Here is my code so far:

Meteor Class

public class Meteors {
    private Texture bigMeteor;
    private Vector2 posBigMeteor;
    private Random yrand;

    //Constructor
    public Meteors(float x){
        bigMeteor = new Texture("meteor.png");
        yrand = new Random();

        //Spawn location of meteor
        posBigMeteor = new Vector2(x, yrand.nextInt(AstroDemo.HEIGHT/2 - bigMeteor.getHeight()));
    }

    public Texture getBigMeteor() {
        return bigMeteor;
    }

    public Vector2 getPosBigMeteor() {
        return posBigMeteor;
    }

    public void reposition(float x){
        posBigMeteor.set(x, yrand.nextInt(AstroDemo.HEIGHT/2 - bigMeteor.getHeight()));
    }
}

Playstate Class

public class PlayState extends State {
    //Total meteor count on screen
    private static final int METEOR_COUNT = 8;

    private Naught naught;
    private Texture bg;
    private Random xrand;
    private Array <Meteors> meteors;

    public PlayState(GameStateManager gsm) {
        super(gsm);
        //Starting co-ordinates of main character (Naught)
        naught = new Naught(50, 100);
        //Setting viewport of the camera
        cam.setToOrtho(false, AstroDemo.WIDTH/2, AstroDemo.HEIGHT/2);
        bg = new Texture("bg.png");
        xrand = new Random();

        meteors = new Array <Meteors>();

        //Spawn meteors randomly off screen
        for (int i = 1; i <= METEOR_COUNT; i++){
            meteors.add(new Meteors(AstroDemo.WIDTH/2 + (xrand.nextInt(300))));
        }
    }

    @Override
    protected void handleInput() {
        //If screen/mouse is held
        if(Gdx.input.isTouched()){
            //Main Character jumps/flys
            naught.jump();
        }
    }

    @Override
    public void update(float dt) {
        handleInput();
        naught.update(dt);
        //If meteors are left side of the screen, re-position to the right side of the screen
        for(Meteors meteor : meteors){
            if (cam.position.x - (cam.viewportWidth/2) > meteor.getPosBigMeteor().x + meteor.getBigMeteor().getWidth()){
                meteor.reposition(meteor.getPosBigMeteor().x + (AstroDemo.WIDTH/2 + 20 + (xrand.nextInt(300))));
            }
       }
        cam.position.x = naught.getPosition().x + 80;

        cam.update();
    }

    @Override
    public void render(SpriteBatch sb) {
        //Adjust the spritebatch for co-ordinate system in relation to camera
        sb.setProjectionMatrix(cam.combined);
        sb.begin();
        //Draw background where the camera is
        sb.draw(bg, cam.position.x - (cam.viewportWidth/2), 0);
        sb.draw(naught.getTexture(), naught.getPosition().x, naught.getPosition().y);
        for (Meteors meteor : meteors) {
            sb.draw(meteor.getBigMeteor(), meteor.getPosBigMeteor().x, meteor.getPosBigMeteor().y);
        }
        sb.end();
    }

    @Override
    public void dispose() {

    }
}


texts:
I am wanting to add a button to my scene in order to mute/unmute music.  I can add the button to my scene, but it's not appearing on the UI.  I can't see it anywhere, not on the scene nor the game when running.

Below is a screenshot of the editor.  You can see the button in front of the camera and in front of the scene itself, but it doesn't appear.  I can't actually see a button, just a 'move' control'.

Things I have tried:

Changing the 'Layer' of the button to default
Adjusting the z-axis (I've tried 0, +1-5, -1-5)
Giving the Image (Script) a material inside the Inspector

The button has text, which isn't visible either.

I could create a sprite and do a raycast, but that seems like overkill just to do a simple click action.

Any ideas?


texts: How can I simulate a rigid body bounced from a wall in 3D world?

texts:
How can I simulate a rigid sword bounced from a wall and hit the ground (like in physical world)?

I want to use this for a simple animation. I can detect the figure and the size of the sword (maybe needed in doing bounce). Rotation can be controlled by quaternions/matrix/euler angles. It should turn the head and do rotations and fly to the ground.

How can I simulate this physical process?

Maybe what I need is an equation and some parameters?

I need these data, and would combine them into my movie file, I use Mathematica to do the thing that generate the movie file(If I have the data, I can also export it into a 3DSMax script for example).


texts: How to display a tile map from a 2D array in JavaScript?

texts:
I have stored my map, but the problem I am having is displaying it. My map is 100x100 tiles which are 40x40px.

I have my loop running through the array but I'm having difficulty selecting the portion of the map image to relate to the tiles. This is the code which selects the portion of the image on each iteration:

var sx = Math.floor(tileId % 8 * tileWidth); //source x
var sy = Math.floor(tileId / 8 * tileHeight); //source y

I'm using Canvas and keep getting this error message:

INDEX_SIZE_ERR: DOM Exception 1: Index or size was negative, or greater than the allowed value.

I'm guessing the remainder or division by 8 is wrong, this is something I picked up from the net, but what exactly does that integer need to be?

Thanks


texts: Unity2D - move rigidbody object with collision

texts:
How do I move and collide my object (position given by touch or click), by Using rigidBody2D.MovePosition i can only teleport my character, and by using velocity, my character keeps moving, I want him to stop at the position given

Ilustrations:


texts:
Is it possible to build corona applications from console?
Or how can I automate build process?


texts: what is the best way to eliminate grinding in games?

texts:
This is a very persistent question in game design, especially in games where you need to hold/retain players like MMO or social games. (On a side note grinding can easily calculated so its easy tool for engagement and timed progression).

The question other than community building/competition are there solutions that can replace grinding and still hold your audience for certain period of time (without adding large amounts of game assets and code)?


texts: How to Handle frame rates and synchronizing screen repaints

texts:
I would first off say sorry if the title is worded incorrectly.

Okay now let me give the scenario

I'm creating a 2 player fighting game, An average battle will include a Map (moving/still) and 2 characters (which are rendered by redrawing a varying amount of sprites one after the other).

Now at the moment I have a single game loop limiting me to a set number of frames per second (using Java):

Timer timer = new Timer(0, new AbstractAction() {

    @Override
    public void actionPerformed(ActionEvent e) {
        long beginTime; //The time when the cycle begun
        long timeDiff; //The time it took for the cycle to execute
        int sleepTime; //ms to sleep (< 0 if we're behind)
        int fps = 1000 / 40;

        beginTime = System.nanoTime() / 1000000;

        //execute loop to update check collisions and draw
        gameLoop();

        //Calculate how long did the cycle take
        timeDiff = System.nanoTime() / 1000000 - beginTime;

        //Calculate sleep time
        sleepTime = fps - (int) (timeDiff);

        if (sleepTime > 0) {//If sleepTime > 0 we're OK
                ((Timer)e.getSource()).setDelay(sleepTime);
        }
    }
});
timer.start();

in gameLoop() characters are drawn to the screen ( a character holds an array of images which consists of their current sprites) every gameLoop() call will change the characters current sprite to the next and loop if the end is reached.

But as you can imagine if a  sprite is only 3 images in length than calling gameLoop() 40 times will cause the characters movement to be drawn 40/3=13 times. This causes a few minor anomilies in the sprited for some charcters

So my question is how would I go about delivering a set amount of frames per second in when I have 2 characters on screen with varying amount of sprites?


texts:
I have a game and want to reward the user for going on every day. I want to be able to get the true date somehow. I do not want the device date, because the user could just change it and get free rewards. Is there a way for me to access the true date from apple time or something like that?

Thanks


texts: Calculate edge loop from plane intersection

texts:
This is a fairly complex question, so please bear with me.

I'm attempting to calculate an edge loop based on the intersection of a plane with a mesh, bounded by a sphere.

Here is a mockup of what the expected result might look like:

The black lines represent the intersected mesh, the orange line the result. Blue and cyan lines are vertex and face normals, respectively. The sphere origin would be somewhere inside the mesh. The orange vertices and sphere origin would also be coincident with the plane. Note that the edge loop is not part of the mesh. This is not a mesh split - just a list of vertices forming a loop along it.

Faces included in the edge should be pointed toward the sphere origin side, and any islands should be ignored (greedy), as shown in this mock up:

In the event that a closed loop cannot be found, the function should return null or an empty array.

I'm working on this in Unity, so I will use its API to further illustrate. The signature I expect to use looks like this:

Vector3[] CalculateCorridorLoop(Vector3 planeNormal,
                                Vector3 origin,
                                float radius,
                                MeshFilter meshSource)

So far...

I've tried a few different approaches, but I'm now leaning toward a more brutal approach. To come up with those mockups I simply used Blender's knife tool, duplicated the edge loop, and then dissolved the edges on the mesh. If I could calculate an edge loop for every face intersecting the plane then project the edges and origin into 2D space using the plane, it simply becomes a problem of finding the outermost loop containing the origin, which is itself contained by the circle.

Of course I get the feeling I've spent so much time on this I've overthought it and missed something simpler - although even that doesn't seem very straightforward. I think I'd need to keep track of which edges belong to which triangles to keep track of which vertex goes with which loop.

I found this paper, Fast Algorithm To Split And Reconstruct Triangular Meshes, which also uses planes for splitting, but seems to integrate the vertices into the mesh as it goes - whereas I just want the resulting edge loops. Though it's entirely possible I'm reading it wrong.


texts:
I have some trouble with my GestureListener class i think. I'm just trying to detect swipe on two half screen. I'm creating two InputListener but I can't add them to InputMultiplexer. Actually, I added with no trouble but it is not working as how I wanted. How can I detect two swipe(fling or pan whatever) events simultaneously ?

Maybe this picture will help you that you understand it.

EDIT : It's from my Player1 class and the other class' contents are the same. (Player2)

private void listenInputs() {

    inputProcessor = new InputProcessor() {

        @Override
        public boolean keyDown(int keycode) {
            return false;
        }

        @Override
        public boolean keyUp(int keycode) {
            return false;
        }

        @Override
        public boolean keyTyped(char character) {
            return false;
        }

        @Override
        public boolean touchDown(int screenX, int screenY, int pointer, int button) {
            if (canMove) {
                lastTouch.set(screenX, screenY);
                firstD = screenX;
            }
            return true;
        }

        @Override
        public boolean touchUp(int screenX, int screenY, int pointer, int button) {
            canMove = true;
            distance= 0;
            return true;
        }

        @Override
        public boolean touchDragged(int screenX, int screenY, int pointer) {

            Vector2 newTouch = new Vector2(screenX, screenY);
            distance = screenX - firstD;

            if (firstD < CarcleGame.HALF_SCREEN) {
                if (Math.abs(distance) > 20) {
                    if (canMove) {
                        canMove = false;
                        Vector2 delta = newTouch.cpy().sub(lastTouch);
                        if (delta.x > 0.7f)
                            move(true); // if it's true then go to the direction right, else go left
                        else if (delta.x < -0.7f)
                            move(false);

                        lastTouch = newTouch;
                    }
                }
            }
            return true;
        }


texts: Efficient way to compare vectorial direction?

texts:
I have a bunch of random vectors representing a direction and four other vectors that we can distinguish with their pyramidal arrows at their extremity, they represent a boundary
what i'd like to do is figure out which vectors are within the given boundaries,
how can I do that?
How can I compare them to filter them properly so the only one selected are vectors within the four boundary direction
I have as info:
directional vector / XYZ Euler angle


texts:
I’m using official admin plugin for Unity implementing Reward video.

But it’s only working for test unit id, when I replacing it to my own unit id, it just failing load by error “No Fill”.

Even when I add test device, still happening the issue.

How can I fix this?


texts: Is it possible to make model in Blender, with enabled GLSL, add multiple textures, etc, and then just load it in XNA, where's own HLSL? Will it work?


texts:
I know how to set Image width and height using pixel coords. Is there a way to set relative coords? I want to deal with multiple screens.

For example i have 1920x1080 screen size. And i have relative coords width (-100,100) and height = 200*1080/1920=112.5, height(-56.25, 56.25)

Can i use this relative coords to set width and height? and how to do it?
Is there any best practices to handle different screens ratio, handle orientation change correctly?

thanks in advance.

here is how i'm using it in my app:

create()

    public void create() {
         stage = new Stage();
            Gdx.input.setInputProcessor(stage);

            camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
            camera.setToOrtho(true, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
            camera.update();

Skin skinBackground = new Skin();
        skinBackground.add("background", new Texture(Gdx.files.absolute(FilePathSlicer.preparePath(taskSheet.background.getPicUrl()))));
        background=new Image(skinBackground,"background");

        if(background!=null) {
            background.setWidth(width);
            background.setHeight(height);
            stage.addActor(background);
        }
    }

render

public void render() {
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        Gdx.gl.glClearColor(255/255f, 255/255f, 255/255f, 1);
        stage.getBatch().setProjectionMatrix(camera.combined);
        stage.act(Gdx.graphics.getDeltaTime());
        stage.draw();
    }


texts: How to pitch, yaw, roll, an object like a flight simulator in OpenGL?

texts:
I'm working on a college Graphics project using LWJGL (OpenGL in Java).  I've done most of the scene but I got a problem in figuring out the jet's orientation.

Here's how I tried it at the very beginning:     (After translate it to the desired position)

        GL11.glRotatef(xRotation, 1, 0, 0);
        GL11.glRotatef(yRotation, 0, 1, 0);

Then I found the I came across the gimbal lock problem? For example: the jet roll 90 degrees to the right, then it pitch up so that it will make a right turn.  But if I pitch up 90 degrees first, then roll at some angle, it look like it's Yawing ! It's still rotate along the original X-axis.
Roll -> Pitch looks fine.
But Pitch -> Roll looks BAD.

Then I tried another way:

        GL11.glRotatef(xRotation, 1, 0, (float)Math.tan(Math.toRadians(-yRotation)));
        GL11.glRotatef(yRotation, 0, 1, 0);

This time the problem actually inverses! The case I just described is inversed.
Roll -> Pitch looks BAD.
But Pitch -> Roll looks fine.

I can't even imagine what might happen when I add the Yaw Rotation into this.

The jet should be able to orient at any direction and Roll,Yaw,Pitch should not interfere with each other

I've done lot of research, it appears to me that I have to aggregate the Roll-Pitch-Yaw  3 rotations into one which is represented by Quaternions. But I'm really confused about the term. If someone has experience in doing a similar work plz give me some hints(examples are much appreciated!), I'm really really frustrated by this. Thank you !


texts: How can I measure the velocity of a drag gesture?

texts:
I want to measure the velocity of a drag(FreeDrag, VerticalDrag, HorizontalDrag) gesture on my Windows Phone. For example, if the measured velocity of a drag is 40 km/h, the player will shoot a bullet in the dragging direction that flies with 40 km/h.

How can I measure the velocity of a drag gesture on my Windows Phone?

Update:
I don't know how to measure the time. Is it possible to do it without touchCollection or should I use touchCollection to determine the StartTime and the EndTime?

I'm not sure if I need the touchCollection block. In addition, I'm not sure if I can use two different types, TimeSpan for StartTime and DateTime for EndTime.

What is the best way to measure the time?

TimeSpan StartTime;
DateTime EndTime;
TouchPanel.EnabledGestures = GestureType.FreeDrag;
protected override void Update(GameTime gameTime)
{
 TouchCollection touchCollection = TouchPanel.GetState();
 foreach (TouchLocation tl in touchCollection)
 {
   GestureSample gs = TouchPanel.ReadGesture();
    if ((tl.State == TouchLocationState.Pressed))
    {
     StartTime = gs.Timestamp;
     }
    if ((tl.State == TouchLocationState.Released))
    {
     EndTime = DateTime.Now;
     }
  }

    while (TouchPanel.IsGestureAvailable)
    {
    GestureSample gs = TouchPanel.ReadGesture();
       switch (gs.GestureType)
        {
          case GestureType.FreeDrag:
               StartTime = gs.Timestamp;
           break;
         }
     }
        base.Update(gameTime);
 }


texts: How do I ensure my Android build is not darker than in Editor?

texts:
My scene on the Android Build looks much darker. Based on my research about the  topic, and from the texture of the light on the spheres, I assume it is because the light uses per vertex render mode on Andriod.

I am trying to force per pixel render on Android, these are the things I have tried:

set the Rendering to Important of the Light on the scene (There is only 1 directional)
check the values of my RenderPipeline asset (the one came with the LWRP Template project), the Main light is Per Pixel, Additional Light (which doesn't seem to matter) is also Per Pixel
set the Preset Light's Render type to Important in the Preset Manager

I will have infinite levels, the map changes dynamically, so Baking the light is not an option.

Can I achieve this somehow? Or at least force my editor to use per pixel so I can light up my scene more intuitively.


texts: how to use unity3d webgl content in a asp.net mvc view?

texts:
I asked this question in stackoverflow but no answers so I think it would fit here better.

I have a unity webgl project and an asp.net mvc project.

I need to show the webgl content in a view.

The first thing that came to my mind was to simply copy the content of the index.html that unity gave me and paste it in a .cshtml file and change the addresses. But when I do this the incorrect header error pops up.

Am I doing some thing wrong or everything wrong. should I change my method entirely?

I also added these file extensions to the web.config

<staticContent>
  <!-- Unity 5.x -->
  <remove fileExtension=".mem" />
  <mimeMap fileExtension=".mem" mimeType="application/octet-stream" />
  <remove fileExtension=".data" />
  <mimeMap fileExtension=".data" mimeType="application/octet-stream" />
  <remove fileExtension=".memgz" />
  <mimeMap fileExtension=".memgz" mimeType="application/octet-stream" />
  <remove fileExtension=".datagz" />
  <mimeMap fileExtension=".datagz" mimeType="application/octet-stream" />
  <remove fileExtension=".unity3dgz" />
  <mimeMap fileExtension=".unity3dgz" mimeType="application/octet-stream" />
  <remove fileExtension=".jsgz" />
  <mimeMap fileExtension=".jsgz" mimeType="application/x-javascript; charset=UTF-8" />
</staticContent>


texts: Attached objects to public Text removed on play mode (Unity)

texts:
As you can see when I play the game the 'touch anywhere to start' object goes away. How do I fix this?

I have added all the relevant code


texts: Rendering issues in Monogame when using shaders

texts:
I am currently fiddling with Monogame, trying to work with Shaders and I have encountered a really weird issue. If the first ever draw in the application's lifetime is with a custom shader all further draws without a custom shader get this red tint (as if blue and green channels were set to 0):

(A is the correct one, the sprite is white and black)

The following code produced these:

spriteBatch.Begin(); // Use this for A
//spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, Gfx.MyShader); // Use this for B
spriteBatch.Draw(Gfx.PlayerStand2, new Vector2(10, 10));
spriteBatch.End();
spriteBatch.Begin();
spriteBatch.Draw(Gfx.PlayerStand2, new Vector2(50, 50));
spriteBatch.End();
spriteBatch.Begin();
spriteBatch.Draw(Gfx.PlayerStand2, new Vector2(80, 80));
spriteBatch.End();

And this is the shader:

sampler TextureSampler : register(s0);

float4 PixelShaderFunction(float2 texCoord : TEXCOORD0) : COLOR0
{
    return tex2D(TextureSampler, texCoord);
}

technique Shader1
{
    pass Pass1
    {
        PixelShader = compile ps_2_0 PixelShaderFunction();
    }
}

It all depends on the first draw - if I replace the first two lines with this:

counter++; // Starts at 0
if (counter == 1){ // Run only on the first draw
    spriteBatch.Begin(SpriteSortMode.Immediate, null, null, null, null, Gfx.GaussianBlur);
} else {
    spriteBatch.Begin();
}

They all become red. If I replace == with != they all display correctly.

I am using OpenGL for rendering. I am aware I could circumvent this problem by always using a custom shader but I fear that this is but a symptom of a greater issue that will come later to bite my bottom. Or hopefully something completely trivial that I missed.

Update: I tried to reproduce it in DirectX version and in this case the batch with the shader does not render, but the other sprites are not red.
I also tried to compile the files via Monogame Pipeline with the same effect.


texts:
I've made a tiledrawer, which takes a list of sprites, and then randomly picks one of those sprites, and draws it in a 2D grid.

This works, but I have a feeling I'm not doing it the right way. When the camera moves over the area, the tiles look choppy.

My code for the generator:

public GameObject tileType;
public Sprite[] sprites;
private Grid grid;
public int gridRadius = 100;

// Start is called before the first frame update
void Start()
{
    if (sprites == null || sprites.Length == 0)
    {
        return;
    }
    var tileSize = 0.5f;
    var tileScale = 1.56f;

    var half = gridRadius / 2;
    var beginX = half * tileSize * -1;
    var beginY = half * tileSize * -1;

    var beginOffset = new Vector3(beginX, beginY, 0);

    grid = GameObject.FindObjectOfType<Grid>();
    var offset = new Vector3(0.25f, 0.25f, 0) + beginOffset;

    for (int x = 0; x < gridRadius; x++)
    {
        for (int y = 0; y < gridRadius; y++)
        {
            var tileOffset = offset + new Vector3(tileSize * x, tileSize * y, 0);

            var tile = Instantiate(tileType, transform.position + tileOffset, Quaternion.identity, grid.transform);
            tile.transform.rotation = transform.rotation;

            var renderer = tile.GetComponent<SpriteRenderer>();
            tile.transform.localScale = new Vector3(1.5f, 1.5f, 0);
            renderer.transform.localScale = new Vector3(tileScale, tileScale, 0);
            renderer.sprite = RandomSprite();
        }
    }

}

private Sprite RandomSprite()
{
    var rand = Random.Range(0, sprites.Length - 1);
    return sprites[rand];
}

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

}

When I say "choppy", I mean the tiles sometimes generates lines between them, sometimes not, even though there is not space between them.

What is the right way of drawing a grid of tiles, from a list of sprites?


texts: Can an existing game be optimised by converting it to use cel-shading?

texts:
I assume it's possible to cel-shade existing games through API interception. If done properly, could this be used as a rendering optimization technique?

This means rather than doing the cel-shading on the pixel shader stage, do a few steps on the vertex side, such as reducing geometry, and lightning complexity.


texts:
I have a memory issue after disposing all my D3D objects and lastly disposing the device. I want to free all memory and, depending on user interaction, creating a new device, but removing all memory footprint of the old device.

I traced down some Disposing issues I had to only have this left, right at the line at disposing the device:

I get this by calling:

mDevice.QueryInterface<DeviceDebug>().ReportLiveDeviceObjects(ReportingLevel.Summary)

I understand that that the DeviceDebug interface I receive to get this debug information increases the Refcount of the ID3D11Device by +1. So it should be 2 references left.

Now I wonder if I need to track down this last reference (the 2nd) in order to get the device fully released after I call .Dispose(). Or if this is a internal refernece that is handled for me.

The issue is, that I don't know how to check for remainding objects after the device disposing. I get no warnings about active objects in output anymore, them I fixed already.

My memory grows linearly by about ~15MB each creation and destruction of my window (not closing the application, just the part that needs a device).

Any help appreciated!


texts: How do I load graphical resources asynchronously?

texts:
Let's think platform-agnostic: I want to load some graphical resources while the rest of the game is running.

In principle, I can load the actual files on a separate thread, or using async I/O. But with graphical objects, I will have to upload them to the GPU, and that can (usually) only be done on the main thread.

I can change my game loop to look something like this:

while true do
    update()
    for each pending resource do
        load resource to gpu
    end
    draw()
end

while having a separate thread load resources from disk to RAM.

However, if there are many big resources to load, this could cause me to miss a frame deadline and eventually get dropped frames. So I can change the loop to this:

while true do
    update()
    if there are pending resources then
        load one resource to gpu
        remove that resource from the pending list
    end
    draw()
end

Effectively loading only one resource per frame. However, if there are many small resources to load, loading all of them will take many frames, and there will be a lot of wasted time.

Optimally, I would like to time my loading in the following manner:

while true do
    time_start = get_time()
    update()
    while there are pending resources then
        current_time = get_time()
        if (current_time - time_start) + time_to_load(resource) >= 1/60 then
            break
        load one resource to gpu
        remove that resource from the pending list
    end
    draw()
end

This way, I would only load a resource if I can do it within the time I have for that frame. Unfortunately, this requires a way to estimate the amount of time it takes to load a given resource, and as far as I know, there are usually no ways to do this.

What am I missing here? How do many games get to load all their stuff completely asynchronous and without dropped frames or extremely long loading times?


texts: How to access a variable from another script in Unity c#

texts:
I need to access a variable from another script in Unity, but I can't figure it out.
Script:

public class move : MonoBehaviour {
public float speed;
// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    transform.position += Vector3.left * Time.deltaTime * speed;
}

}

I want to access the variable speed in another script, but I can't. Any help will be appreciated :)


texts: How to determine depth of a pixel perfect collision

texts:
I am trying to figure out how to determine the depth of a pixel perfect collision in XNA.  I want to know the depth in order to be able to use it in my collision response.

At the moment I have the following code, that provides me with a working pixel perfect collision detection:

public static bool IntersectPixels(Matrix transformA, int widthA, int heightA, Color[] dataA, Matrix transformB, int widthB, int heightB, Color[] dataB)
{
    Matrix transformAToB = transformA * Matrix.Invert(transformB);

    Vector2 stepX = Vector2.TransformNormal(Vector2.UnitX, transformAToB);
    Vector2 stepY = Vector2.TransformNormal(Vector2.UnitY, transformAToB);

    // Calculate the top left corner of A in B's local space
    // This variable will be reused to keep track of the start of each row
    Vector2 yPosInB = Vector2.Transform(Vector2.Zero, transformAToB);

    // For each row of pixels in A
    for (int yA = 0; yA < heightA; yA++)
    {
        // Start at the beginning of the row
        Vector2 posInB = yPosInB;

        // For each pixel in this row
        for (int xA = 0; xA < widthA; xA++)
        {
            // Round to the nearest pixel
            int xB = (int)Math.Round(posInB.X);
            int yB = (int)Math.Round(posInB.Y);

            // If the pixel lies within the bounds of B
            if (0 <= xB && xB < widthB && 0 <= yB && yB < heightB)
            {
                // Get the colors of the overlapping pixels
                Color colorA = dataA[xA + yA * widthA];
                Color colorB = dataB[xB + yB * widthB];

                // If both pixels are not completely transparent,
                if (colorA.A != 0 && colorB.A != 0)
                {
                    // then an intersection has been found
                    return true;
                }
            }

            // Move to the next pixel in the row
            posInB += stepX;
        }

        // Move to the next row
        yPosInB += stepY;
    }

    // No intersection found
    return false;
}

How would I determine how deep the collision is into the dataB texture data?


texts: How to move the generated polygon horizontally in openGL?

texts:
I am trying to develop a small ball game in OpenGL where rectangular bars of random height is generated and moved towards left and there is a ball which should be moved up and down(like jump action) whenever mouse left button is pressed. I am generating the polygon pattern but the problem is the movement

What is the best way to move the rectangles(of random height) horizontally? (or any generated pattern preferably polygon from right to left.)

I tried code below for movement of a single rectangle but i am getting a blank screen

void move_polygon()
 {
    int px,py;
    px=randr(50,100);
    py=randr(100,600);
    float r,g,b;
    r=(float)(rand()%10);
    g=(float)(rand()%10);
    b=(float)(rand()%10);
    float rf=r/10,gf=g/10,bf=b/10;
    glColor3f(rf,gf,bf);
    for(int pos=800;pos<=0;pos-=10)
    {
        Sleep(200);
        glClear(GL_COLOR_BUFFER_BIT);
        glBegin(GL_POLYGON);
        glVertex2f(pos,0);
        glVertex2f(pos,py);
        glVertex2f(px+pos,py);
        glVertex2f(px+pos,0);
        glEnd();
        glFlush();
        Sleep(100);
    }
}


texts: Segmentation Fault using Allegro_Tiled, function al_open_map();

texts:
I have consistently segfaulted trying to load a TMX file into a *map.

int main(int argc, char *argv[])
{
    ALLEGRO_DISPLAY *display = NULL;
    ALLEGRO_EVENT_QUEUE *event_queue = NULL;
    ALLEGRO_TIMER *timer = NULL;
    ALLEGRO_KEYBOARD_STATE keyboard_state;
    ALLEGRO_MAP *map = al_open_map("data/maps", "TestMap.tmx");
...

Active debugger config: GDB/CDB debugger:Default
Building to ensure sources are up-to-date
Selecting target:
Debug
Adding source dir: /home/X/Desktop/Programming/C/AllegroRoboticsTest/
Adding source dir: /home/X/Desktop/Programming/C/AllegroRoboticsTest/
Adding file: /home/X/Desktop/Programming/C/AllegroRoboticsTest/bin/Debug/AllegroRoboticsTest
Changing directory to: /home/X/Desktop/Programming/C/AllegroRoboticsTest/.
Set variable: LD_LIBRARY_PATH=.:/usr/local/lib:/opt/opencascade/lib
Starting debugger: /usr/bin/gdb -nx -fullname -quiet  -args /home/X/Desktop/Programming/C/AllegroRoboticsTest/bin/Debug/AllegroRoboticsTest
done
Setting breakpoints
Debugger name and version: GNU gdb (GDB) 8.1
Program received signal SIGSEGV, Segmentation fault.
In al_get_standard_path () (/usr/lib/liballegro.so.5.2)
#2  0x00005555555563ba in main (argc=1, argv=0x7fffffffe3a8) at /home/X/Desktop/Programming/C/AllegroRoboticsTest/main.c:45

At first I thought, maybe I just didn't build the library right, so I rebuilt it 2 more times, once as a static and another as a shared library.

The interesting thing is that it builds just fine when using the cmake files that came in the example.

I cannot recreate it though.

This is the callback after I moved the open map command into it's usual place, directly from the example that comes with allegro_tiled.

// If MAP_FOLDER is relative to the working directory and not the running
// executable, then add a call to `al_find_resources_as(RELATIVE_TO_CWD);`
// before calling `al_open_map()`.
//al_find_resources_as(RELATIVE_TO_CWD);
map = al_open_map("data/maps", "TestMap.tmx");
int map_total_width = al_get_map_width(map) * al_get_tile_width(map);
int map_total_height = al_get_map_height(map) * al_get_tile_height(map);

// Draw the map
al_clear_to_color(al_map_rgb(0, 0, 0));
al_draw_map_region(map, map_x, map_y, screen_width, screen_height, 0, 0, 0);
al_flip_display();

   ...
   Setting breakpoints
   Debugger name and version: GNU gdb (GDB) 8.1
   Child process PID: 25749
   In ____strtoll_l_internal () (/usr/lib/libc.so.6)
   #3  0x0000555555556615 in main (argc=1, argv=0x7fffffffe3a8) at /home/X/Desktop/Programming/C/AllegroRoboticsTest/main.c:114


texts: viewing fbx files in windows via xna 4.0

texts:
I've made some models in Blender and exported them in Autodesk fbx format.  I'm trying to view them using XNA 4.0 Refresh.

Loading them isn't much an issue, but I'm not familiar enough with XNA 4.0 to, well basically I want to load in the model at say the origin (0,0,0) world coordinates, and then rotate and/or zoom the camera about the world coordinates origin as well so that I can test the model.  Typically the mouse, and maybe some arrow keys for zooming/rotating the camera.

Anyways, this seems like a simple task and I shouldn't have to re-invent this, isn't there a skeleton code somewhere for this kind of thing for XNA 4.0?  I couldn't find a solid example for this on the web.  I found a couple that seemed like they might work for xbox, but I'm trying to do this on windows only.

Anyways, just looking to be pointed in the right direction on this one, thanks.


texts: Dealing with edges on spherical heightmapped terrain

texts:
This is the problem I'm having: where the height has been applied to the vertex, the edge of each face has been pushed apart. I was wondering how I can best deal with this issue?

I read elsewhere that calculating the mean between the two adjacent edge vertices and applying to both will seal the gap, but wouldn't that cause some UV stretching?

Any advice would be great, Caius.


texts:
Many questions have been posted on this topic but I'm facing a weird behavior which I could not find an explaination for.

I perform a raycast giving it a LayerMask parameter which is defined as public variable and set in the inspector with thick on layer "Wall" and "Enemy".

At first glance it appeared to work fine because raycast rightly stops  on GameObjects with that layer.

But then I saw that it stopped also on GameObjects with default layer, like if the LayerMask was ignored. Is there something I'm missing?

According to this answer I set up everything correctly and I expected it to work fine.

Looking at the inspector at Runtime I can clearly see that my mask is set only to "Wall" and "Enemy", and that the GameObject the collider is attached to has default layer set. I'm then stating that the mask the way I'm using it does not exclude other layers. The only way I found to have this working is by setting that GameObject layer to Ignore Raycast but in this case the LayerMask is not necessary.

I'm calling the function this way:

RaycastHit2D inSight = Physics2D.Raycast(start, end, lm);

Maybe is there something different using Physics2D?
I would really enjoy touse LayerMasks instead of giving specifically Ignore Raycast to whatever I want to ignore. Any clue?


texts: My FollowPlayer script runs AWAY from the player?

texts:
With the script I'm using, it would make whatever model it was attached to, follow the player when they were close enough. Even though I have NOT updated to the newer version of Unity, the script isn't working how it used to.

While it does make the model face towards the player, it no longer follows/chases then and I have a suspicion that it may be because I am using rigidbody for the player controls instead of character controller (due to Character Controller no longer working after the latest Unity, which I did NOT update to)

Below is a copy of the script I'm using, which is super simple:

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

public class FollowPlayer : MonoBehaviour {

    //The target player
    public Transform Player;
    //At what distance will the enemy walk towards the player?
    public float walkingDistance = 10.0f;
    //In what time will the enemy complete the journey between its position and the players position
    public float smoothTime = 10.0f;
    //Vector3 used to store the velocity of the enemy
    private Vector3 smoothVelocity = Vector3.zero;

    //Call every frame
    void Update()
    {
        //Look at the player
        transform.LookAt(Player);

        //Calculate distance between player
        float distance = Vector3.Distance(transform.position, Player.position);

        //If the distance is smaller than the walkingDistance
        if (distance < walkingDistance)
        {
            //Move the enemy towards the player with smoothdamp
            transform.position = Vector3.SmoothDamp(
                transform.position,
                Player.position,
                ref smoothVelocity,
                smoothTime);
        }
    }
}

Any ideas why the model isn't chasing the player? I keep changing the settings to see if it's anything silly like that, but no matter what I put it, or what I do, the model just wants to stare but not follow or chase the player :/

Here's a screenshot of the hierarchy:

[

And the player model does have the player tag. No matter what values I put into the inspector for the FollowPlayer script, the model with the attached script will not move towards the player.

UPDATE: I figured out it was because the model with the script attached didn't have a rigidbody component. The problem now is, the model runs away from the player.


texts: How can I write an additive mesh shader that splits the RGB channels while accounting for depth?

texts:
I'm trying to create a sort of "hologram" effect. So far, what I have is an additive, three-pass shader that uses ColorMask for each pass to separate the RGB channels. The problem is that doing so requires ZWrite to be off (first image) so that each pass doesn't intersect the others (second image). However, doing so means that the model geometry overlaps itself, which I don't want.

I've tried the various methods of taking depth into consideration with transparency (This, for example) but they all cause problems when trying to separate the RGB channels. Is there some way to have each pass take depth into consideration within itself, but not with the other passes?


texts: Adding tolerance to a point in polygon test

texts:
I've been using this method which was taken from Game Coding Complete to detect whether a point is inside of a polygon. It works in almost every case, but is failing on a few edge cases, and I can't figure out the reason.

For example, given a polygon with vertices at (0,0) (0,100) and (100,100), the algorithm is returning:

True for any point strictly inside the polygon
False for any of the vertices
False for (0, 50) which lies on one of the edges of the polygon
True (?) for (50,50) which is also on one of the edges of the polygon

I'd actually like to relax the algorithm so that it returns true in all of these cases. In other words, it should return true for points that are strictly inside, for the vertices themselves, and for points on the edges of the polygon.

If possible I'd also like to give it enough tolerance so that it always tend towards "true" in face of floating point fluctuations. For example, I have another method, that given a line segment and a point, returns the closest location on the line segment to the given point.

Currently, given any point outside the polygon and one of its edges, there are cases where the result is categorized as being inside by the method above, while other points are considered outside. I'd like to give it enough tolerance so that it always returns true in this situation.

The way I've currently solved the problem is an hack, which consists of using an external library to inflate the polygon by a few pixels, and performing the tests on the inflated polygon, but I'd really like to replace this with a proper solution.


texts:
I am implementing a pretty straightforward client/server multiplayer architecture with Socket.IO and am having an issue where my client framerate seems to be faster than the servers. I have both interval loops set at 1000 / 30 yet they quickly diverge, even on my local machine. The code is simple in the example (just increase position.x by a constant on each tick), so there is no heavy computation that should slow it down. I expect them to be off but I don't expect this distance to increase over time.

Is this minor tick difference something that's inescapable? I can do server reconciliation but there is snapping every few seconds. This is how it looks without any reconciliation:

(red is the client, blue is the server)

I know there is an alternative implementation where I would multiply the constant (which is added to position) by the timestep on each frame, thereby syncing the two. This actually more or less works, but the problem with that approach is that the game logic I am implementing has the players moving on a fixed/precise grid, and when the position updates by long floats this is difficult to enforce.

Any suggestions?

Link to full example code: here.


texts:
I've been designing the memory management module for my game engine, including things like custom allocators and when it came to allocating memory for strings I kinda got stuck.
What I mean by strings in this context is things like UI text,
Items description, dialogues etc, so basically strings themselves are immutable, but they can stop being useful and just get freed.

With the string (and basically any object type with such allocation patterns) allocator I'd like to mostly get rid of the malloc/free invocations and so I'm wondering what kind of allocator is suitable for this jobs.
Another thing that worries me is fragmentation, because string have variable length by nature

How do game engines handle strings like this in the first place?

EDIT

Firstly I'd like to address some of the questions that came up.

The strings themselves would be loaded from an asset file.

By 'stop being useful' I mean a situation where player interacts with some kind of item that has a description associated with it and we'd like to show the description on screen.

To do that, the text would get loaded, displayed and freed some time after the player closes the description window (the delay is here because there the player could reopen the window again in a brief second for whatever reason).

Such allocations would occur very often, because we don't need all the resources at all times, just a specific subset of them and my idea was to create an allocator for that purpose. It would malloc a large enough block of memory and store the strings (or any resource of such allocation pattern) in it, marking the free spots as the string get freed.

That's when 'what about fragmentation' came up in my mind, because some strings might actually be stored a bit longer than others, leading to fragmentation inside the allocator.

But after reading some of the comments I figured that what I actually need is separate allocators for long-living strings/resources, such as UI elements, and for short-lived elements, like the dialogues and descriptions
What I also realized thanks to @Moo-Juice is that I could introduce something like resource-groups, that would hold the group of resources needed at that time, for example when entering some location, we'd load all the things that are contained within that location.
Thanks for the insight!

One thing remains a puzzle for me tho.
I've looked around Doom 3 source code, where I found a class called idStrPool which uses new/delete to allocate/deallocate strings.
Can anybody comment on that? After reading some books and articles I was convinced, that such a thing is pure evil in a game engine, yet here it its.
A use case I see for this is like handling input from the player, i.e. when the player types something and we want to capture it.
Can anyone comment on that?

Edit 2

Ok, I see that guys from idSoftware have overrided the operators in Heap.h


texts: How to make this C++ game server cross platform? [Focusing on Ubuntu compatibility right now]

texts:
The question's description will evolve depending on requested information or evolution of answers.
I made this C++ server for a game, which works on Windows, and would like to make it cross-platform, so it at least works on Linux (Ubuntu), macOS would be a plus i'd really appreciate, but not indispensably necessary (specially if single "cross-platform executable" isn't a possibility).
The server was programmed using VisualStudio IDE. These are all my source files I copied to another directory, including a custom static library (this one is in the same directory, the rest are all in C:/libraries):

Project dependencies are the following as configured in VisualStudio:

All libraries are to be linked statically. These are the ones my server uses:

GLM: Header only, cross platform.
Cereal: Header only, cross platform.
SFML modules: Can be linked statically. Cross platform according to them, even though this surprises me, since, for example, sfml_network module depends on winsock, which is a windows library...
MORPH_Shared_functions, My own library: Is static. It's own dependencies are the same as already listed for server, so I'm asuming that would make it cross-platform.

The entire server fits in a single executable without dynamic library dependencies. I tried moving the exe to another computer, and it works fine without the libraries installed in the system since they're merged into the executable.
According to the first answer I got, Every platform should be considered separately. So I'm focusing on Linux/Ubuntu first:
- Progress 1:
Begining with Ubuntu, I tried the g++ compiler for windows. I installed it on windows by installing MinGW, and now I can use it from windows's cmd. I tried following this nice and simple guide: https://courses.cs.washington.edu/courses/cse373/99au/unix/g++.html
From what I read, I understand a propper approach would be first compiling each .cpp individually, so I made myself a list of commands:
g++ -c -o Game.o Game.cpp
g++ -c -o CommandManager.o CommandManager.cpp
g++ -c -o ServerPlayer.o ServerPlayer.cpp
g++ -c -o ServerProp.o ServerProp.cpp
g++ -c -o ServerWorldState.o ServerWorldState.cpp
g++ -c -o UDP_Server_CS.o UDP_Server_CS.cpp

then I would do something like:
g++
-Wall
-o MORPH_Server
-Xpreprocessor SFML_STATIC
-I MORPH_Shared_Functions
-I C:\libraries\SFML\SFML-2.5.1\include
-I C:\libraries\GLM\glm
-I C:\libraries\CEREAL
-L C:\libraries\SFML\SFML-2.5.1\extlibs\libs-msvc\x64
-L C:\libraries\SFML\SFMLx64SourceAndCompile\lib\Debug
-l MORPH_Shared_Functions.lib
-l winmm.lib
-l ws2_32.lib
-l sfml-system-s-d.lib
-l sfml-network-s-d.lib
Main.o Game.o CommandManager.o ServerPlayer.o ServerProp.o ServerWorldState.o
UDP_Server_CS.o

In order to link them all together
However, the first individual module compilation attempt (Game.cpp) results in a header from my custom shared library not being found with error:
In file included from Game.h:2:0,
                 from Game.cpp:1:
UDP_Server_CS.h:1:33: fatal error: udp_network_manager.h: No such file or
directory
 #include "udp_network_manager.h"

I really don't know if I should link all libraries for each compiled module, so for now I at least tried:
g++ -c -o Game.o -lMORPH_Shared_Functions.lib Game.cpp

In order to point to my shared library, hopefully helping with pointing to it's header, but this returns the same error.
I imagine if I continued with this approach (which works for ubuntu, and no other OS's I know of), I'd first try to get the commands right for compiling, and then I could try making visual studio compile with CMake using that same commands, or something like that. I don't know too much about cmake, I only used it for compiling some libraries like sfml a few times.
Note: I already did a similar question some weeks ago (How to remotely host my c++ game server on Ubuntu?). This one is based on the same objective, but with more specifics on the case, and some actual strategies already developed.
In general I'm still looking for advice, ideas, and even specific guides.


texts: Why does this floor() call appear to have no effect?

texts:
I'm trying to get an effect where my material forms a mosaic which is aligned to the material. So I slapped a simple quad in the scene with a new material on it and set a new shader to that material.

My inputs (at least one thing in here will be removed later since it turns out I'm not using it):

        struct Inputs
        {
            float4 vertex : POSITION;
            float2 uv_panel : TEXCOORD0;
        };
        struct FragmentData
        {
            float4 vertex : POSITION;
            float4 uv_grab : TEXCOORD1;
        };

Vertex function:

        FragmentData Vertex(Inputs i)
        {
            FragmentData o;

            o.vertex = UnityObjectToClipPos(i.vertex);

            // what I actually want to do (the exact maths might be
            //   wrong still):
            float2 uv_panel = floor(i.uv_panel * _Pixels) / _Pixels;

            // Convert that UV value for inside the panel
            // to a UV value for the grab texture
            float4 object_coords = float4(0, 0, 0, 1);
            object_coords.xy = uv_panel - 0.5;
            float4 clip_coords = UnityObjectToClipPos(object_coords);
            o.uv_grab = ComputeGrabScreenPos(clip_coords);

            return o;
        }

And then the fragment function is pretty trivial:

        half4 Fragment(FragmentData i) : COLOR
        {
            return tex2Dproj(_GrabTexture, UNITY_PROJ_COORD(i.uv_grab));
        }

The end result is basically equivalent to doing nothing at all. I can see the objects behind the quad as if it weren't there. Upside is that it means my transformations are correct. Downside is that it means the mosaic effect somehow isn't being applied.

To check whether the floor call was working (and because I currently know no better way to debug this crap) I tried applying it like so:

            float2 uv_panel = floor(i.uv_panel);

This has no effect either.

This seems odd to me, because I thought uv_panel values in x and y would range from 0.0 to 1.0, so almost all values should floor to 0.0.

When I do this:

            float2 uv_panel = float2(0, 0);

It acts like I expected, with the bottom of the grab texture being smeared up the panel with the panel's alignment. So it's definitely using whatever value I put in here.

At this point I have no idea how to proceed because it's like my assumptions about the values in a float2:TEXCOORD0 are completely incorrect, or the floor() function does something completely different to what I expected.

What am I doing wrong here?


texts: How are you handling scores that can worsen (e.g. Elo rating) in Game Center?

texts:
Currently, Game Center leaderboard scores can only change one-way (e.g. increase). This makes it impossible (I think) to deal with Elo ratings and the like. How are you getting around this in your leaderboards?

I have filed a bug report / feature request with Apple already FWIW.

Are you using a third-party leaderboard service? Rolling  your own?


texts: How to not render what is behind object?

texts:
I am working on a 3d project using openGL. I am looking for a way to optimize my renderings.
Is there a way to tell if an object is behind another object and thus not visible to not waste time rendering it ?
I am already working on a frustrum culling implementation to not display what is not visible because out of the viewing frustrum, but I didn't find a way to know if an object in located behind another object.
Can any of you help me about this, please ?


texts: Are 2D art assets typically created at their intended in-game display size?

texts: I'm wondering if game makers create their sprites smaller than their intended in-game size in order to be more efficient or whether doing that produces unacceptable quality.


texts: Should abilities have their state and functionality separated?

texts:
I'm developing a top-down game using Javascript and Canvas in an ECS architecture.
I'm wondering, which of these is better from a design / elegance point of view?
Method 1: Combining the ability function and its metadata into one object:
// in ability factory
createBlinkAbility() {
  return {
    cooldown: 5000,
    castTime: 1000,
    hotkey: "q",
    execute(entity: Entity, scene: Scene) {
      let position = entity.get(CT.Position);

      let level = scene.queryComponent(CT.Level);

      position.x = Helpers.randomInt(0, level.width);
      position.y = Helpers.randomInt(0, level.height);
    }
  }
}

function executeCurrentCast(entity: Entity, ability: Ability) {
  ability.execute(entity); // all abilities have an execute function
}

Method 2: Separating ability metadata from its function:
// in ability factory
createBlinkAbility() {
  return {
    type: "blink",
    cooldown: 5000,
    castTime: 1000,
    hotkey: "q"
  }
}

// in ability factory
castBlink = (entity: Entity, scene: Scene) => {
  let position = entity.get(CT.Position);

  let level = scene.queryComponent(CT.Level);

  position.x = Helpers.randomInt(0, level.width);
  position.y = Helpers.randomInt(0, level.height);
}

function executeCurrentCast(entity: Entity, ability: Ability) {
  switch (ability.type) {
    case "bow": this.abilityFactory.castBow(entity); break;
    case "blink": this.abilityFactory.castBlink(entity); break;
    ...
  }
}

I know in general in an ECS architecture it is wise to separate "state" from "actions", but I'm not sure if this would also apply to things like abilities. It seems like it might be wise to maintain that separation, but the code seems like it might be "cleaner", or shorter at least, in the former case.
Lastly, I'm not really concerned with the performance differences between these two approaches, but rather which is better from a design standpoint.


texts: Calculate an approximate distance between two rigid bodies or OOB

texts:
Is there any easy way to get an approximate distance between two OOB?

I searched around and people talk about GJK algorithm, however I don't see it returning the distance between two convex objects even they are not colliding.

I don't need to be exact but just sphere checking is not acceptable in my case. Any ideas?


texts: I'm curious that most console controllers released these days - and all handheld consoles - contain four main buttons rather than two. Obviously increases in processing power, graphics engines etc, have allowed for more complex games, but is there an argument to be made that two buttons are really enough to create some great games? In other words, would someone releasing a new handheld console on the market today be foolish not to include four?


texts: Applying Transformation Matrices to VBOs in OpenGL

texts:
So I've recently tried to add Vertex Buffer Object Matrix transformation to an OpenGL engine I'm working on. I could go about this by applying the matrix to a copy of each vertex individually, but this would take a lot of CPU resources, so I am trying to implement transformation natively using OpenGL. This code works:

    /// <summary>
    /// Sets up the required OpenGL settings so as to create the necessary environment for the models to work (must be called on a thread on which an OpenGL context is set up, preferably on the thread on which the model was loaded).
    /// </summary>
    public static void Setup(Size viewPort, ref Matrix4 camera) {
        GL.MatrixMode(MatrixMode.Projection);
        GL.PushMatrix();
        if (!(viewPort.Width == 0 || viewPort.Height == 0)) {
            Matrix4 matrix;
            Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver3F, (float) viewPort.Width / viewPort.Height, 0.01F, long.MaxValue, out matrix);
            GL.LoadMatrix(ref matrix);
        }
        GL.MatrixMode(MatrixMode.Modelview);
        GL.PushMatrix();
        Camera = camera;
        GL.LoadMatrix(ref Camera);
        GL.Enable(EnableCap.DepthTest);
        GL.Enable(EnableCap.Lighting);
    }

    /// <summary>
    /// Renders the model (must be called on a thread on which an OpenGL context is set up, preferably on the thread on which the model was loaded).
    /// </summary>
    public override void Render() {
        if (IsVisible) {
            /*Matrix4 matrix = Matrix4.CreateTranslation(location);
            GL.MultMatrix(ref matrix);*/
            if (Cull)
                GL.Enable(EnableCap.CullFace);
            else
                GL.Disable(EnableCap.CullFace);
            texture.Bind();
            if (DataBuffer == 0) {
                GL.GenBuffers(1, out DataBuffer);
                GL.BindBuffer(BufferTarget.ArrayBuffer, DataBuffer);
                GL.BufferData<Vertex>(BufferTarget.ArrayBuffer, BufferSize, BufferData, Optimization);
            } else {
                GL.BindBuffer(BufferTarget.ArrayBuffer, DataBuffer);
                if (UpdateFrame) {
                    GL.BufferData<Vertex>(BufferTarget.ArrayBuffer, BufferSize, BufferData, Optimization);
                    UpdateFrame = false;
                }
            }
            IndexBuffer.Bind();
            GL.VertexPointer(3, VertexPointerType.Float, Vertex.SizeOfVertex, IntPtr.Zero);
            GL.TexCoordPointer(2, TexCoordPointerType.Float, Vertex.SizeOfVertex, TexturePointer);
            GL.NormalPointer(NormalPointerType.Float, Vertex.SizeOfVertex, NormalPointer);
            GL.DrawElements(BeginMode.Triangles, IndexBuffer.Count, IndexBuffer.Format, IntPtr.Zero);
            GL.Disable(EnableCap.CullFace);
            //GL.LoadMatrix(ref Camera);
        }
    }

    /// <summary>
    /// Resets the OpenGL settings set by calling Setup().
    /// </summary>
    public static void Reset() {
        GL.PopMatrix();
        GL.MatrixMode(MatrixMode.Projection);
        GL.PopMatrix();
    }

First Setup() is called to set up the projection matrix, then several meshes are rendered using the Render() method, then Reset() is called at the end to restore the matrices before I swap the buffers to the window.

However, when I comment out the commented lines in order to apply a simple translation matrix, I only get flickers all over the window. I tried using GL.Push() and GL.Pop() at the beginning and end of the Render() method, but to no avail. I also tried using GL.LoadIdentity() first and GL.MatrixMode(MatrixMode.Projection), but still no success.

Can anyone be kind enough to point out the mistake in my code please?


texts: How to change the value of variable from actor Y by the blueprint of actor X?

texts:
I have a project, and it has: 1 NPC (actor X), 2 target points and 1 tower (actor Y).

Image of components in level:

These rose arrows demonstrate part of the NPCs path.

I added a Event Begin Overlap in the blueprint of the NPC so that when it collides with the tower it loses 10 of life every second:

Image of print of variable life:

When the NPC gets 0 life, it goes to the next target point.

But I would like to know how to also modify the life of the tower by the same blueprint (NPC).

The code is already in my mind, it is kind of obvious to speak the truth.

"Code" of NPC blueprint:

I do not want to have to create a new Event Begin Overlap on the blueprint of the tower.

And I think using the blueprint level would not be a good idea.

One of the links below indicated something like Blueprint Interface, but I'd like to know if I can do what I want for the NPCs own blueprint.

Links:

https://forums.unrealengine.com/international/brazil/89438-pegar-vari%C3%A1vel-de-outro-blueprint

https://answers.unrealengine.com/questions/21386/communication-between-2-blueprints.html?sort=oldest

https://answers.unrealengine.com/questions/24773/how-to-call-a-blueprint-variable-from-another-blue.html

https://docs.unrealengine.com/en-us/Engine/Blueprints/UserGuide/Types/Interface


texts: How to sort scores and assign positions based on the scores?

texts:
I have three game objects each with an individual score. I was wondering how I should go about sorting these scores in ascending order. I want to also give these objects a position based on their score. Any help would be appreciated.

For example:

object1.score = 1300,

object2.score = 3000,

object3.score = 2200

What I'm looking for is:

object1.position = 3,

object2.position = 1,

object3.position = 2

Game Object code:

SGameObject
{
    int cp = 0;
    int lap = 0;
    int score = 0;
    int position = 0;
}


texts: 2D physics engine: Impulse based collision response with contact point manifold

texts:
I'm implementing a 2D physics engine where collision response is based on impulse computation.
I'm going to first expose the context, then the problem, and finally the questions.

Context

Simple collision between two solids, the first one is static, the second one falls.
The second solid has its colliding face parallel to the second solid.
Two collisions point are generated (one at each side of the second solid colliding edge).

Given two solids A and B who collided.

\$\vec Va\$ is the vector from A's center of mass to one Colliding Point.

\$\vec Vb\$ is the vector from B's center of mass to one Colliding Point.

\$\vec N\$ is the collision normal.

\$Ia\$ and \$Ib\$ are inertia tensor in world space of solids A and B.

Here is the impulse formula if you only take linear speed into account:

$$J = \frac{-(1 + bounceCoeff) * (\vec Va - \vec Vb) \cdot \vec N}{\frac{1}{mA} + \frac{1}{mB}}$$

Here is the impulse formula if you take linear and angular speed into account:

$$J = \frac{-(1 + bounceCoeff) * (\vec Va - \vec Vb) \cdot \vec N}{\frac{1}{mA} + \frac{1}{mB} + ((\frac{\vec Va \times \vec N}{Ia}) + (\frac{\vec Vb \times \vec N}{Ib})) \cdot \vec N}$$

Here is the way I update velocities for n contact points:

float \$pointCoeff = \frac{1}{\textbf{n}}\$

for(currentCollidingPoint : points)

{

\$\vec Va(t+1) = \vec Va(t) + \vec N * (J * \frac{1}{massA}) * pointCoeff\$

\$\vec Vb(t+1) = \vec Vb(t) - \vec N * (J * \frac{1}{massB}) * pointCoeff\$

}

Problem

Case 0:

If I only take the linear speed into account, the second solid falls on the static one and bounce upward (the resulting velocity post collision is positive on the y axis).

Case 1:

If I take the linear and the angular speed into account, the second solid falls on the static one but doesn't bounce (the resulting velocity post collision is still negative on the y axis).

Question

Am I right to state this is not normal that, because colliding faces are parallel and only B is moving down, B should bounce no matter if we take angular speed into account (A only performs translation, no rotation)?

I think that because if I only generate one collision point in the middle of B's colliding edge, B bounces

If I'm right, I guess that can be due to the way I consider how the pointCoeff variable is used in the algorithm.

Do you have any suggestion or piece of advice ?


texts:
I'm trying to use C# generics on a method in order to send a Vector3 (position) as a parameter. I can print the value correctly but can't store it on a local variable. I also can't access its x, y or z attributes separately.

I'm implementing a state machine. My intention is to use generics for allowing sending different parameters to the different states. The value will be sent to an "Enter" method which will be called once on each state every time that state is set to active or current.
So for example: the player will be on the DefaultState->something happens->change state to HeroTeleportingState while sending it it's new position

This is my Enter method on the HeroTeleportingState class:

void IState.Enter<T>(T newPosition)
{
    //The following line prints the correct value
    Debug.Log("move this hero to " + newPosition);

    //The following lines don't work
    //pos = newPosition
    //pos.x = newPosition.x;
}

The method call is just something like: currentlyRunningState.Enter(Vector3.one);

pos = newPosition gives me the following error on Visual studio (I'm paraphrasing cause my visual studio is in spanish):

  Cannot implicitly convert type 'T' to 'UnityEngine.Vector3'

And pos.x = newPosition.x gives me something like:

  'T' does not contain a definition for 'x' and no extension method 'x' accepting a first argument of type 'T' could be found

EDIT: IState interface:

public interface IState
{
    void Enter<T>(T value);

    void Execute();

    void Exit();
}


texts: Sending high scores to a web server in an open source game

texts:
I've never dealt with sending/receiving data from web servers in my games, so I absolutely have no idea how to do this. I tried googling for a good solution but couldn't find anything satisfying.

I currently get data from my web server by doing a HTTP request that gets the contents of a JSON text file stored on the server, and parses them in-game.

I do not know how to "write" high scores to the server, and even worse I do not know how to avoid people sending what they want to the server since the game is open source.

How is this usually done?


texts:
Ok so ive created a prefab of an obstacle avoidance bot and am attempting to clone it. Problem is, only one of the instances works correctly, the rest just sit there. The bots are supposed to turn left when right sensor is triggered and vice versa.
The instantiation code:

public int populationSize = 10;
public GameObject carPrefab;
public Vector2 spawnPosition;
public static float speed = 2f;

private GameObject[] cars;

// Use this for initialization
void Start () {
    cars = new GameObject[populationSize];
    for (int i = 0; i < populationSize; i++) {
        spawnPosition = new Vector2((1.0f*i)-2,3.83f);
        cars [i] = GameObject.Instantiate (carPrefab,spawnPosition,Quaternion.identity);
    }

}

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

}

The prefab scripts: (Left Sensor and Right Sensor are children of CarMovement)

public float speed = 2f;
public static Rigidbody2D rb2d;

// Use this for initialization
void Start () {
    rb2d = GetComponent<Rigidbody2D> ();

}

// Update is called once per frame
void Update () {
    rb2d.transform.Translate (Population.speed * Time.deltaTime, 0, 0);
}

Left Sensor:

// Use this for initialization
void Start () {

}

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

}

void OnTriggerStay2D (Collider2D other){
    Debug.Log ("LEFT");
    CarMovement.rb2d.rotation -= 5;
}

Right sensor:

Code (CSharp):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RightSensor : MonoBehaviour {

// Use this for initialization
void Start () {

}

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

}

void OnTriggerStay2D (Collider2D other){
    Debug.Log ("RIGHT");
    CarMovement.rb2d.rotation += 5;
}

Any help would be greatly appreciated. I have no idea whats going on.


texts: LibGDX Textfield - Text Overflow - Not Wrapping

texts:
In my app's registration screen, the textfield is not wrapping text as I expected. Notice in the above image, the email field is not containing the text. I have set the size of the textfield using setSize() method but I couldn't find any way to wrap text. Is there any solution to this?

I'm using LibGDX v1.9.0.

EDIT: I don't have problem with overflowing but I think it should be hidden beyond the textfield borders.

UPDATE: It was indeed carelessness from my part. I actually included a padding to the textfield position which I didn't correct when defining its size. Issue got solved now. I don't know whether I should keep the question or delete it.


texts: Why are my sprite outlines partially rendering in the wrong place?

texts:
I've been trying to draw an outline around a sprite using the code from this answer.

Details

My sprite is called Ship2Sprite.

This is how I create the rectangle:

 rectangle = New Rectangle(backgroundPos.X + NPCAI.enemyPosistion.X,
                           backgroundPos.Y + NPCAI.enemyPosistion.Y,
                           Ship2Sprite.Width, Ship2Sprite.Height)

This is how it looks without any rectangle drawn:

If I use this line of code

hudSpriteBatch.Draw(t, rectangle, New Rectangle(0, 0, 0, 0), Color.Red,
                    NPCAI.enemyAngle, New Vector2(0, 0), SpriteEffects.None, 0)

the following is the result in game

hudSpriteBatch.Draw(t, New Rectangle(rectangle.Left, rectangle.Top, 2, rectangle.Height), New Rectangle(0, 0, 0, 0), Color.White, NPCAI.enemyAngle, New Vector2(0, 0), SpriteEffects.None, 0)
hudSpriteBatch.Draw(t, New Rectangle(rectangle.Right, rectangle.Top, 2, rectangle.Width), New Rectangle(0, 0, 0, 0), Color.White, NPCAI.enemyAngle, New Vector2(0, 0), SpriteEffects.None, 0)
hudSpriteBatch.Draw(t, New Rectangle(rectangle.Left, rectangle.Top, rectangle.Width, 2), New Rectangle(0, 0, 0, 0), Color.White, NPCAI.enemyAngle, New Vector2(0, 0), SpriteEffects.None, 0)
hudSpriteBatch.Draw(t, New Rectangle(rectangle.Left, rectangle.Bottom, rectangle.Width, 2), New Rectangle(0, 0, 0, 0), Color.White, NPCAI.enemyAngle, New Vector2(0, 0), SpriteEffects.None, 0)

However, when trying to use the code from the linked answer, this is the result:

The first and third lines produce the correct lines, however the other 2 are in the correct orientation but not the correct position

Am I missing something somewhere?

EDIT

Based on Blau's answer, I have updated my code to this:

 Public Shared Sub DrawOutline(ByVal t As Texture2D, ByVal sprite As Texture2D, ByVal pos As Vector2, ByVal graphics As GraphicsDevice)

    Dim spriteBatch1 As New SpriteBatch(graphics)
    Dim rectangle As New Rectangle(Game.backgroundPos.X + pos.X, Game.backgroundPos.Y + pos.Y, sprite.Width, sprite.Height)
    Dim w = rectangle.Width
    Dim h = rectangle.Height
    Dim x = rectangle.X + w / 2
    Dim y = rectangle.Y + h / 2
    Dim transform As Matrix = Matrix.CreateRotationZ(NPCAI.enemyAngle) * Matrix.CreateTranslation(x, y, 0)

    spriteBatch1.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, Nothing, Nothing, Nothing, Nothing, transform)
    x = -w / 2
    y = -h / 2

    spriteBatch1.Draw(t, New Rectangle(x, y, w, 2), Nothing, Color.White)
    spriteBatch1.Draw(t, New Rectangle(x, y + h - 2, w, 2), Nothing, Color.White)
    spriteBatch1.Draw(t, New Rectangle(x, y, 2, h), Nothing, Color.White)
    spriteBatch1.Draw(t, New Rectangle(x + w - 2, y, 2, h), Nothing, Color.White)
    spriteBatch1.End()

End Sub

However the rectangle is rendering in the wrong position, which is slightly ahead of the sprite. Like this

EDIT 2, with the following code

 Public Shared Sub DrawOutline(ByVal t As Texture2D, ByVal sprite As Texture2D, ByVal pos As Vector2, ByVal graphics As GraphicsDevice, ByVal angle As Single)

    Dim spriteBatch1 = New SpriteBatch(graphics)
    Dim rectangle As New Rectangle(Game.backgroundPos.X + pos.X, Game.backgroundPos.Y + pos.Y, sprite.Width, sprite.Height)
    Dim w = rectangle.Width
    Dim h = rectangle.Height
    Dim x = rectangle.X + w / 128
    Dim y = rectangle.Y + h / 128

    Dim transform As Matrix = Matrix.CreateRotationZ(angle) * Matrix.CreateTranslation(x, y, 0)

    spriteBatch1.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, Nothing, Nothing, Nothing, Nothing, transform)
    x = -w / 128
    y = -h / 128
    ' spriteBatch1.Draw(t, rectangle, Color.Red)
    spriteBatch1.Draw(t, New Rectangle(x, y, w, 2), Nothing, Color.White)
    spriteBatch1.Draw(t, New Rectangle(x, y + h - 2, w, 2), Nothing, Color.White)
    spriteBatch1.Draw(t, New Rectangle(x, y, 2, h), Nothing, Color.White)
    spriteBatch1.Draw(t, New Rectangle(x + w - 2, y, 2, h), Nothing, Color.White)
    spriteBatch1.End()

End Sub


texts:
I have a 3D scene that I've tried rendering in Direct3D 10 and using WPF's 3D framework. Obviously, going directly to Direct3D is producing far better performance but I am getting banding which doesn't appear using the same scene in WPF.

Does anyone have any tips on removing this type of artifact? It's obviously possible because WPF doesn't have it... If you have any questions about my Direct3D setup I will be please to add that information.

WPF:

Direct3D:


texts: Handling movement on sloped surfaces - clamping character to sloped surface

texts:
I've noticed that a lot of people seem to have this issue but I've yet to find an actual working solution - when a rigidbody-based character controller (I'm not using Unity's character controller) moves down a sloped surface, they will bounce/bunny hop on the way down instead of staying on the surface. I'm building a 3d platformer and ran into this issue - I've tried a fair amount of things but nothing seems to work cleanly. I managed to find a 2D solution here but I can't seem to get it to work cleanly in 3D. Here is my code:

    void NormalizeSlope()
{
    // Attempt vertical normalization
    if (isGrounded)
    {
        RaycastHit hit;
        if (Physics.Raycast(floorCheck.position, Vector3.down, out hit, groundCheckDistance))
        {
            if(hit.collider != null && Mathf.Abs(hit.normal.x) > 0.1f)
            {
                // Apply the opposite force against the slope force
                // You will need to provide your own slopeFriction to stabalize movement
                rigidbody.velocity = new Vector3(rigidbody.velocity.x - (hit.normal.x * 0.4f), rigidbody.velocity.y, rigidbody.velocity.z); //change 0.6 to y velocity

                //Move Player up or down to compensate for the slope below them
                Vector3 pos = transform.position;
                pos.y += -hit.normal.x * Mathf.Abs(rigidbody.velocity.x) * Time.deltaTime * (rigidbody.velocity.x - hit.normal.x > 0 ? 1 : -1);
                transform.position = pos;
            }
        }
    }
}

With that, I get varying results on surfaces with different slopes. Also, my character jitters. On some slopes, my character even slowly inches their way up the surface. Has anyone else run into this issue? Does anyone have a working solution for this problem?


texts: Tutorial to port XNA game to MonoGame on iOS?

texts: Are there any good tutorials to convert a current XNA game to work iOS using MonoGame?


texts: So I'm gonna start on a new project and were surfing around google images and found this image. Basically its almost pure 2D where there is no 3d object and everything is represented in 2d images as you see. Im wondering what this technique is called? Im guessing its some variant of parallax? I know this style has been called 2.5d back in the day. The project will be in MonoGame(c#) so i need headers of where to start developing an engine like this, what is the "2.5d" technique called?


texts:
I'm an excellent writer with a talent for crafting characters, worlds, and plotlines of a unique and appealing nature. For some reason I'm studying computer science, but I know fiction writing is my true calling.

How can I find an entry-level job or internship developing the stories, characters, and dialogue for a video game? That would be my dream job, and I know I could make a superb showing.

Any tips on where I can find opportunities? Google searches turned up a ton of game design jobs, but I think that's different. I couldn't find anything related to writing.

Thanks!


texts: Analytics for PC games: is there anything similar to localytics, flurry, etc?

texts:
I would like to know if there exists any service such as Localytics or Flurry but for PC? These ones are mobile focused. It would be really great if they had support for PC too.

In the case there's nothing similar at all, what alternatives or which methods would you recommend for me to keep track of this analytics?

I'm planning to use it in a game and not only to gather generic data such as gender, age, country, etc. What I'd really like is to be able to track gameplay statistics such as: is my game too difficult? (number of deaths per player per level), is my game fun? (number of players who never finish the game and at which point did they stop playing), etc.


texts: GL how to look at the center of the viewport

texts:
I'm using GLFW3 and OpenGL to visualize measurements from an IMU that I have. I've gotten the simple cube example working and I can rotate it successfully with quaternions that I've input.

However since I'm visualizing an IMU, it is important that I know which way I am looking at it. I would prefer to look at it from a top down view.

Hence I want to keep the cube at the center of the world (0, 0, 0) and look down at it from a corresponding height (0, 0, z) which is where I want my camera to be at. I've the following code, can someone please guide me on how to set up my glLookAt function? All the values that I input make my cube disappear.

void display( GLFWwindow* window )
{
  while(!glfwWindowShouldClose(window))
  {
    // Scale to window size
    GLint windowWidth, windowHeight;
    glfwGetWindowSize(window, &windowWidth, &windowHeight);
    glViewport(0, 0, windowWidth, windowHeight);

    // Draw stuff
    glClearColor(0.2, 0.2, 0.2, 1.0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glMatrixMode(GL_PROJECTION_MATRIX);
    glLoadIdentity();
    gluPerspective( 60, (double)windowWidth / (double)windowHeight, 0.1, 100 );

    glMatrixMode(GL_MODELVIEW_MATRIX);
    glTranslatef(0,0,-5);

    drawCube();

    // Update Screen
    glfwSwapBuffers(window);

    // Check for any input, or window movement
    glfwPollEvents();
  }


texts: Libnoise bounding box - from spherical to planar

texts:
I'm trying to convert a bounding box inside a spherical map (equirectangular image as a result of Libnoise/c++) into a planar projection, but I can't find the correct algorithm for it and I'm not good at projections.

I'm using Javascript and Python and I've been trying to adapt some libraries I've found that convert equirectangular images into cubemaps, but those work by processing each face separately and I find it extremely complicated to adapt such libraries to process just a bounding box of the equirectangular result.

This is the library I'm using as a reference.

And this is the diagram of what I'm trying to do with the resulting image.

I know I'll have some distortions and that the resulting image will be "narrower" when heading closer to the poles, so I'm planing to calculate such offsets regarding to the bounding box to cover the desired area.

This would allow me to work on the map using XY flat coordinates, without the spherical distortion.


texts:
So I'm new to working with a 3D space and not sure how to fix my problem, I basically have a turret that rotates along its Z axis, and pitches along it's Y but after rotating 180 on the Z axis the turret points down as I completely understand despite being unexpected.

I have a fiddle with what I'm working on here https://jsfiddle.net/2v4ezmaz/2/

So the question is, how do I make it rotate like it does in blender where the barrel end stays pointing up while rotating the z? After lots of reading it's all to do with cross vectors since the .rotation property is euler angles which I think is my problem. I need to use quaternions but I can't logically see what needs to happen.

My brain is thinking of it as needing to reset the rotation back to its default then apply Z rotation and apply the Y rotation, but that can't be right.

After reading http://blog.wolfire.com/2010/07/Linear-algebra-for-game-developers-part-4 I'm sure my answer is there somewhere but I cant think what the code needs to be to do what i want.

Any pointers would be super helpful since my brain is fried reading/trying vector and matrix rotations.


texts: Gauss-Krüger system to Unity Coordinate Conversion

texts: In my recent project, I am getting an object file via a request to REST API and found that the OBJs (object file) are in Gauss-Kruger System. I want to know that how exactly I place the model as I have several objects so coordinate conversion should work between UCS(unity coordinate system) and Gauss Kruger System. Previously I am able to convert UCS to Lat Long via Unity GPS Conversion project.


texts: Unity Raw Image ui not showing when small

texts:
I have some Images online that I download using WWW class and the use as UI elements.
So far all of them where working perfectly but now the one I added recently is acting up.
First you should know that all of the images are being downloaded by the same script and handled by that so there should be no difference between  their materials and stuff AFAIK (if I'm missing something please tell me).
Second , the problem is that this particular image only shows up when it's taking more than one sixth of the screen, for example if I make it bigger by changing it's size in the inspector, or if I go to scene view and zoom in on it, it starts to fade in the larger it gets on the screen.
Also, I changed the picture to something that was working properly to make sure it's not from the image.

    public IEnumerator AddTools(Tool Tool)
    {
        Texture2D T = new Texture2D(4, 4, TextureFormat.DXT1, true);
        SpriteTool ST = new SpriteTool();
        ST.TheTool = new UnityEngine.Texture();
        ST.ID = Tool.ID;
        ST.ToolName = Tool.Name;
        ST.Type = Tool.Type;
        WWW wWw = new WWW(Tool.Url);
        while (!wWw.isDone)
        {
            yield return wWw.progress;
        }
        wWw.LoadImageIntoTexture(T);
        ST.TheTool = T;
        ST.TheTool.name = Tool.Name;
        SpriteTool PA = ObjectTools.SingleOrDefault(p => p.ID == ST.ID);
    }

The SpriteTool Type is a class I made for storing some of the information needed to build the UI element later.

    private GameObject CreateButton(SpriteTool item = null, float angle = 0)
    {
        Texture2D T2D = (Texture2D)item.TheTool;
        T2D.SetPixels(T2D.GetPixels(0, 0, T2D.width, T2D.height));
        T2D.Apply();
        GameObject Tool = new GameObject();
        Tool.transform.SetParent(GUICanvas.transform);
        //There was some code for positioning the element and resizing it that I
        //did not include but I can see in the scene view that the size and the position
        //are what they supposed to be so that's not the problem
        Tool.AddComponent();//The type is RawImage
        Tool.GetComponent().texture = T2D;//the type is RawImage
     }


texts: From the image below I know the vectors P1, P2 and P3. How can I find the point A which lies on the circle and line P2A which is a bisector (angle q and r are equal) of the lines P2P1 and P2B? Also how can I find the point B which is in the same direction as P2P3 and lies on the circle?


texts: DirectX 11 generate normals for tessellated triangles

texts:
I've spent a couple days looking for an answer to this - How can I access the newly created triangles of tessellation and generate normals for them? I've followed much of the shader code from the following tutorial:
http://www.richardssoftware.net/2013/09/bump-and-displacement-mapping-with.html

I would like to use these normals so that I can correctly light the new triangles as part of my displacement mapping implementation. Can this be done? My other idea was to use bump mapping as well as displacement mapping in order to get the correct normals and bi/tangents. Would this be overkill? Would it look right?

Any advice would be greatly appreciated.

Thank you


texts: Finding a path with minimal number of turns on a grid?

texts:
There is a path, generated by my implementation of A*, where diagonals aren't allowed, and the heuristics is the Manhattan distance.

Is there a way to always or nearly always find a path with the least amount of turns? Even if it's a bit longer, and even if it costs more computationally.

Or is there a way to algorithmically "fix" a path later? Like on the image below, cut those long detours and replace them with those blue parts.

My current version is far from optimal, both length-wise, and both turn-wise.
I also tried multiplying the heuristic value of a tile, if:

it isn't going in the same direction as the line made from the previous 2 tiles. But that didn't help either.


texts:
Quite a few of the 2D games that I have seen use per-tile lighting, where each tile has a set brightness (continuous scale of 0 to 1, for example).

One way of calculating the brightness of any one tile is to loop with all light sources and add a brightness value to the tile based on distance from the light source. However, with 100^2 tiles and 100 lights, that's a million iterations.

What's a CPU efficient method of calculating the light on each tile with multiple light sources?

Light sources that have objects in the way of tiles should also have a lesser impact but it doesn't matter if this doesn't resemble shadows.

The light sources change every few seconds.


texts: Play Audio After Countdown In JavaScript

texts:
Is there a way I can have an audio sample play after a certain amount of time, like 3 seconds in JavaScript? I've looked everywhere and can't seem to find what I'm looking for! I'm very new to this type of stuff, so apologies for the kind of daft question...

Thanks


texts: Unity3d - Cast dynamic shadows without processing multiple lights

texts:
Back Story

I've built a game with a friend and all goes well until there are too many spheres under a group of 5 lights, then things start getting choppy.

Troubleshooting

I've found that by turning off all of these lights but one the game runs smoothly, the problem is that the shadows are not realistic at all. Because of the 4 main lights, the objects should have four main shadows.

My Ideas

I wanted to use a "projector" but that is too static for multiple & random appearing / disappearing objects. I might be able to do a projector per sphere  but I'm hoping there is an easier way as this would require a lot of work to get just right.

Question

How can I get 4 lights to cast a raycast shadow on a group of dynamically moving spheres (100 of them) without processing the light portion?