texts:
When I move, I grab the tile in front of the player, but when the player is colliding between two tiles, I grab the wrong tile due to rounding error. I made a video explaining what I mean.

As you can see, when the player is moving down on the edge of a tile, they pass through. This is how I find the tile:

Tile t = world.tiles[(int) ((int) getX() / 32 + x)][(int) ((int) getY() / 32 + y)];`

This is my collision detection code:public static boolean isColliding(AABB a, AABB b) {
        if (Math.abs(a.pos.getX() - b.pos.getX()) < a.size + b.size) {
            if (Math.abs(a.pos.getY() - b.pos.getY()) < a.size + b.size) {
                return true;
            }
        }
        return false;
    }
The pos variable in the AABB class is the center of the entity and the size is half the size of the player.

How can I fix this so it finds the correct tile?

Edit:
Ok, I changed my move method to get the tiles around the player, but now the player only collides if he is colliding in the middle of four solid tiles! I don't understand!

private void move(int x, int y, float sx, float sy) {
    Vector2f tempPos = new Vector2f((pos.getX() + (pos.getX() + 32)) / 2, (pos.getY() + (pos.getY() + 32)) / 2);
    box.update(new Vector2f(tempPos.getX() + sx, tempPos.getY() + sy), 16);
    if (getX() / 32 + x > 0 && getX() / 32 + x < world.mx && getY() / 32 + y > 0 && getY() / 32 + y < world.my) {

        for (int xx = 0; xx <= 1; xx++) {
            for (int yy = 0; yy <= 1; yy++) {
                if (world.getTile((int) (getX() / 32) + xx, (int) (getY() / 32) + yy) != null) {
                    Tile t = world.getTile((int) (getX() / 32) + xx, (int) (getY() / 32) + yy);
                    t.color = true;
                    if (t.type != 0 && !Collision.isColliding(box, t.getBox())) {
                        setPos(getX() + sx, getY() + sy);
                    } else if (t.type == 0) {
                        setPos(getX() + sx, getY() + sy);
                    }
                } else {
                    setPos(getX() + sx, getY() + sy);
                }
            }
        }

    } else {
        setPos(getX() + sx, getY() + sy);
    }
    glPushMatrix();
    glTranslatef(getX(), getY(), 0);
    glPopMatrix();
}

The type in Tile is just for checking to see if the tile is air. As you can see, I have two for loops that loop through the four tiles above, below and to the right and left of the player, and see if he collides with any of them. I have no idea why this isn't working, and I've tried to figure out how to do this for a week now. Can anyone show me a link or code to get the tiles around a player and see if he collides with them?


texts: How can I mark a pixel in the stencil buffer?

texts:
I never used the stencil buffer for anything until now, but I want to change this. I have an idea of how it should work: the gpu discards or keeps rasterized pixels before the pixel shader based on the stencil buffer value on the given position and some stencil operation.

What I don't know is how would I mark a pixel in the stencil buffer with a specific value. For example I draw my scene and want to mark everything which is drawn with a specific material (this material could be looked up from a texture so ideally I should mark the pixel in the pixel shader), so that later when I do some post processing on my scene I would only do it on the marked pixels. I didn't find anything on the internet besides how to set up a stencil buffer and explaining the different stencil operations. I was expecting to find some System-Value semantics like SV_Depth to write to in the pixel shader (because the stencil buffer shares the same resource with the depth buffer in D3D11), but there is no such thing on MSDN. So how should I do this?
If I am misunderstanding something please help me clear that up.


texts: Skeletal Animation - Automatically apply skeleton to model

texts:
Looking at websites such as mixamo.com or some game's development systems such as the animation editor for Overgrowth (http://www.youtube.com/watch?v=-RpqbC5-Z0E), i see that the skeleton in these situations is automatically being applied to the models.

I really don't expect (though wouldn't mind) code that does this, but i really am looking for some sort of pointer in the direction, or how they go about this. If any of you have done this, or know how to, please do reply, i don't want to spend the next week trying to crack it, then another to actually code it :P

Thanks all :)

Just for a bit more information, i am in C# working with OpenTK with my own custom model loader, etc. but i can easily adjust any given code / concept to fit with mine :)


texts: Planning Class Inheritance for Game Objects

texts:
This is specifically about the development and planning direction of the game development.

I'm creating a fairly basic RPG and am wondering about the approach that I should take. I've been trying to outline it all in a flow chart first, but want to see if this is a good way of going about it.

For example, I've created a class called "items", which then currently derives into "Weapons" "Armor" and "Potions". I then derive these classes further into specific types and I keep going and going, basically as specific as I want to get.

Before I get too deep into this (again, I'm still planning) - I just want to know if this is a good way of approaching this problem.


texts: How to smooth terrain to lower polygon count?

texts:
I'm using Unity.
I've created a simple Beach using Terrain editor.
The problem is that Stats show me already a lot of Triangles only for Terrain renderer: 40K .

So my question is: how can I create a Unity Terrain suitable for Mobile game ?
How can I smooth terrain edge ?

Thanks


texts: How to get rid of the white border/background on my png image?

texts:
I am making a game using pyGame; it is basically a space invader game, with a tank.

As we can see, this tank image I have has white borders / a white background, which I really want to get rid of.

I am thinking of editing it out, but it would be replaced by a different colour. Is there any way to somehow cut out this tank image from its original rectangular box?


texts: how can i fix my code in order to get rid of the error that says that the object I want to instantiate is null?

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

public class replicate : MonoBehaviour
{

    public void replicateCube(InputField T)
    {
        int H = int.Parse(T.text);

        for (int i = 0; i < H; i++)
        {

            GameObject prefab = Resources.Load("Cube") as GameObject;
            GameObject go = Instantiate(prefab) as GameObject;
            go.transform.position = new Vector3(0, i*5, 0);

        }
    }
}


texts: How can I represent rooms and associated actions and inventory in a text-based adventure game?

texts:
I am just getting started learning to make games. I have created a simple text-based game where the user can walk around between rooms and interact with the objects in each room. However, I feel like my approach has led to a pile of bad spaghetti code. I'm not sure what a good way to structure a game like this would be.

My approach was to have one class with a method for each room and all the objects and interactions that could be done in that room. For example, this is the method for the study:

public static void Study()
{
    bool studyexited = false;

    while (!studyexited) {
        string usercommand = Console.ReadLine ();
        usercommand.ToLower ();

        switch (usercommand) {
        case "turn left":
            GameEventText.StudyLeft ();
            break;
        case "turn right":
            GameEventText.StudyRight ();
            break;
        case "go forward":
            Notes firstsetofclues = new Notes ("First Note");
            GameEventText.StudyFront ();
            string firststudycommand = Console.ReadLine ();
            firststudycommand.ToLower ();

            if (firststudycommand == "read note") {
                firstsetofclues.Firstnotereading ();
            }

            Console.WriteLine ("Picking up this note would prove valuable");
            string secondstudycommand = Console.ReadLine ();
            secondstudycommand.ToLower ();

            if (secondstudycommand == "pick up note") {
                if (MainClass.PlayerInventory.AddItem (firstsetofclues))
                {
                    Console.WriteLine ("The note has been added to your inventory");
                } else {
                    Console.WriteLine ("Your inventory is full");
                }

                MainClass.PlayerInventory.Inventorydisplay ();
            }
        }
    }
}

I don't feel like this is an approach that will scale; that is, I can't really write functions like this for every room. I believe that using files in some way would be a good strategy to avoid the "hard coding" that I'm currently doing. But I am not sure how I can achieve that?


texts: GUI Label shows on screen when object is out of view?

texts:
I have GUI Labels over NPCs in my game, and the labels display their name above their head. But when I walk away and go somewhere else, their names stay on screen like it's mirrored or something?

Here's what I'm talking about:

This is how it looks normally

This is what happens when I walk out of view.

The Code:

using UnityEngine;
using System.Collections;

public class NPC : MonoBehaviour {

private float left;
private float top;
public float leftModifier;
public float topModifier;

private Vector3 NPCScreenPosition;

//FIX THE MIRRORING ISSUE

void Start () {

}

void Update () {
    Vector3 NPCNameWorldPosition = (transform.position + new Vector3(0.0f, transform.lossyScale.y, 0.0f));
    NPCScreenPosition = Camera.main.WorldToScreenPoint(NPCNameWorldPosition);
    left = NPCScreenPosition.x + leftModifier;
    top = Screen.height - (NPCScreenPosition.y + topModifier);
}

void OnGUI() {
    GUI.Label(new Rect(left, top, 150, 25), gameObject.name.ToString());
  }
}


texts: Is there a 3d game engine without a built-in physics engine?

texts:
I know about jMonkeyEngine, Ardor3D, etc. Yes, I've also heard of LWJGL and OpenGL (the both are essentially the same, though) but neither of them really suit me. I don't want to deal too much in the backend stuff, because though it's really cool, I find it tedious. I have a good understanding of what goes on behind the scenes, but I need a higher-level API without a built-in physics engine. Is there such an engine? It would definitely be a plus if the engine has cool shader effects like specular lighting, normal mapping, etc.

EDIT: The engine has to be Java-based.


texts: I've been looking into developing a small game with Java, as I am fairly familiar with it and see game development as good opportunity to improve my knowledge. When I research different libraries and other such things, the two resources I have often seen are LibGDX and LWJGL. I am however still unsure of the differences between the two. Would someone be able to explain where the differences lie and what each's strength is.


texts: How can i display a nice big gui text in the middle of game view screen?

texts:
The same idea like the message: "Display 1 No cameras rendering"
I'm trying to do it too but i don't see anything when running the game.

In the Hierarchy i have a empty GameObject and in the Inspector attached to it the script and two components: GUI Text and GUI Texture

This is the script:

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

public class SwitchCameras : MonoBehaviour
{
    [Header("Cameras Init")]
    public Camera[] cameras;
    public Vector3[] originalPosition;
    [HideInInspector]
    public Vector3 currentCameraOriginalPosition, currentCameraPosition;

    [Space(5)]

    [Header("Cameras Switch")]
    public string currentCameraName;
    public Vector3[] lastCameraPosition;

    private int currentCamera = 0;

    [Space(5)]

    [Header("Gui Text")]
    public GUIText myGUItext;
    public GUITexture texture;
    public int guiTime = 2;

    void Start()
    {
        cameras = Camera.allCameras;
        lastCameraPosition = new Vector3[cameras.Length];

        if (cameras.Length >= 1)
        {
            originalPosition = new Vector3[cameras.Length];
            for (int i = 0; i < cameras.Length; i++)
            {
                originalPosition[i] = cameras[i].transform.position;
            }
        }

        if (cameras.Length == 1)
        {
            myGUItext.text = "Need more then 1 camera for switching..";
            myGUItext.gameObject.SetActive(true);
            texture.gameObject.SetActive(true);
            StartCoroutine(GuiDisplayTimer());
        }
        else
        {
            Debug.Log("Found " + cameras.Length + " cameras");
        }

        for (int i = 0; i < cameras.Length; i++)
        {
            cameras[i].enabled = false;
        }
        cameras[0].enabled = true;
        currentCameraName = cameras[0].name;
        currentCameraOriginalPosition = originalPosition[0];
    }

    void LateUpdate()
    {
        if (Input.GetKeyDown(KeyCode.C))
        {
            cameras[currentCamera].enabled = false;

            if (++currentCamera == cameras.Length)
                currentCamera = 0;

            cameras[currentCamera].enabled = true;
            currentCameraName = cameras[currentCamera].name;

            currentCameraOriginalPosition = originalPosition[currentCamera];
        }
        lastCameraPosition[currentCamera] = cameras[currentCamera].transform.position;
        currentCameraPosition = lastCameraPosition[currentCamera];
    }

    IEnumerator GuiDisplayTimer()
    {
        yield return new WaitForSeconds(guiTime);
        myGUItext.gameObject.SetActive(false);
        texture.gameObject.SetActive(false);
    }
}

I used a break point and it's getting to the line:

myGUItext.text = "Need more then 1 camera for switching..";

But not showing it on the game view when running the game.


texts: Custom shadow mapping in Unity. Works with preservative Light view but not with Orthographic

texts:
So about a week ago I decided to make my own shadow mapping technique in Unity based on my understanding of the whole thing. The entire experience was somewhat successful. I learned a lot and I get to correct a lot of things such as the MVP matrix and the math behind it.  One thing though didn't work as planned and I don't know why.

First lets talk about what worked. I wrote a replacement shader that will show the depth of every object based on the Light Position/perspective. Therefore I made a custom Light GameObject that act as a camera/light with that replacement shader attached to it, and I record everything the Light sees into a render texture.

Then I made a second Camera which is basically a child of the main camera, and sees what the main camera see with the exception of the replacement Shader that I attached previously to the Light gameobject. again I recorded everything from the camera to a render texture as well.

After that, I wrote a basic Shader that does a basic light calculation and make a the shadow comparison between the two textures, and determines whether a fragment in a shadow or light. Also, I added a shadow Bias as well to eliminate any artifacts.

            struct appdata {
            float4 position : POSITION;
            float3 normal : NORMAL;
            float2 uv : TEXCOORD0;
        };

        struct v2f {
            float4 position : SV_POSITION;
            float2 uv : TEXCOORD0;
            float3 normal : TEXCOORD1;
            float3 worldPos : TEXCOORD2;

        };

        float4 _Tint;
        sampler2D _MainTex;
        sampler2D  SahdowMap_Light, SahdowMap_View;
        float4 _MainTex_ST;
        float4x4 WorldToCamera, WorldToLight;
        float3 _LightDir1;

        v2f VertexProgram(appdata v) {
            v2f i;
            i.position = UnityObjectToClipPos(v.position);
            i.worldPos = mul(unity_ObjectToWorld, v.position);
            i.normal = UnityObjectToWorldNormal(v.normal);
            i.uv = TRANSFORM_TEX(v.uv, _MainTex);
            return i;
        }

        float Shadow_Cal(v2f i, sampler2D DepthMap,float4x4 space) {

            float4 projected2 = mul(space, float4(i.worldPos, 1.0f));
            float2 uv = (-projected2.xy / projected2.w) * 0.5 + 0.5;
            float Shadow = tex2D(DepthMap, uv).r;

            if (uv.y > 1.0)
            Shadow = 0.0;

            return Shadow;
        }

        float4 FragmentProgram (v2f i) : SV_TARGET {

            float LightDepth = Shadow_Cal(i, SahdowMap_Light, WorldToLight);
            float ViewDepth = Shadow_Cal(i, SahdowMap_View, WorldToCamera);
            float bias = max(0.05 * (1.0 - dot(i.normal, _LightDir1)), 0.015);
            float Shadow = LightDepth + bias < ViewDepth ? 0 : 1;

            float4 Texture = tex2D(_MainTex, i.uv);
            float3 lightpos = _LightDir1 - i.worldPos;
            return saturate(dot(lightpos, i.normal)) *_Tint * Texture * Shadow;
        }

The problem is when the Light is on perspective, this works perfectly fine as shown above, but when I switch the light camera to Orthographic this happen:

I tried many different things to fix it but I failed.
I would love your insight in this whole thing, your thought, solution or even a suggestions.

You are free to download the whole project as a package here Download

Special thanks to DMGregory.


texts: Cocos2D: Box2D body that is movable by one type of object but not another

texts:
I'm in the process of creating a simple platform game using Cocos2D 2.0 and Box2D. I'm trying to create a kind of crate object that cannot be moved by the player, but that can be moved by an elephant object. When the player runs up to the crate, it should stop him dead in his tracks (as if he is running into a static Box2D body). If the elephant runs into it it should get knocked out of the way (as if the elephant was running into a dynamic Box2D body of much smaller mass/density). I can't use collision bitmask because of course I want collision to occur in both cases, I just want that collision to result in different things depending on which type of object is hitting the crate.

Anyone have a hint as to how to make this work?

Thanks in advance!


texts: LibGDX: Shape from ShapeRenderer won't show up when put in another class

texts:
I am currently trying to make a little snake clone as my second project with LibGDX. I want to draw the borders of the screen with a ShapeRenderer. The Shape gets displayed flawlessly when I create/draw it in the render method of my game. I wanted to outsource the code into an own "Border"-Class, to get a single object for collision and graphics, but if I do this, the shape does
not get displayed anymore.

Working code before outsourcing to a Border-Class:

public void render(float dt){

...
borderRenderer = new ShapeRenderer();
    borderRenderer.begin(ShapeRenderer.ShapeType.Filled);
    borderRenderer.setProjectionMatrix(gameCam.combined);
    borderRenderer.setColor(1.0f, 0.3f, 0.3f, 1);
    borderRenderer.rect(x , y , width, height);
    borderRenderer.end();
}

ShapeRenderer outsourced, gets not displayed anymore:

public void render(float dt){
...
for (Border border : borders) {
            border.draw();
        }
}

public class Border {
    private ShapeRenderer borderRenderer;
    private OrthographicCamera gameCam;
    private float x, y, width, height;

    public Border(float x, float y, float width, float height, OrthographicCamera gameCam){
        this.gameCam = gameCam;
        this.borderRenderer = new ShapeRenderer();
    }

    public void draw(){
        borderRenderer.begin(ShapeRenderer.ShapeType.Filled);
        borderRenderer.setProjectionMatrix(gameCam.combined);
        borderRenderer.setColor(1.0f, 0.3f, 0.3f, 1);
        borderRenderer.rect(x , y , width, height);
        borderRenderer.end();

    }

}

The border also gets properly initialized in the constructor.

As I was writing this I recognized that using assets for this would probably be a better idea, but I'm still curious.
Thanks in advance for your help !


texts: With Monogame is it possible to await SoundEffect or SoundEffectInstance before playing another SoundEffect or Song?

texts:
I am trying to do some proof of concept work using Monogame, mostly for my own knowledge.  One thing I am having trouble with, however, is timing sounds effects and background music to my liking.

So in my scenario I would like to play a series of SoundEffect objects when the game first loads, and when those effects have finished, play a Song in the background until the game is finished.  When either the player or computer meets victory conditions the game will end, which involves stopping the background Song, playing a win/lose SoundEffect, and loading the end screen.

Here's where I started:

var open0 = Content.Load<SoundEffect>("Open0");
var open1 = Content.Load<SoundEffect>("Open1");
open0.Play();
open1.Play();
bgMusic = Content.Load<Song>("BGTrack");
MediaPlayer.Play(bgMusic);
MediaPlayer.IsRepeating = true;
MediaPlayer.Volume = 0.25f;

This approach ends up just playing all three items simultaneously.  Its more noise than good game experience.

I also tried moving the Play() method calls into an async method and using await on the threads, but of course Play() doesn't return Task so that didn't work. Likewise, SoundEffectInstance and DynamicSoundEffectInstance don't seem to offer any kind of awaitable method calls, unless I'm missing them.

I also tried wrapping subsequent calls in a while loop, using the SoundEffectInstance.State property as my logic control:

var open0 = Content.Load<SoundEffect>("Open0");
var open1 = Content.Load<SoundEffect>("Open1");
SoundEffectInstance open0Instance = open0.CreateInstance();
SoundEffectInstance open1Instance = open1.CreateInstance();

open0Instance.Play();
while (open0Instance.State != SoundState.Playing)
    open1Instance.Play();

while (open0Instance.State != SoundState.Playing &&
        open1Instance.State != SoundState.Playing)
{
    bgMusic = Content.Load<Song>("BGTrack");
    MediaPlayer.Play(bgMusic);
    MediaPlayer.IsRepeating = true;
    MediaPlayer.Volume = 0.25f;
}

Ugly code, but I was trying to figure out what would work...and this didn't.  The first sound played and nothing else, so I'm guessing the State property doesn't implement INotifyPropertyChanged (although I'm not even sure that's relevant outside of MVVM now that I think about it).

The sounds at the end of the game are not giving me trouble because I can simply stop the MediaPlayer and play my closing Effect:

MediaPlayer.Stop();
gameObjects.PlayerWinEffect.Play(1.0f, 0.0f, 0.0f);

So is there a way to control SoundEffect and MediaPlayer timing more explicitly?


texts:
I am writing a Java game.

My problem is to get a really smooth input. If I hit the key W the character has to go forwards, but if I hit A and release the W key, the character doesn't go left ways :( .

It isn't smooth. Which ways are given in common game developing for a smooth input?

My current source code
(Input.java): http://pastebin.com/9Z9qtXik
(MainLoop.handlingInputs): http://pastebin.com/Vx8BzSpL


texts: Gravity CharacterController on moving platform

texts:
I have a third person character witha character controller. In the C# Player script I set the move direction like this which works pretty nice to simulate gravity

private Vector3 _moveDirection = Vector3.zero;

private float Gravity = 20.0f;

void Update()
{
 // ....
_moveDirection.y -= Gravity * Time.deltaTime;

_characterController.Move(_moveDirection * Time.deltaTime + mExternalMovement);
}

The mExternalMovement (also Vector3) I set when the player is on a platform that moves. This works as well for platforms the move e.g. from left to right. But when I use the same for platforms that move up and down the player is like trembling- because of the gravity that is always set for the y movement.

But I have to set the gravity as well when standing on the platform.... any ideas?


texts: How can I have margins or padding around a texture in libgdx?

texts:
I am building a game using libgdx a 2048 like game and I draw the tiles of the board using textures (each texture represents a tile with the number 2 or 4 etc.)

I would like tohave a small space around the square textures. How can I do this ?

Thanks.


texts: Blender 2.6: UV-Matching on Non-Image-Textures

texts:
Situation:
I want to model a piece of wood in Blender (2.63.0). In order to do this I use a set of Noise and Clouds textures on a brown material. But these textures are warped and shown in the wrong size.
Question:
How can I do UV-matching on textures, which aren't of the Image or Movie type? Or is there another way to avoid texture warping? - Thanks for your answers or rather your ideas (and please tell my if anything isn't clear!).


texts: Increasing the probability for similar tiles to generate next to each other

texts:
I'm working on a tile map system, which insofar looks like this (green is grass, air is white, stone is grey, and blue is water):

It uses a simple random number generator so that there's a 45% chance of the tile being grass, 30% chance of it being water, and a 25% chance of it being stone.

Is there anyway I can increase the tendency for grass/stone blocks to clump together to form land masses, and make water blocks form oceans (sort of like what could be seen in a game like Minecraft)?


texts: Mapping Coplanar Vertices in 3D space on to a 2D Plane

texts:
Say I have a plane specified by a normal vector and point on the plane.

I want to specify a 2-D co-ordinate system that lies 'across' the plane, and then use that to find the 2-dimensional distance between any given points on that plane.

I want to do this so that I can specify scaled texture UV co-ordinates on an arbitrary plane. I will use the average centre of all points on the plane (the barycentre?) as UV: 0,0, and then I need a way to determine the 2-dimensional UV value for each point, subsequently.

Here's an example of what I'm trying to do:

The points in bright green are supplied as the inputs, those are the values I'm trying to work out. The dark green is the calculated mean-average centre (the image isn't exactly to scale), and should act as UV: 0,0.

A friend suggested that I take (firstPoint - centrePoint).ToUnit() as my 'x-axis' and then xAxis.Cross(planeNormal) as my 'y-axis'. That seems like a good place to start, but I'm unsure how to use these values to get X/Y co-ordinates for each point.

I don't care what the 'plane-local' X/Y axes are as long as they're the same for each vertex on the plane. I can rotate them in-editor later to make the right alignment manually anyway (I don't think there's any good way to programmatically select a 'default').


texts:
How action game controls should be implemented so that they would work on smart phones as well?

At the moment I use wasd/arrow keys and I am able to handle for example two keys down at the same time.

But many phones has no physical keyboard so should I render some control areas? Are there any JS libraries for this?


texts:
I'm using Blender to export my armatures in relative coordinates, and I'm trying to get to absolute coordinates in my engine. For the above example, the childBone's tip is an offset of [-1,0,0], which is relative to the forward direction of the rootBone, not the global X axis. I understand how matrix multiplication works, but I can't quite seem to get there. Could someone break down the exact steps needed to calculate the absolute coordinates? Here's my attempt:

Vector3f rootRoot = new Vector3f(1,1,0);
Vector3f rootTip = new Vector3f(2,1,0);
Vector3f rootTipOffset = Vector3f.sub(rootTip, rootRoot);
float rootLength = rootTipOffset.length();
Quaternion rootRotation = new Quaternion(new Matrix4f().initRotation(rootTipOffset, Vector3f.Y_AXIS));
Matrix4f rootBindPose = new Matrix4f().initTranslation(rootRoot).mult(rootRotation.toRotationMatrix());
//Matrix for the root of the root bone

Matrix4f childOffset = new Matrix4f().initTranslation(rootTipOffset).mult(rootBindPose);

Vector3f childRoot = new Vector3f(0,0,0); //2,1,0
Vector3f childTip = new Vector3f(-1,0,0); //2,2,0
Vector3f childTipOffset = Vector3f.sub(childTip, childRoot);
float childLength = childTipOffset.length();
Quaternion childRotation = new Quaternion(new Matrix4f().initRotation(childTipOffset, childOffset.getRotation().getUp()));
Matrix4f childBindPose = childOffset.mult(new Matrix4f().initTranslation(childRoot).mult(childRotation.toRotationMatrix()));
Matrix4f testMatrix = new Matrix4f().initTranslation(new Vector3f(0,0,childLength)).mult(childOffset);
System.out.println(testMatrix.getTranslation()); //Prints [2, 1, 1]


texts: What would be the best way to implement a multi-directional "board game" movement system?

texts: I'm pretty new to game dev, and can't figure out how to do this, even though it is probably really easy. If you need more reference, look up some gameplay of the Wii game Dokapon Kingdom, that's the kind of system I'm trying to create. I also made a picture to help you better understand my dilemma. Thank you all so much in advance!


texts: With flash/flex games talking to backend, is it pull only or can the game server push?

texts: With flash based games (or flex), is it a pull or request/response system or is it possible for the game server (say java based) to actually push out to its remote flash clients?


texts: Get color array with alpha for an image in java

texts:
I can get the pixel array like this:

int[] pixels = image.getRGB(0, 0, width, height, null, 0, width);

But it ignores the alpha channel, I only get the rgb (I'm reading a PNG image). How can I get the alpha channel too?


texts: Can I use one set of images to represent multiple sprites in Java?

texts:
I've got a game that has 3 basic sprites, at the moment I'm loading 8 images into each sprite for animating.
Each character class has a sprite object.
if I've got 10 characters on screen at once then that's 80 images loaded in to memory.
Can I make a central sprite class that only holds 8 images for each of the 3 sprites, then get the character objects to request the relevant images from the central sprite class, thereby massively reducing the memory required for the images?


texts: How to change size of collider attached to UI Image in unity

texts:
I have a circle image which has a Cicle collider 2D and Rigidbody 2D attached to it and its size (width and height) is constantly increasing in script like this:

rt = circle.GetComponent<RectTransform>();
float width = rt.rect.width + increment;
float height = rt.rect.height + increment;
rt.sizeDelta = new Vector2 (width, height);

The collider doesn't change size with UI Image as it expands...what should i do in order to make the collider change size as UI Image changes size.


texts: Unity LineRender texture distorts in Game view

texts:
I have a LineRenderer with a tiled texture of repeating arrows. I have a script that scrolls the texture.

However the texture distorts as it moves. The distortion goes back and forth repeating. Without the script the arrows are still distorted in game view so I dont think it is an issue particularly with the scroll.

public class LineArrow : MonoBehaviour
{
    public float scrollSpeed = 1f;
    public Renderer _renderer;
    // Start is called before the first frame update
    void Start()
    {
        _renderer = GetComponent<LineRenderer>();
    }

    // Update is called once per frame
    void Update()
    {
        float vOffset = Time.time * scrollSpeed;
        _renderer.material.SetTextureOffset("_MainTex", new Vector2(vOffset, 0));
    }
}

The first image is the scene view and the second is the game view


texts:
so I've been trying to create a basic particle system in pygame which I can later expand upon but I've run into a spot of bother creating the particle emitter. Obviously what's supposed to happen is it's supposed to create a new particle every frame (or a set of particles) but instead it just alters the particle that's created first time round. I understand why this is happening, as far as the game is concerned, every frame I add the same object to the particle list so when I call the update function it calculates the positional and velocity sums multiple times, what I'm having trouble with is fixing it. How would I go about making a new particle every time?

My existing classes for this are as follows:

class Particle():
    def __init__(self, pos, vel, accel, image):
        self.pos = pos
        self.vel = vel
        self.accel = accel
        self.life = 255
        self.lifecount = 1
        self.image = image

    def update(self):
        self.vel.add(self.accel)
        self.pos.add(self.vel)
        self.life -= self.lifecount

    def is_dead(self):
        if self.life <= 0:
            return True
        else:
            return False

class Emitter():
    def __init__(self, pos):
        self.pos = PVector(pos[0], pos[1])
        self.particles = []
        self.part_list = [Particle(self.pos, PVector(0,2), PVector(0,0), pygame.image.load("resources/particles/fireball.png"))]

    def update(self):
        self.particles.extend(self.part_list)
        for p in self.particles[:]:
            p.update()
            if p.is_dead():
                self.particles.remove(p)

    def draw(self, surface):
        for p in self.particles:
            x = p.pos.x
            y = p.pos.y
            temp = pygame.Surface((p.image.get_width(), p.image.get_height())).convert()
            temp.blit(surface, (-x, -y))
            temp.blit(p.image, (0, 0))
            temp.set_alpha(p.life)
            surface.blit(temp, (x, y))

The positions, velocities and accelerations are all part of a vector class with vector math functions.


texts:
I'm learning OpenGL and I don't understand why my texture is flipped if I give
as UVs the "matching" vec2 of the mesh's vertex (vec3).

Example:

vert -256 -256
uv   0    0

vert 256 256
uv   1    1

I've had to try a different order for the UVs to be able to get the correct result...

Can someone explain why is that so?
Thanks.

Screenshots:
http://imgur.com/a/49ZVp

This are the snippets of code I use:

// Create texture
GLuint texDebugId;

// RGBA Texture:
// R G
// B A

unsigned char texDebugBuf[] = {
    255, 0, 0, 255,
    0, 255, 0, 255,
    0, 0, 255, 255,
    0, 0, 0, 0,
};
glEnable(GL_TEXTURE_2D);
glGenTextures(1, &texDebugId);
glBindTexture(GL_TEXTURE_2D, texDebugId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 2, 2, 0, GL_RGBA, GL_UNSIGNED_BYTE, texDebugBuf);
glBindTexture(GL_TEXTURE_2D, 0);
glDisable(GL_TEXTURE_2D);

//------------------------------

// Prepare VBOs
static const GLfloat verts[] = {
    -256.0f, -256.0f, 0.0f,
    256.0f, -256.0f, 0.0f,
    -256.0f, 256.0f, 0.0f,
    256.0f, 256.0f, 0.0f
};

/*
// FLIPPED (but why?)
static const GLfloat uvs[] = {
    0.0f, 0.0f,
    1.0f, 0.0f,
    0.0f, 1.0f,
    1.0f, 1.0f,
};
*/

// OK
static const GLfloat uvs[] = {
    0.0f, 1.0f,
    1.0f, 1.0f,
    0.0f, 0.0f,
    1.0f, 0.0f,
};

// Upload vertices
glBindBuffer(GL_ARRAY_BUFFER, vbo_id);
glBufferData(GL_ARRAY_BUFFER, sizeof(verts), verts, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);

// Upload UVs
glBindBuffer(GL_ARRAY_BUFFER, vbo_tex_id);
glBufferData(GL_ARRAY_BUFFER, sizeof(uvs), uvs, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);

//------------------------------

// Render
glBindTexture(GL_TEXTURE_2D, texId);

glEnableVertexAttribArray((GLuint) pd.vertex_a);
glEnableVertexAttribArray((GLuint) pd.uv_a);

// Vertices
glBindBuffer(GL_ARRAY_BUFFER, vbo_id);
glVertexAttribPointer(
    (GLuint) pd.vertex_a,  // attribute id
    3,                     // size
    GL_FLOAT,              // type
    GL_FALSE,              // normalized?
    0,                     // stride
    (void *)0              // array buffer offset
);

// UVs
glBindBuffer(GL_ARRAY_BUFFER, vbo_tex_id);
glVertexAttribPointer(
    (GLuint) pd.uv_a,      // attribute id
    2,                     // size
    GL_FLOAT,              // type
    GL_FALSE,              // normalized?
    0,                     // stride
    (void *)0              // array buffer offset
);

glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

glBindBuffer(GL_ARRAY_BUFFER, 0);
glDisableVertexAttribArray((GLuint) pd.uv_a);
glDisableVertexAttribArray((GLuint) pd.vertex_a);

glBindTexture(GL_TEXTURE_2D, 0);

Note:

proj matrix:
proj = glm::ortho(-320, 320, -240, 240, -1.0f, 100.0f); // 640x480 with 0,0 at center

camera matrix:
cam_target = glm::vec3();
cam_up = glm::vec3(0.0, 1.0f, 0.0f);
cam_pos = glm::vec3(0.0f, 0.0f, 5.0f);
camera = glm::lookAt(cam_pos, cam_target, cam_up);

MVP matrix:
glm::mat4 mvp = proj * camera;


texts:
I'm writing a small game at the moment. Presently, I have one or two design elements that aren't locked down yet, and I wanted to ask for input on one of these.

For dramatic effect, the player's character in my game is immobilised, alone and has a supposedly limited amount of ammo for their weapons. However, I would like to periodically resupply the player with ammo (for the purpose of balancing the level of difficulty and to allow the player to continue if they're doing well).

I'm trying to think of a method of resupply that's different to the more familiar strategies of making ammo magically appear or having the antagonists drop some when they die. I'd like to emphasise the notion of the player's isolation as much as possible, and finding a way of 'sneaking' ammo to the player without removing too much of that emphasis is basically what I'm trying to think of (it's definitely a valid argument that resupplying the player removes it anyway)

I have considered a sort of simple in-game 'store', where kills get you points that you can spend on ammo for your favourite weapon. This might work well, and may also be good for supporting a simple micro-transaction business model within the game. However, you'd have to pause the game often to make purchases, which would interrupt the action, and it works against the notion of isolation.

Any thoughts?


texts: Calculate line intersecting most points, based on random points in a grid

texts:
I have been struggling with a math issue for a game I've been developing. I am in need to find the best starting and ending point for a straight line so that it intersects most of the circles (the blue one always needs to be intersected).

As you can see in the image below I want to be able to calculate that green line based on the given points, where the blue one is required to be intersected. The rule is that the line has to intersect as many circles as possible and should always intersect the blue circle.

I've tried to apply the best fit algorithm but that doesn't really takes intersection into consideration. Would appreciate if someone could help me out solving the math for this.

There will only ba a maximum of 5 circles while calculating the line.

Note: I am not deeply involved into math, only know the basic symbols for it.


texts:
I just recently asked this question and the conclusion seems to be that using genetic programming (GP) for Procedural Game Content Creation hasn't really been  done. I want to change that.

I'm fairly certain GP could be deployed to help find a new terrain generator. The question I'm getting to is how might this be achieved?

All GPs have a few basic parts that can be generalized for all GPs (parent selection, recombination, mutation, survival). I can figure those out on my own. The issue arises in the problem specific parts. These are how you represent the problem in code (this usually uses a tree), and how you evaluate how good a generator might be (this can be one or more values).

The questions in a nutshell:

How would you represent a terrain generator in a way that can be
parsed into a tree?
What kind of terrain would this have to generate? (heightmap, vertex
graph,...)

The less this is based on a hightmap the better.
What would be used to evaluate the fitness of a solution?

ex: we want interesting terrain so we could have one of the values be the average change in the normals for each vertex on the terrain.


texts: How often to SendData() in my peer-ro-peer XNA game?

texts:
Currently I call

myLocalNetworkGamer.SendData(myPacketWriter, ...)

every Update(). 60 times a second sounds too much. Is there an inbuilt way to only send less often? How often should network players update their position?

UPDATE It is a real time shooter. Also does XNA backlog the updates if the other peer is not receiving them fast enough or are packets dropped in this case?


texts: How to pass arguments with BungeeCord/Bukkit plugin messaging

texts:
I am trying to send a plugin message from Bukkit, to BungeeCord, but can not figure out how to send arguments.
Here is the code from the Bukkit plugin, which sends the message:

  ByteArrayDataOutput out = ByteStreams.newDataOutput();
  out.writeUTF("BungeeCord"); out.writeUTF("Argument");

  // If you don't care about the player // Player player =
  // Iterables.getFirst(Bukkit.getOnlinePlayers(), null);
  // Else, specify them
  Player plr =  Bukkit.getPlayerExact("spacegeek224");

  plr.sendPluginMessage(p, "BungeeCord",
  out.toByteArray());

Here is the code in the main class of my BungeeCord plugin:

@Override
    public void onEnable() {
        this.getProxy();
        ProxyServer.getInstance().getPluginManager().registerListener(this, new ChannelListener());

        this.getProxy();
        ProxyServer.getInstance().registerChannel("Return");
    }

And finally, here is the code for the ChannelListener:

package net.spacegeek224.metro.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.event.PluginMessageEvent;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.event.EventHandler;

public class ChannelListener implements Listener {

    @EventHandler
    public void onPluginMessage(PluginMessageEvent e) {
        if (e.getTag().equalsIgnoreCase("BungeeCord")) {
            DataInputStream in = new DataInputStream(new ByteArrayInputStream(e.getData()));
            try {
                String channel = in.readUTF(); // channel we delivered
                if(channel.equals("BungeeCord")){
                   ProxyServer.getInstance().broadcast(new ComponentBuilder(e.getReceiver().toString()).create());

                } else {
                    ProxyServer.getInstance().broadcast(new ComponentBuilder(e.getReceiver().toString()+":"+channel).create());

                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }

        }
    }

    public void sendToBukkit(String channel, String message, ServerInfo server) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        DataOutputStream out = new DataOutputStream(stream);
        try {
            out.writeUTF(channel);
            out.writeUTF(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
        server.sendData("Return", stream.toByteArray());

    }
}

I have tried many things, including Google, and looking at what other methods are available, but have come up with nothing.


texts: We're a small company without enough employees to run a large scale beta in house.  The app is geo-location based so we're trying to recruits some beta testers from all over that aren't "friends and family".  Are there any sites or communities dedicated to something like this?


texts:
I absolutely cannot stand animating in Unity.
I am making an FPS game with many weapons, and each weapon has four animations: running, jumping, aiming, and shooting. I would like to create a .anim file in Unity with the keyframes of the character and the weapon, and then edit that .anim file in Blender. How would I edit .anim files in Blender?


texts: Unity 2d, Place object nearest to a coordinate without overlap?

texts: I am working on a game similar to Pool (Carrom actually). I need to place coins at the center of the board or nearest possible to it without overlapping any other coins. This is a 2d game.


texts: How to find the degree of interpolation?

texts:
I have two quaternions: A and B. I want to lerp between them.

Given another quaternion C, I want to find the variable unknown, as seen in the equation below:

Quaternion.Lerp(A, B, unknown) == C

(Unfortunately, the equation above is misleading. In the scenario that C is "out of range" -- i.e. not along the shortest path to get from A to B -- unknown should simply be 0 or 1.)

How can I do so?


texts: DirectX11 Swap Chain RGBA vs BGRA Format

texts:
I was wondering if anyone could elaborate any further on something that's been bugging me.

In DirectX9 the main supported back buffer formats were
D3DFMT_X8R8B8G8 and D3DFMT_A8R8G8B8 (Both being BGRA in layout).

http://msdn.microsoft.com/en-us/library/windows/desktop/bb174314(v=vs.85).aspx

With the initial version of DirectX10 their was no support for BGRA and all the textbooks and online tutorials recommend
DXGI_FORMAT_R8G8B8A8_UNORM (being RGBA in layout).

Now with DirectX11 BGRA is supported again and it seems as if microsoft recommends using a BGRA format as the back buffer format.

http://msdn.microsoft.com/en-us/library/windows/apps/hh465096.aspx

Are there any suggestions or are there performance implications of using one or the other?

(I assume not as obviously by specifying the format of the underlying resource the runtime will handle what bits your passing through and than infer how to utilise them based on the format.)


texts: How do I implement a AABB-Sphere collision

texts:
i have been trying to implement an aabb-sphere collision.

This is what I tried

@Override
public boolean collides(Sphere other) {
    Vector3f axis = Vector3f.sub(Vector3f.sub(max, min, null), other.getCenter(), null);
    float dist = axis.length();

    return dist < (other.getRadius() * other.getRadius());
}


texts:
I have .tmx map loaded, and a camera to see it. The map is bigger than the camera viewport, so I need to move that viewport scrolling the camera.
Now I want to draw a sprite on the map. To do that, at the beginning I used the batch.draw() method, trying to calculate the position relative to the camera, but it didn't worked. After that I found that I could add this line:

batch.setProjectionMatrix(camera.combined);

using an Sprite class to draw my object. Howevert, it won't draw on screen; I don't know why.
Here's my code:

MOVING CAMERA:

private void controlCamera()
    {
        if (Gdx.input.isKeyPressed(Keys.RIGHT) && camera.position.x <= mapPixelWidth + camera.viewportWidth/2)
        {
            camera.position.x += mapSpeed;
        }
        else if (Gdx.input.isKeyPressed(Keys.LEFT) && camera.position.x > camera.viewportWidth/2)
        {
            camera.position.x -= mapSpeed;
        }
        else if (Gdx.input.isKeyPressed(Keys.UP) && camera.position.y <= mapPixelHeight + camera.viewportHeight)
        {
            camera.position.y += mapSpeed;
        }
        else if (Gdx.input.isKeyPressed(Keys.DOWN) && camera.position.y > camera.viewportHeight/2)
        {
            camera.position.y -= mapSpeed;
        }
    }

Note that I'm moving the camera between viewport/2 and viewport/2 + map size, since the left down corner is situated at (viewportWidth/2, viewportHeight/2). That's the default position where my .tmx map is drawn.

SPRITE RENDER METHOD:

public void render(SpriteBatch batch, float stateTime)
    {
        currentFrame = anim.getKeyFrame(stateTime, true);
        sprite.setPosition(getDrawCoords().x, getDrawCoords().y);
        sprite.setSize(currentFrame.getTexture().getWidth()/2, currentFrame.getTexture().getHeight());
        sprite.setRegion(currentFrame);
        sprite.draw(batch);
    }

GETDRAWCOORDS METHOD:

public Vector2 getDrawCoords()
{
    int x =  (int) (map.camera.viewportWidth/2 + map.tilePixelWidth * xMap);
    int y = (int) (map.camera.viewportHeight/2 + map.tilePixelHeight * yMap);
    return new Vector2(x,y);
}

I really don't know if I wrote the sprite.setPosition correctly. I tried with lots of things but it never get drawn.

MAIN CLASS RENDER METHOD:

public void render() {
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        map.update(); //Include camera mov
        stateTime += Gdx.graphics.getDeltaTime();
        map.render(); //draw the map. Include camera.update()
        batch.setProjectionMatrix(camera.combined);
        batch.begin();
        units.get(0).render(batch, stateTime); //render my unit
        batch.end();

    }

Using a batch.draw() with the texture draw well the sprite in the initial position, but when I try to move the camera it goes crazy. I tried to write the vector position in terms of the other vector, but it doesn't work, and I'm pretty sure of my vector calculus. I'm trying with the sprite and using the projection matrix because I read it give a position relative to camera, but now I can't get my sprite drawn.

Any help is appreciated. Thank you!


texts: How is the result returned in SharpDX.DirectInput.Device.Acquire()?

texts:
The documentation of IDirectInputDevice8::Acquire says:

  Return Value

  If the method succeeds, the return value is DI_OK, or
  S_FALSE if the device was already acquired. If the method fails, the
  return value can be one of the following error values:
  DIERR_INVALIDPARAM, DIERR_NOTINITIALIZED, DIERR_OTHERAPPHASPRIO.

However, SharpDX's Device.Acquire() is a void. The documentation for this method  is not really helpful.

How can I know if a call to Device.Aquire() has succeeded or not?

Alternatively, where is the source for Acquire() located? I've tried looking at the contents of Device.cs, but not only it is not located in there, but Device is marked as partial, which means the source for Acquire() is probably in a different file, but I can't seem to find it.


texts: How do you set event after a pawn takes damage?

texts:
How can I set event after bot/pawn takes damage in UDK? (possibly in Kismet?)

I need to do something similar to this: http://www.youtube.com/watch?v=gjRf5lTcWLY


texts: How can I make terrain texturing look detailed both close-up and far away?

texts:
I attempting to make my game have very detailed textures, and in general look pretty. However, I'm having some issues with that.

Let's take a look at a rock texture close up:
Picture.

As you can see, this looks perfectly adequate for a 3D game up-close. However, I'm struggling to get this working at a distance: Picture

At a distance, the texturing looks obviously uniform, and looks very tiled and very bland. Picture

How can I solve this issue to make my textures look more detailed at all distances? I obviously have mipmapping enabled, but I don't understand why the texture looks so badly detailed and what I can do to improve it.


texts: Is it feasible to create a blockchain to use as a market place game mechanic without extreme inflation?

texts:
After watching a fascinating video about block chains, the narrator brought up the idea of using block chains in video games. The example he used was in an MMO type of situation where the player used a sword to defeat a dragon and then the sword became known as Dragon Slayer and its stats would go up and the value of it would increase as well. The player would then sell it to another player who used it to defeat some other powerful monster and it gained more stats and its name changed again. Obviously, it needs to be fine tuned a lot more before it is a feasible idea considering if a sword is owned by say 1000 players then, its description couldn't hold that much information and would need to be limited.

I am thinking of using the block chains similar to the above example except bring it to more of a market place type of mechanic. The player maybe goes through dungeons to defeat monsters. The deeper you go the higher the value of your weapon goes up (stats and gold value) and the higher dungeon you get to the more powerful weapon you will need.

As I think about this concept more I find myself wondering how I could avoid extreme inflation of the in game currency. I'd like to get away from micro-transactions but, I know that is a big tool in helping keep inflation down. (i.e. a second currency). What are some other key ways to keep inflation down in a fast growing in-game economy?

I guess the main thing I see happening is that the balance between the skills earned vs. value earned on a weapon need to be extremely similar so that combat farming doesn't occur in the lower levels but also so that players don't just hold onto the same weapon the whole time they play the game either.

I guess that could be part of the solution but, maybe there are more concrete answers out there that may prevent extreme inflation of in game currencies.


texts:
Is Windows 8 supporting DirectX 9? Because I was looking through some samples written in C++ and DirectX 9 made for Windows 8. It wasn't that, like I know it ( look here http://directxtutorial.com/Lesson.aspx?lessonid=111-4-2 ). E.g. Inizialising DirectX with COM:

ComPtr<ID3D11Device1> dev;
ComPtr<ID3D11DeviceContext1> devcon;

It's just weird because I know it with the old way:

ID3D11Device *dev;
ID3D11DeviceContext *devcon;

( I hope you understand what I want to tell )

I hope it hasn't change completely due the released their new OS.


texts: How to handle the birth and death of particle without reading from the buffer

texts:
I've implemented a simple particle system where each particle has a position, velocity, age and lifespan stored in different SSBOs.

Most of the data including all the position, velocity and age is updated through a compute shader. And emiting new particles is handled by CPU since it's a serial process. But in order to track whether each particle is alive or dead, I have to read all the lifespan data back to CPU from the SSBO (using glGetBufferSubData()), which do stalls the GPU I'm afraid.

So I was wondering is there any way to prevent reading the data back from GPU. I found a demo particle system made by AMD using directX, which uses a dead list and an alive list in the compute shader. But I have no idea how to achieve this with GLSL. Any ideas?

Demo code:

...

// The dead list, so any particles that are retired this frame can be added to this list
AppendStructuredBuffer<uint>            g_DeadListToAddTo       : register( u2 );

// The alive list which gets built using this shader
RWStructuredBuffer<float2>              g_IndexBuffer           : register( u3 );

...

// Dead particles are added to the dead list for recycling
if ( pb.m_Age <= 0.0f || killParticle )
{
    pb.m_Age = -1;
    g_DeadListToAddTo.Append( id.x );
}

...


texts: Unity UI's Image component renders without anti-aliasing?

texts:
I tried the sprite's import settings with point filtering, with billinear filtering, I also tried changing my canvas' UI Scale mode to Screen Space - Camera, but nothing seems to fix it.

I also tried scaling it up and down, but it rendered with these edges all the time.

How could I smoothen it? Thanks in advance.


texts: How to find all possible destinations, within a certain walking distance of a unit?

texts:
I have a standard 2D grid that i use for pathfinding.
I already use A* to find the path of my units when I want to move them around.

What I need to implement now is a preview of all possible destinations of the unit when it is selected.

Here is what I want to achieve.

The yellow/orange cells represent the possible destinations.

I want to make this as optimized as possible, because it can be executed on very big maps and for multiple units.

I have something in mind but I wonder if there is better approach for this.

Here is my idea:

Get a list of all cells that are walkable in a square around my unit.
The square will be from Unit.X - Unit.Speed to Unit.X + Unit.Speed for X axis and Unit.Y - Unit.Speed to Unit.Y + Unit.Speed for Y axis.
For each element in this list, execute A* search to see if it is possible to find a path.

By doing the search for only the cells that are within my unit range I should be able to do this on big maps.

Basically this is the same feature that we have in games like Heroes 3 and many other turn based games.

Screenshot:

I was also wondering when it is a good idea to execute this pathfinding logic.
When you select a unit (might result a spike) or when something moves on the map to update the list of all possible destinations of all units on the map.


texts: How do i store blocks information in my Voxel game?

texts:
I am trying to make a voxel game.

Voxel games made by blocks and each block has it's own information such as durability, step sounds, strength, ...

How do i store these information inside of blocks? or is it true to save their information inside of themselves.

Do i store them on all blocks instances or static properties?

public class Block
{

    public virtual float durability
    {
        get
        {
            return 1f;
        }
    }

    public virtual float strength
    {
        get
        {
            return 1f;
        }
    }

    public virtual StepSound stepSound
    {
        get
        {
            return new StepSound ( "stone.ogg" );
        }
    }

}

Then create a class by inheriting Block class:

public class BlockDirt : Block
{

    public override float durability
    {
        get
        {
            return 0.5f;
        }
    }

    public override float strength
    {
        get
        {
            return 0.5f;
        }
    }

    public override StepSound stepSound
    {
        get
        {
            return new StepSound ( "dirt.ogg" );
        }
    }

}

Now i have all the above properties inside of any BlockDirt instances.

But it takes to much memory. just think i have 100 BlockDirt.

Or Do i create a base class:

public class Block
{

}

Then inherit it for creating blocks:

public class BlockDirt : Block
{

    public static StepSound stepSound = new StepSound ( "dirt.ogg" );
    public static float durability = 0.5f;
    public static float strength = 0.5f;

}

And use the BlockDirt static properties for all BlockDirt instances?

I don't know how to get static properties from class instance, but i know i can do it using Reflection but it takes more CPU and memory than instance based data.

What should i do?

Any help is appreciated.


texts:
I’m converting a game from XNA to iOS with Monogame.
In the code snippet below, smallDeform is a Texture2D on which I call the GetData method.

smallDeform = Game.Content.Load<Texture2D>("Terrain/...");
smallDeform.GetData(smallDeformData, 0, smallDeform.Width * smallDeform.Height);

I’m having some problem with Monogame because the feature in iOS has not been implemented yet because it returns this exception.

#if IOS
   throw new NotImplementedException();
#elif ANDROID

I tried to serialize the data in a XML file from Windows to load the whole file from iOS. The serialized files weight more than 100MB each, that is quite unacceptable to parse.

Basically, I’m looking for a workaround to get the data (for instance a uint[] or Color[]) from a texture without using the GetData method.

PS: I'm on Mac, so I can't use the Monogame SharpDX library.

Thanks in advance.


texts: Problems about oriented bounding boxes collision detection

texts:
I get a question for the following code which detects if two OOBs collide by SAT. The OBBs struct is also listed below.

struct OBB {
Point c; // OBB center point
Vector u[3]; // Local x-, y-, and z-axes
Vector e;  // Positive halfwidth extents of OBB along each axis
}

int TestOBBOBB(OBB &a, OBB &b)
{
float ra, rb;
Matrix33 R, AbsR;
// Compute rotation matrix expressing b in a’s coordinate frame
for(inti=0;i<3;i++)
   for(intj=0;j<3;j++)
      R[i][j] = Dot(a.u[i], b.u[j]);
//Compute translation vector t
Vector t = b.c - a.c;
// Bring translation into a’s coordinate frame
t = Vector(Dot(t, a.u[0]), Dot(t, a.u[2]), Dot(t, a.u[2]));

// Compute common subexpressions. Add in an epsilon term to
// counteract arithmetic errors when two edges are parallel and
// their cross product is (near) null (see text for details)
for(inti=0;i<3;i++)
    for(intj=0;j<3;j++)
        AbsR[i][j] = Abs(R[i][j]) + EPSILON;

// Test axes L=A0,L=A1,L=A2
for(inti=0;i<3;i++) {
    ra = a.e[i];
    rb = b.e[0] * AbsR[i][0] + b.e[1] * AbsR[i][1] + b.e[2] * AbsR[i][2];
    if (Abs(t[i]) > ra + rb) return 0;
}

// Test axes L=B0,L=B1,L=B2
for(inti=0;i<3;i++) {
    ra = a.e[0] * AbsR[0][i] + a.e[1] * AbsR[1][i] + a.e[2] * AbsR[2][i];
    rb = b.e[i];
    if (Abs(t[0] * R[0][i] + t[1] * R[1][i] + t[2] * R[2][i]) > ra + rb) return 0;
}

// Test axis L=A0xB0
ra = a.e[1] * AbsR[2][0] + a.e[2] * AbsR[1][0];
rb = b.e[1] * AbsR[0][2] + b.e[2] * AbsR[0][1];
if (Abs(t[2] * R[1][0] - t[1] * R[2][0]) > ra + rb) return 0;

//reset code are omitted

For the part "Test axes L=A0,L=A1,L=A2",
why do we multiply each b.e[i] by the component from each axis in a's coordinate frame then add the result together?
I know this part want to project the half positive extents onto each axis in a's coordinate frame, but it should do the dot product with the b.e vector and the projected axis, am I wrong?
(that is b.e[0] * AbsR[0][i] + b.e[1] * AbsR[1][i] + b.e[2] * AbsR[2][i])

For the part "Test axes L=B0,L=B1,L=B2",
It seems a.e vector is multiplied by each axis in a's coordinate frame, why don't transform the a.e vector into the b's coordinate frame since they are not at the same coordinate frame?

For the part "Test axis L=A0xB0",
Why can we get ra and rb values by that arithmetic operation?
What does Abs(t[2] * R[1][0] - t[1] * R[2][0] mean?


texts:
So, I'm developing a 2D, tile based game and a map maker thingy - all in Java.

The problem is that recently I've been having some memory issues when about 4 maps are loaded. Each one of these maps are composed of 128x128 tiles and have 4 layers (for details and stuff).

I already spent a good amount of time searching for solutions and the best thing I found was run-length enconding (RLE). It seems easy enough to use with static data, but is there a way to use it with data that is constantly changing, without a big drop in performance?

In my maps, supposing I'm compressing the columns, I would have 128 rows, each with some amount of data (hopefully less than it would be without RLE). Whenever I change a tile, that whole row would have to be checked and I'm affraid that would slow down too much the production (and I'm in a somewhat tight schedule).

Well, worst case scenario I work on each map individually, and save them using RLE, but it would be really nice if I could avoind that.

EDIT:
What I'm currently using to store the data for the tiles is a 2D array of HashMaps that use the layer as key and store the id of the tile in that position - like this: private HashMap< Integer, Integer >[][]


texts: Heightmap using Simplex noise with octaves: help with parameters and interpretation

texts:
I've found a few pieces of code around, where Java code for Simplex noise (based on this widely quoted paper) was coupled with octaves to get a heightmap. However those classes/snippets are NOT in the -1,1 range despite saying so, so I had to add some modifications.

By trial and error and some brain work I got to a version that produces an output within -1 and 1, here (could you sanity check it please? It this correct?):

public static float[][] generateOctavedSimplexNoise(final int width,
                                                    final int height,
                                                    final int octaves,
                                                    final float roughness,
                                                    final float scale)
{
    final float[][] totalNoise = new float[width][height];
    float layerFrequency = scale;
    float layerWeight = 1f;
    float weightSum = 0f;

    for (int octave = 0; octave < octaves; octave++)
    {
        // Calculate single layer/octave of simplex noise, then add it to total noise
        for (int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                totalNoise[x][y] += (float) noise(x * layerFrequency, y * layerFrequency) * layerWeight;
            }
        }

        // Increase variables with each incrementing octave
        layerFrequency *= 2f;
        weightSum += layerWeight;
        layerWeight *= roughness;
    }

    // scale output between -1 and 1, as we are doing
    // a weighted average
    for (int x = 0; x < width; x++)
    {
        for (int y = 0; y < height; y++)
        {
            totalNoise[x][y] /= weightSum;
        }
    }

    return totalNoise;
}

My understanding is that "roughness" must vary between 0 and 1, and influences the "flatness" of the final image. What "scale" is I cannot fathom yet - any help?. Also, more than 6-7 octaves seems useless in my tests, hopefully this is expected.

But most of all my question is: how do I work in a top-down way? That is, knowing the kind of map I roughly want (a big island in the ocean, with a few lakes and a few mountains, but mostly plain and hills) how do I choose parameters and the thresholds for terrain types?

I've tried a lot, but I can't seem to control the function to produce a nice map..


texts: How to create pixel perfect noise shader?

texts:
I would like to know how they created the pixel perfect noise shader in monument valley 2 in that b/w level (example picture). I think it starts with a billboard shader, but I have no clue how to scale the texture to it's native size.

I'm using ShaderLab (unity, mobile platforms)


texts: Is requirements analysis useful in game development?

texts:
I'm a software engineering student with a game development focus. How big of a part does requirement analysis play in game development?

I'm asking because I'm trying to decide whether to take a class on requirements analysis. Here is a description:

  An in-depth study of current research and practice in requirements elicitation, requirements, analysis, requirements specification,requirements verification and validation, and requirements management.

Would this type of knowledge be useful for an independent game developer? (The alternatives are artificial intelligence or software architecture.)


texts:
I am trying to draw point sprites in OpenGL ES 2.0, but all my points end up with a size of 1 pixel...even when I set gl_PointSize to a high value in my vertex shader.

How can I make my point sprites bigger?


texts:
Here is my issue.

I currently have Box2D setup and working. But, it works with my Entity system. So I can create static objects and dynamic moving ones, and they simulate fine.

However, my world is made up of tiles.

I have very easy ways of determining which Tiles a Body is intersecting, but I'm not sure how to tell this to Box2D.

I could obviously turn each tile into a Body but that would waste a lot of ram because I have 10s of thousands of tiles.

The tiles also form some cool patterns and can be converted to an empty tile at will.

My thought was to do something like this:

-Iterate the bodies, find which tiles they are touching, add these as static bodies into the world. Step the world. Remove the bodies.

This seems like a bit of a hack though and I am wondering if anyone can think of a better way.

Thanks


texts:
This is a follow-up question to How to reapply force applied to one object to another object

  I want to make two objects move, react to collisions and other stuff as if they were one.
  For example, Objects A and B are entangled.
  When Object C rams into Object A and starts moving with it, Object B should start moving with it. When Object B hits a wall, Object A should act like it also hit a wall.
  I tried changing position/speed every frame, but this only works when done in one direction.
  Now, I want all forces applied to any of the objects to also apply to the other objects entangled to it.

Edit: This is the new code which only fails when multiple collisions happen at once

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

[RequireComponent(typeof(Rigidbody))]
public class EEScript : MonoBehaviour
{
    public List<EEScript> activeObjects;
    public new Rigidbody rigidbody;
    public Vector3 lastPosition;
    // Start is called before the first frame update
    void Start()
    {
        rigidbody = gameObject.GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        lastPosition = transform.position;
    }

    private void OnCollisionEnter(Collision collision)
    {
        foreach (EEScript entangled in activeObjects)
        {
            if (entangled == this) continue;
            Rigidbody rb = entangled.rigidbody;
            if (rb is null) continue;
            rb.velocity = rigidbody.velocity;
            rb.angularVelocity = rigidbody.angularVelocity;
            entangled.transform.position = entangled.lastPosition + transform.position - lastPosition;
        }
    }
}


texts: Unity - Sprite with collider2d hits a rigidbody - Searching for a way to make the rigidbody not to react

texts:
When a sprite with a box collider 2d hits the game object (rigid body),

the collision detection is fired and I get the event.

However, the sprite moves the rigidbody and I have trouble restoring it back.

I tried to create a collision detection without ridigbody but without success.

Is there a way so that the ridigbody is never moved?

Hint: I can't make it static, since the rigidbody becomes immovable.


texts: Ideas for refactoring regarding simple state management in entities and level

texts:
I'm actually developing a very simple 3D game, Arkanoid/Breakout style, with very simple mechanics, and it's progressing while I learn the game dev domain own concepts and techniques (My background is C/C++ middleware/low-level systems programmer).

I've advanced to a functional game loop, input, movement, collision checks, all it's working, but I reached to a day where the code was a mess, e.g: my Level class was doing too much. So I partitioned, OOP style, the code in several classes.

My intention is to get ideas from more experienced programmers regarding how Game state and substates relate with entities. My general picture is:

A game object which contains the main loop
A level object which contains a World instance with a list of all entities.
A renderer class which does Direct2D and Direct3D rendering.

Prior to the major refactoring, I was doing something like

Level::Update(float clockMs)  {
  switch (m_state)
    case (LevelState::Preloading) { ... }
    case (LevelState::Load) { ...}
    case (LevelState::Playing) {
        UpdateBallPosition ( ... )
        CheckCollisions( ...)
    }

}

Level contained references to ball, game bricks, etc. Now  I create the entities in the Level startup and add them to the World instance. (World is a member of Level).

Now I want to move all state-related code to the entities themselves. Suppose "Ball", it shouldn't do anything until Level is in LevelState::Playing. Where do you store typically state for the current Level (suppose a closed-level game)? It's correct to store entities with a pointer to the World and the World to mantain a pointer to the Level containing it? It's a tightly coupled architecture but I want to discuss how to relate world/level states with entities, and how the entities acknowledge in which higher-level states they are.

Keep in mind that I accept good procedural or data-driven approaches. I'm not an OOP fanatic, I think good designs can be built upon several paradigms. Thanks.


texts:
I want to add a Component to a GameObject using an existing instance of the Component class.

Let's say I have the class Foo:

public class Foo : MonoBehaviour {
    int id {get; set;}
    string name {get; set;}
    //and other many variables
}

In another class I already have an instance of Foo with all variables setup.

What I want to do is attach the existing instance of Foo to a GameObject, instead to attach it and then setup all the variables.

Something like that, it is just an example, of course it give errors:

GameObject go;      //Existing GameObject
Foo foo;            //Existing instance of Foo with variables setup.

go.AddComponent(foo);

Instead of doing:

GameObject go;      //Existing GameObject
Foo foo;            //Existing instance of Foo with variables setup.

go.AddComponent("Foo");

Foo myComponent = go.GetComponent<Foo>();
myComponent.id = foo.id;
myComponent.name = foo.name;
//and so on

Is there a way to do that?


texts:
I have a canvas.  It has an empty game object as a child.  That object has a RectTransform component.  The RectTransform pivot value is set to 0.4, 0.5 (x, y).
In some code I wanted to update the pivot value using the following:

Debug.Log(((RectTransform)transform).pivot);  // logs: (0.4, 0.5)
((RectTransform)transform).pivot.Set(0.3f, 0.8f);
Debug.Log(((RectTransform)transform).pivot);  // logs: (0.4, 0.5)

I don't know why the set command is not working.  The tooltip for Set is: "Set x and y components of an existing Vector2"


texts: How can I import animated 2D content from Animate CC into Unity?

texts:
I'm a programmer making his efforts to get a bit into art. I have basic drawing and animation knowledge that I think is enough to have some simple games rolling.

I have used several programs to create content for unity like aseprite (pixel art), photoshop, spine, etc... but these last days I discovered Animate CC (aka old Flash) and it seems to be a really nice tool. The ability to animate + create vector graphics in the same program really attracts me.

When I create an animated asset in Animate CC, how can I import it into Unity? I imagine I won't be able to import the svg animation but I think it should be somehow possible to build a sprite sheet from it and import it into unity.

Could anyone suggest a comfortable workflow to do this?


texts: legal disclaimers and lisence type for a free multiplayer browser game

texts:
I have created a multiplayer browser game. The game is completely free (donations are welcome) but I would like:

(a) to protect my concept in some way.
(b) to provide legal notes that the user should accept before registering.

In some games (i.e. Travian) there are legal notes such as Terms and Conditions, Privacy Policy. Should I include things like these? Where can I get/create such legal texts? I can barely afford hosting, not to mention a lawyer to write all those things for me.

What should I do?

Chris


texts:
I have a collision method where the parameters for the method are the rectangle of the player and a list with the rectangles of the tiles.

I work with booleans like bLeft, bRight,... and this creates a problem if my player collides with two tiles at the same time, then one tile may say True while the other says false.

This is my collision method (NOTE: Very buggy and incomplete collision detection, this is because the reason above)

public override void Collision(Rectangle collisionRect, List<Rectangle> tileCollision)
{

    foreach (Rectangle rect in tileCollision)
    {
        if (collisionRect.Intersects(rect))
        {

            rect2 = Rectangle.Intersect(rect, collisionRect);

            collision = true;
            stopping = true;
            walking = false;

            if (collisionRect.X < rect.X && !(collisionRect.Y <= rect.Y - 50))
            {
                bLeft = true;
            }

            if (collisionRect.X > rect.X && !(collisionRect.Y <= rect.Y - 50))
            {
                bRight = true;
            }

            if (collisionRect.Y <= rect.Y - 50)
            {
                bUp = true;
            }

            if (collisionRect.Y >= rect.Y + rect.Height)
            {
                bDown = true;
            }

            if (bLeft && !bRight && !bUp && !bDown)
            {
                fallingTest = false;
                stopping = true;

                if (left)
                {
                    stopping = false;
                    fallingTest = false;
                }
            }

            if (bRight && !bLeft && !bUp && !bDown)
            {
                fallingTest = false;
                stopping = true;

                if (right)
                {
                    stopping = false;
                    fallingTest = false;
                }
            }

            if (bUp)
            {
                ground = true;
                fallingTest = true;
                stopping = false;

                if (moving)
                {
                    walking = true;
                }

                if (bLeft && bUp)
                {
                    stopping = true;

                    if (left)
                    {
                        stopping = false;
                    }
                }

                if (bRight)
                {
                    stopping = true;

                    if (right)
                    {
                        stopping = false;
                    }
                }
            }

            if (bDown && !bRight && !bLeft && !bUp)
            {
                stopping = true;
                fallingTest = false;

                if (moving)
                {
                    walking = true;
                }
            }
        }

        if (!(tileCollision.Any(c => collisionRect.Intersects(c))))
        {
            collision = false;
            fallingTest = false;
            stopping = false;

            ground = false;

            if (moving)
            {
                walking = true;
            }
        }
    }
}

So I basically need a line of code that counts the colliderboxes that the player collides with at the moment of collision. I tried doing this by adding 1 to the variable collisionBoxes but this results in doing +1 each frame (because this collision method is called in  Update)

I also use rect2 for visual overlapping of the player collision box and the tile collision box, but when the player touches more than one tile, then the rect2 only shows on one tile. This is because I use the foreach but I tried using a list to store the overlapping rectangles in but it didn't work.

One more question, should I use all these booleans? Because I don't know how to handle them if more than one block touches the player (all the tiles are checking for the booleans, resulting in bugs).


texts: Why do GPUs have limited amount of allocations?

texts:
I've been learning Vulkan lately and I read that you can allocate VRAM memory only set amount of times and it doesn't matter if it's 2gb or 2kb, why is it?

I'm specifically referring to VkPhysicalDeviceLimits structure which has a field maxMemoryAllocationCount.


texts:
I have a texture that is 1024x900. Should I resize it in Photoshop to be 1024x1024 or leave it as it is?

What about a texture sized 1000x900?


texts: How to choose and scale heuristics for A-star on a graph?

texts:
I am trying to find the best and scale my cost function for my algorithm. I am following amit blog which explain that (http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html#manhattan-distance).

I have a humanoid character first blue circle is the start configuration with the left foot (red). Then I expand a set a possible right footsteps (blue) and again with the left foot (red) until the center of the character reach the goal.

my heuristic look like : f = g + h;
with g = g + oneStepCost (distance between 2 footsteps) + TerrainCost (0 free, Infinity if obstacles); // Cost to go
h = distance between the middle of the character and the goal;

What do you think about this basic heuristics ?
I feel using the Euclidian distance is the best suited for my configuration but Manhattan distance seems a lot faster.

On amit blog, he says that it is good to have a cost function = 1 for the minimum distance traveled but I don't really understand how to do that because my cost function is in meters.

Then, i might have lot of paths which are almost the same length. So, I have to break ties. So, if I use this formula : h *= (1.0 + p)
with p <(minimum cost of taking one step)/(expected maximum path length)
.
For my case, minimum cost of taking one step = 0.10 m and maximum path length = (0.25 meter * 12 steps). Does it seems correct to you ?
Any others tips in order to improve heuristics and not spending time for the path with almost the same length ?


texts:
I'm looking for a way to render every non-transparent pixel in a sprite solid white (to 'flash' the sprite white when the player takes damage etc). This is on Windows Phone 7.

I was using a very simple custom shader to do this under XNA 3.1, but WP7 doesn't support these and finding an alternative's proving difficult.

I'd appreciate any help or suggestions. I'd rather not have to manually create a solid white copy of every sprite in my game though.


texts:
When we import a D3D12 memory object into cuda we do something like this:

cudaExternalMemoryHandleDesc cuExtmemHandleDesc{};
cuExtmemHandleDesc.type = cudaExternalMemoryHandleTypeD3D12Resource; //here
//...
CheckCudaErrors(cudaImportExternalMemory(&m_externalMemory, &cuExtmemHandleDesc));

What is the difference between cudaExternalMemoryHandleTypeD3D12Resource and cudaExternalMemoryHandleTypeD3D12Heap? When should I use one or the other when importing memory object?


texts: How to wrap a components position using angles (i.e horizontal compass)

texts:
I'm trying to make a horizontal compass.  The compass is made up of UI components: panel (with mask), with a child UI Image (the compass image).

Here is the compass from Fallout:

As you turn around, so does the compass.  I want to move the child based on the rotation of the player.  I want to move the child by using transform.position so that any child components will also move (i.e way points).

I found some code on the Unity forum.  I got it to kinda work, however when it wraps around, it doesn't wrap to the correct position.  See GIF.  When I approach the South rotation, it wraps but not to the correct position.  The compass image and code can be found here.

I've made sure that the image is native size, and also tried various values in the "numberOfPixelsNorthToNorth" property.

using UnityEngine;
using UnityEngine.UI;

using System.Collections;

public class CompassHandler : MonoBehaviour {
    public float numberOfPixelsNorthToNorth;
    public GameObject target;
    Vector3 startPosition;
    float rationAngleToPixel;

    void Start(){
        startPosition = transform.position;
        rationAngleToPixel = numberOfPixelsNorthToNorth / 360f;
    }

    void Update (){
        Vector3 perp = Vector3.Cross(Vector3.forward, target.transform.forward);
        float dir = Vector3.Dot(perp, Vector3.up);
        transform.position = startPosition + (new Vector3(Vector3.Angle(target.transform.forward, Vector3.forward) * Mathf.Sign(dir) * rationAngleToPixel, 0, 0));
    }
}

I don't really understand how the code works in the Update method, as my Math knowledge is pretty poor.  I looked up the methods used, but still was clueless.  So I can't work out how to solve it.

I would like to understand what is going on in the Update, but if that is too much, can anyone help fix the issue that is seen in the GIF?

Edit:  Here is a GIF using the accepted solution.


texts:
The shell of a grenadelauncher is very small (10cm) and the speed is very fast (80m/s). Collision detection using colliders is impossible.

To get the collision point of a rocket launcher I send a Ray out from the rocket with a length of say 5 metres. If the Ray detects an object it will wait for 5/SpeedOfRocket seconds and then detonate. A rocket travels in a straight line, therefore no problem:

Grenades however travel in an Arch. They are not selfpropelled, they slow down due to air resistance and they are pulled down by gravity. If I fire a grenade up into the air and use a Ray to detect the collision, it will simply fall through the floor, or another object. The grenade doesn't rotate towards the direction of travel.

Using a second and third Ray to detect collisions behind and below the grenade catch all collisions successfully. However you will not be able to shoot a grenade closely above a hill or through a narrow window without it triggering a collision if within range of the Ray.

For now I have "solved" the problem by using the grenade just like a rocket. I simulate gravity by simply rotating the grenade as it moves. One ray to catch collision is enough because the Grenade will always face the direction of travel.

It works fine if you use the Grenade Launcher "normally". Until you shoot it like a mortar launcher: straight up in the air. I find it mathematically impossible to simulate the trajectory as such. There are too many variables involved and it would be a ridiculous attempt at solving a (what seems to be) a trivial initial problem.

I need to get the grenade to face the direction of travel like this:


texts: Animation works well on preview but not when hitting play

texts:
I'm using a simple animation where I want to move an sprite just a little bit bellow its current position, and this works well on preview mode in the Animation tab.
But as soon as I hit play, the value I'm trying to animate is not the same as the one in the keyframe, the value is lesser than the one I setted. I don't know what I'm doing wrong... I'll append a clip showing this problem.
I already tried turning on and off Apply Root Motion and some alike questions, but none of the solution worked for me so far...


texts: Why aren't my Unity rotations working properly?

texts:
I'm experiencing a rather annoying bug and I was hoping someone could offer some help because this just isn't making sense to me. I have a Ballistic script that tells the bullet to move in its local forward direction, which should be whichever way the gun is pointing. I have a PlayerAttack script that calls for a bullet to spawn with OnShootEnter(). It sets the bullets position to that of a bulletSpawn transform, which is a child of the gun.

OnShootEnter() is being properly called and bulletSpawn is properly assigned; and yet, when the bullet spawns, its facing Vector3.forward, instead of it facing bulletSpawn.forward. These are the only two scripts affecting the bullets spawn, rotation, and direction. Everything looks in order to me; what am I missing?

public class PlayerAttack : MonoBehaviour
{
    public GameObject bulletPrefab;

    public Transform gun;
    public Transform bulletSpawn;
    public float damage;

    void OnShootEnter()
    {
        GameObject bullet
            = Instantiate(bulletPrefab, bulletSpawn.position, bulletSpawn.rotation);
     }
}

public class Ballistic : MonoBehaviour
{
    public GameObject model;
    public float range;
    public float accuracy;
    public float speed;

    Vector3 dir = Vector3.zero;

    void Start ()
    {
        model.transform.SetParent (this.transform);
        dir = transform.forward;
    }

    void Update ()
    {
        transform.GetComponent<Rigidbody> ().velocity = dir.normalized * speed;
        range -= Time.deltaTime;

        if (range <= 0)
            Destroy (this.gameObject);
    }
}


texts: Finding all possible paths from one hexagon to another

texts:
I got a hexagonal grid (cube coords)

In hex (0,0,0) there is a soldier and in another (distance == 4 hexes) a target:

i need to find all possible pathes from soldier hex to a target :
1)Length of path should be no more then 6 hexes
2)Not including those which returning to already visited tiles
3)Including those that are longer than the shortest possible path .
Though i need to solve it on javascript, but even pseudocode or just some thougths would be helpful
Thank you !


texts: Is it reasonable to generate mipmaps on the color attachment of my framebuffer in realtime?

texts:
I'm looking into hdr tonemapping and so far all the equations I've found result in really, dulled results.

One i haven't tried uses an average luminance of the image. The pdf I've been reading suggests to generate mipmaps on my texture to get down to a single pixel that will then have average luminance.

However, in my tests this performs very slowly. I.e. I can't use it for realtime graphics.

Am I likely doing something wrong, or should I expect to be able to generate mipmaps for a framebuffer in realtime (I obviously need to generate them each frame).

If I shouldn't expect to be able to: Is there another method to glimpse average luminance of the image on screen?


texts:
im trying to make a circle button with tap event i used hitArea property from sprite class and using pixi Circle class i did that

this.sprite = game.add.sprite(50,50,"cursors");

        this.sprite.anchor.set(0.5,0.5);

        this.sprite.hitArea = new PIXI.Circle(50,50,84);

        this.sprite.inputEnabled = true;

        this.sprite.events.onInputDown.add(function(){

            console.log("clicked");
        });

    };

it is not working at all
so i tried removing  this.sprite.anchor.set(0.5,0.5);

input is work fine when there is no hit Area so what should i do

note :
phaser version is 2.2.2


texts: How to programatically retarget animations from one skeleton to another?

texts:
I'm trying to write code to transfer animations that were designed for one skeleton to look correct on another skeleton. The source animations consist only of rotations except for translations on the root (they're the mocap animations from the CMU motion capture database). Many 3D applications (eg Maya) have this facility built-in, but I'm trying to write a (very simple) version of it for my game.

I've done some work on bone mapping, and because the skeletons are hierarchically similar (bipeds), I can do 1:1 bone mapping for everything but the spine (can work on that later). The problem, however, is that the base skeleton/bind poses are different, and the bones are different scales (shorter/longer), so if I just copy the rotation straight over it looks very strange.

I've attempted a number of things similar to lorancou's solution below to no avail (ie multiplying each frame in the animation by a bone-specific multiplier). If anyone has any resources on stuff like this (papers, source code, etc), that would be really helpful.


texts: How do I calculate the total XP to reach a particular level, when each level takes 10% more?

texts:
How do I calculate the amount of XP for a level where the first level is 110, and each level after is 10% more than the last. Preferably to do without a loop because the levels will have to be infinite and will need to be quickly calculated.

in js using a loop:

var xptest=110;
var lastLevel = 110;
for (var level = 2; xptest <= Number.MAX_SAFE_INTEGER || level < 100; level++) {

    lastLevel*=1.1;
    lastLevel = Math.round(lastLevel *1.1)
    xptest+= lastLevel;

    console.log('LEVEL',level,'('+lastLevel+' / '+xptest+')');
}


texts:
OK, my multi-touch system was somewhat convoluted, but was working perfectly OK until I tried to run my game on my Nexus 10 which is running Jellybean.

Crashing all over the place!  So I removed my whole multi-touch routine and am trying to start from scratch and to simplify it.

Basically, I have 3 buttons, left, right and jump.  Left is left of screen, right is right of screen and jump is in the middle.

What I need is when the player presses left and that button held down and then they press right, for the latter touch to override, so the right touch registers and the character moves from left to right.  If he then releases one of the buttons the character moves in the direction of the button which remains pressed.  Again, same with jump.

I can get my character moving left and right with single-touch but all day I've been trying to understand multi-touch and just can't get it.

I don't understand the whole pointer ID's and pointer Indexes and would be really grateful if someone could just explain and give an example of some code which would accomplish what I require.  Just 2 buttons would do and I could go from there.

Many thanks!

edit

Here is some really basic code and the results I get from it:

public boolean onTouchEvent(MotionEvent event) {

int action = event.getAction() & MotionEvent.ACTION_MASK;
int pointerIndex = (event.getAction() & MotionEvent.ACTION_POINTER_ID_MASK) >> MotionEvent.ACTION_POINTER_ID_SHIFT;
int pointerId = event.getPointerId(pointerIndex);

        Log.v("multitouch","pointer ID "+pointerId);
            Log.v("multitouch","pointer Index "+pointerIndex);

    return true;

}

when I press the first finger down, ID and Index are both 0
when I press the second finger down, ID and Index are both 0
if second finger is released and the first one remains, the ID and Index are both 0
However, if the first finger is release and the second one remains then the Index is 0 but the ID is 1

I don't understand how this works and how I can use it to determine which fingers are on the screen at which time and would really be grateful if someone could throw some light on it for me - thanks!!


texts: Keeping user's attention with tycoon style games

texts:
I'm developing a tycoon game, and with most games in the "genre", some in game things just take time. Making money, waiting for things to happen, etc. For mobile gaming (ios, android), how do I keep this entertaining. Without talking specifically about my game, there are day cycles / things that happen at certain points (can I be more general?...)

There's different possibilites, and some I've seen have either a fast-forward button or something in order to not make it boring. (I'm talking about a tycoon game with a little bit of stuff to do; you can't constantly be busy like sim city or something). Do I just have notifications generated at certain times to tell the user a "day is over" or a "power up is attained"? Or would that get too annoying?

I'm open to any ideas on how to keep users interested, but it's really not a game that you can constantly play for hours. Not enough stuff to do, doesn't require that much micro-management.


texts: How do I make wasd controls for a top down game in unreal engine 4.13.1

texts: I've been trying to make controls for a top down game in unreal engine 4 but I can't figure out how to make it and all the tutorials I've been seeing are outdated.


texts: Triggers are not detecting colliders from other game objects in Unity version 5.2.2f1?

texts:
I was working on a basic slots game, and I came across a hiccup with the 2D Physics engine. Currently I'm letting the reels spin for three seconds. Once it has finished spinning, it will go to the reel stop that the RGN picked out. Also, when it has reached the end of the reel I had it so that reel would "wrap around" to the firs reel stop continuing displaying the stops as it before.

I'm using a edge collider as a trigger on each reel (I'll call it a symbol trigger for short). The symbol trigger is a child of the reel but the actual symbols (which are game objects in screen space) are procedural generated and attached to the actual reel. All the symbols have a rigidbody2D and are kinematic. For some reason the triggers do no respond with on enter, on stay, or on exit, and that is with putting debug logs.

Now I have taken the reels and triggers to and out of world space and screen space, switched from rigidbody2D to 3D along with, messed with the sleep options, and switched it from discreet to continuous and still have get no response from the collider. If anyone knows why this is happening, your insight would be highly  appreciated!

Thanks for reading about my issue and have a good day.


texts: Change AI steering behavior's direction to 8 directions

texts:
I am making a 2d soccer game, all players move in 8 directions, so I need to convert AI steering behavior(like arrive and pursuit) into 8 directions.
Here are three example situations:

Player(now is at point A) set target To point B, we could not directly move in direction(B - A), player need to first move to point C in horizontal or vertical, then move in 45 degree to reach target point.
 Consider in my game there is no steering behavior accumulation, which means, at any time , only have one function to affect player movement(arrive or pursuit), so I first make convert code in arrive function, because pursuit actually call arrive either.
Here is pseudo-code:

void RSAIController::Init()
{
   ...
    m_vDirectionArray[0] = CCPoint(1.f, 0.f);
    m_vDirectionArray[1] = CCPoint(0.7071f, 0.7071f);
    m_vDirectionArray[2] = CCPoint(0.f, 1.f);
    m_vDirectionArray[3] = CCPoint(-0.7071f, 0.7071f);
    m_vDirectionArray[4] = CCPoint(-1.f, 0.f);
    m_vDirectionArray[5] = CCPoint(-0.7071f, -0.7071f);
    m_vDirectionArray[6] = CCPoint(0.f, -1.f);
    m_vDirectionArray[7] = CCPoint(0.7071f, -0.7071f);
}
//called in arrive method, then use m_vMoveDirection as speed direction
void RSAIController::ConvertTo8Directional()
{
    int idx = -1;
    float maxValue = -MaxFloat;
    CCPoint direction = m_vTarget - m_pPlayer->Pos();
    //do this because in cocos2d normalize zero vector will return (1, 0)
    //which is not the expected result,so I avoid it manually
    if(!VIsZero(direction))
        direction = direction.normalize();

    for(int i = 0; i < 8; ++i)
    {
        float dotValue = m_vDirectionArray[i].dot(direction);
        if(dotValue > maxValue)
        {
            maxValue = dotValue;
            idx = i;
        }
    }
    m_vMoveDirection = m_vDirectionArray[idx];
}

Then I am thinking 8-directional AI movement is pretty common in old nes game, like "Nintendo World Cup". Does anyone used to meet this problem or have any articles related to this?

UPDATE: I have update the code in @Json advice, but still got the errors I met before.
1.Actually player will change direction in 22.5 degree not 45 degree. I need player move on the diagonals when the degree is just reach 45.
2.When player move on the diagonals, the player will keep shaking. For example, in situation 1, when player start to move from C to B in first frame, player decide to move in perfect 45 degree, but player can not reach precise point C because "distance from A to C" has small error to "player speed(constant) * move time from A to C" , this will cause next frame player probably run in horizontal direction, again and again..
  Do I need to check when the last frame that arrive at C, then just make player at the precise point C manually to avoid this error, or there has any other trick to fix this?