texts: Continuous Physics Engine's Collision Detection Techniques

texts:
I'm working on a purely continuous physics engine, and I need to choose algorithms for broad and narrow phase collision detection. "Purely continuous" means I never do intersection tests, but instead want to find ways to catch every collision before it happens, and put each into "planned collisions" stack that is ordered by TOI.

Broad Phase
The only continuous broad-phase method I can think of is encasing each body in a circle and testing if each circle will ever overlap another. This seems horribly inefficient however, and lacks any culling.

I have no idea what continuous analogs might exist for today's discrete collision culling methods such as quad-trees either. How might I go about preventing inappropriate and pointless broad test's such as a discrete engine does? I also would like to be able to see collisions more than 1 frame ahead to.

Narrow Phase
I've managed to adapt the narrow SAT to a continuous check rather than discrete, but I'm sure there's other better algorithms out there in papers or sites you guys might have come across.
What various fast or accurate algorithm's do you suggest I use and what are the advantages / disatvantages of each?

Final Note:
I say techniques and not algorithms because I have not yet decided on how I will store different polygons which might be concave, convex, round, or even have holes. I plan to make a decision on this based on what the algorithm requires (for instance if I choose an algorithm that breaks down a polygon into triangles or convex shapes I will simply store the polygon data in this form).


texts:
In my (Google Cardboard) Android app I would like to make my camera move on Touch. That movement state should be controlled via a "switch", so when I touch the screen the camera starts to move and when I tap again it stops. To achieve that I appended this script to the camera:

using UnityEngine;
using System.Collections;

public class TapControl : MonoBehaviour {

public float speed;
public int state = 0;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    if (Input.GetTouch(0).phase == TouchPhase.Began)
    {
        state += 1;
    }
    if (state % 2 == 0)
    {
        transform.Translate(Vector3.forward * speed * Time.deltaTime);
        }
    }
}

The state-integer increases every touch. But nonethless, the camera's behavior can be described as a "hold-touch to move" when the state-variable is even.

So, to make it short: Can anyone detect any programming mistakes i made that could cause this strange behavior?


texts: Unity Rendering Pass Before Refraction not showing

texts:
In the documentation it states:

Before Refraction: Draws the GameObject before the refraction pass. This means that HDRP includes this Material when it processes refraction. To expose this option, select Transparent from the Surface Type drop-down.

I have selected the Transparent option for surface type but the Before refraction rendering pass is not in the drop down list for rendering pass. How can I get it to be there? Are there some other option that might be disabling it?


texts: Looking for a complete information game slightly more complex than Tic-tac-toe

texts:
I am testing various rating systems (Elo rating and some alternatives). I need a"world" with computer players participating in championships. Computer players are characterized by two parameters:
(1.1) Depth of search (probability to search yet another ply deeper)
(1.2) Probability to remember the outcome in their previous games. (Relatively high)
(1.3) Probability to learn from "published games". (Relatively low)

I tried tic-tac-toe, but there are two problems:
(2.1) Players learn too fast. (Decreasing learning rate turns it in a toss-a-coin)
(2.2) Ply count is granular. The difference between "can/cannot see a fork" or "can/cannot see opponent's fork/one move win is huge.

A battleship game doesn't have complete information. A game like chess or five in a raw would require prohibitively large amount of memory to remember all possible combinations.


texts: Make a trigger work for only a certain type of object

texts:
Is there a way you can make a trigger only exist to a certain type of objects while excluding other ones. I don't think the code will help but I just put anyway.

public class Girl : MonoBehaviour {

    public Attacker attacker;
    public Animator anim;
    public float girlHealth;
    public GameObject obj;

    // Use this for initialization
    void Start()
    {
        attacker = GetComponent<Attacker>();
        anim = GetComponent<Animator>();

    }

    // Update is called once per frame
    void Update () {
        if (!obj)
        {
            anim.SetBool("isattacking", false);
        }
    }
   void OnTriggerEnter2D(Collider2D collision)
    {
        obj = collision.gameObject;

        if (obj.tag == "Axe") {
            anim.SetBool("isattacking", false);
            anim.SetTrigger("ifAx");
        }

        if (obj.tag == "Stone") {
            anim.SetBool("isattacking", true);
        }
        if (obj.tag == "ActiveDefender")
        {
            anim.SetBool("isattacking", true);
        }

    }

}

I figured out a way to do it

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Attacker))]
public class Girl : MonoBehaviour {

    public Attacker attacker;
    public Animator anim;
    public float girlHealth;
    public GameObject obj;
    // Use this for initialization
    void Start()
    {
        attacker = GetComponent<Attacker>();
        anim = GetComponent<Animator>();

    }

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

        if (!obj)
        {
            anim.SetBool("isattacking", false);
        }

    }
   void OnTriggerEnter2D(Collider2D collision)
    {

       if(collision.gameObject.tag == "Stone")
        {
            obj = collision.gameObject;
        }
       else if (collision.gameObject.tag == "ActiveDefender")
        {
            obj = collision.gameObject;
        }

         if (obj.tag == "Stone") {
            anim.SetBool("isattacking", true);
        }
         else if (obj.tag == "ActiveDefender")
        {
            anim.SetBool("isattacking", true);
        }
        Debug.Log(collision.gameObject);

    }
    void OnTriggerExit2D(Collider2D collision)
    {

    }

}


texts: How to make sure that the set of randomly spawning obstacles is passable?

texts:
Prompt

Suppose we have a little mini-game where you have to avoid incoming obstacles by moving the blob up and down at a constant speed. The blob's x coordinate is fixed and the obstacles will spawn from the right edge of the screen.

The obstacles may vary in size, speed, starting height, spawn interval, angle, etc. (they can overlap). But let us work with just varying height and speed for now. My question is:
If I were to generate the next obstacle with randomised starting height and speed, how can I make sure that the player can still avoid everything?

Example

In the image above, suppose the blob's speed is enough to move him up towards the gap near the top before the obstacles reach his x coordinate, but he's not fast enough to reach the bottom gap in time. So given the current set of obstacles, the blob should move himself towards that gap (possibly with a bit of leeway before the obstacles will actually reach him).

Now consider the next obstacle spawning at the same height as the gap.
This is fine since the blob can still move up or down immediately after getting through the first set of obstacles. But suppose we are unlucky and the random difficulty setting makes it so that the new obstacle is twice as fast and will reach the blob's x coordinate at the same time as the first set of obstacles. Then the whole set of obstacles is regarded as impassable with respect to the blob's current position.
In particular, how can we determine that the first case is OK while the second is not?

Attempt

Intuitively, I am imagining a "live zone" that updates itself as the obstacles move. The live zone defines a (set of) range along the blob's vertical axis in which he can be in at any given point in time in order to make sure that he can avoid the obstacles. By definition, blob must always remain within the zone, otherwise, we will hit an obstacle no matter what. In a sense, the live zone "zooms in" on spaces without an obstacle.

In the above example, we have 2 zones near the top and bottom gaps.

The zone narrows as the obstacles approach the blob. The narrowing rate depends the relevant obstacles' speeds.
The fact that blob cannot reach the bottom gap in time can be demonstrated with him having to leave the zone he's in.

Let's call part of the live zone that blob is in an "active zone". The goal is then to make sure that the active zone is always non-empty and that it is always possible for blob to stay within that zone. If a new obstacle removes the active zone, we can stop it and let it pick a different settings for the new obstacle. But how would I go about implementing this or is this approach feasible in the first place?

Some parametrisation of the obstacle's position based on time or their x coordinate?
If we squash the x axis into just a line corresponding to blob's x coordinate, then the live zone is just the complement of the union of all the obstacles.
What if there really is no next valid obstacle? No, this cannot be the case since we can just repeat the last spawned obstacle, provided we started with a non-empty active zone.


texts: How does zooming in affect collision detection?

texts:
So I'm pretty new to DirectX, currently going through some tutorials to get an understanding of it. Now that I'm getting a small grasp onf graphics programming, I'm wondering how simple AABB bounding box collision would work, if the Z factor on quads was being changed for a zoom effect.

Say I have 2 quads set up, a texture applied to both, a bounding box around each and their positions set overlapping each other. I have an orthographic camera set up. Will zooming in scale the textures and quads so the boxes around them are no longer representative of them?


texts:
I am trying to make an 3d  game in Marmalade. I am completely new to Marmalade.

How to add 3d physics, gravity, dynamic object, sensors, colliders in Marmalade.

I was going through the API and did not find anything. Can you guys let me know how to accomplish these things


texts: Unity: set y rotation messed up the object

texts:
I created 3 boxes, then align the three to form some sort of a gate,
I set the parent to an empty object so that I can easily move it. And I add box collider inside the gate.

When I try to rotate it on Y axis, the boxes deforms

I just want to rotate the Y, not deformed it. Here are the object

Is this related to the transformation I created before?
Something that requires to apply the transformation first? like in blender3d?


texts: Remove background from sprite sheet after splitting

texts:
I am using libgdx to implement a Parallax background. Now I need to show some animated object over the background. I downloaded a sprite sheet(with images of objects on white background), and split it using TextureRegion.split() method. But when I draw the objects to screen, white background is shown along with the object as in this image:

I tried using batch.enableBlending() but it didn't work. Is there any way to resolve this issue? Or should I code only using individual sprites with transparent background? Here is a brief code snippet :

public class Animator extends Actor{
        int FRAME_COLS = 3, FRAME_ROWS = 3;

        Animation<TextureRegion> eagleAnimation;
        Texture eagleSheet;
        float stateTime;

        Animator(Texture sheet) {
            eagleSheet = sheet;
            TextureRegion[][] tmp = TextureRegion.split(eagleSheet, eagleSheet.getWidth()/FRAME_COLS,
                    eagleSheet.getHeight()/FRAME_ROWS);
            TextureRegion[] eagleFrames = new TextureRegion[FRAME_COLS*FRAME_ROWS];

            int index = 0;
            for(int i = 0; i < FRAME_ROWS; i++) {
                for(int j = 0; j < FRAME_COLS; j++) {
                    eagleFrames[index++] = tmp[i][j];
                }
            }

            eagleAnimation = new Animation<TextureRegion>(0.09f, eagleFrames);
            stateTime = 0f;
        }

        @Override
        public void draw(Batch batch, float parentAlpha) {
            stateTime += Gdx.graphics.getDeltaTime();

            TextureRegion currentFrame = eagleAnimation.getKeyFrame(stateTime, true);
            batch.enableBlending(); // doesn't work
            batch.draw(currentFrame, 250, 250, 264, 264);

        }

    }

This is where I call above class from :

    public class GameScreen implements Screen {

        MyGdxGame game;

        Texture eagleSheet;
        OrthographicCamera camera;
        Array<Texture> layers;
        Stage stage;

        public GameScreen(MyGdxGame game) {
            this.game = game;
            stage = new Stage(new ScreenViewport());
            camera = (OrthographicCamera) stage.getViewport().getCamera();

            layers = new Array<Texture>();

            for(int i = 1 ; i <= 6; i++) {
                layers.add(new Texture(Gdx.files.internal("parallax/img" + i + ".png")));
            }
            ParallaxBackground parallaxBackground = new ParallaxBackground(layers);
            parallaxBackground.setSpeed(1);
            parallaxBackground.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
            stage.addActor(parallaxBackground);

            eagleSheet = new Texture(Gdx.files.internal("eagle.png"));
            Animator animator = new Animator(eagleSheet);
            animator.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
            stage.addActor(animator);

        }

        @Override
        public void render (float delta) {
            Gdx.gl.glClearColor(1, 0, 0, 1);
            Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

            stage.act();
            stage.draw();

        }

        @Override
        public void dispose () {
            stage.dispose();
        }

        @Override
        public void show() {}

        @Override
        public void hide(){}

        @Override
        public void resume(){}

        @Override
        public void resize(int x, int y){}

        @Override
        public void pause(){}

    }


texts: How to abstract mouse movement event streams for networked multiplayer?

texts:
I'm building a mouse driven 3rd person shooter with client-server network architecture.

My input system is event based. Keyboard input is captured by keys.S.onUp() keys.S.onDown() events. When these events are triggered I immediately pass them across the network to be replicated on the server and other clients.

Mouse input is captured by a mouse.onmove() event that receives data from screen coordinates x,y. This method is fired constantly as the mouse is moved producing a flood of data. This may be premature optimization, but I feel like its a bad idea to immediately pass this flood over the network.

I currently have an abstraction that wraps the mouse.onmove() event and creates essentially a mouse.moveStart() and mouse.moveStop(). This significantly reduces the flood of mouse input to send on the network.

Unfortunately, this abstraction produces a less responsive feel on the local client experience. I am setting a lookVelocity. When mouse.moveStart() is triggered the camera position and player rotation is updated per-frame by the lookVelocity value. This produces a stiff fixed rate movement. If you rapidly move the mouse the camera movement is not reflected.

Additionally, this is an isomorphic/universal code base. Meaning I am using the same code between client and server. Ideally, I would like to reuse the same mouse event abstraction between both client and server.


texts: How would I implement render scaling in a DX11 game?

texts: I would like to implement render scaling that could render a scene at a certain % of the window resolution. How would I do this? I've tried resizing a number of things, then resizing them up or down to match the window size but I've never gotten it to work.


texts: Why am I seeing elapsed game time differ from total game time in XNA?

texts:
I was trying three different ways of using ElapsedGameTime and TotalGameTime, because I want an exact match, so everything is updated/drawn accordingly.

As I was experimenting, I learned that the very first update, ElapsedGameTime and TotalGameTime are both 0.

Second update, ElapsedGameTime is 0.0166667, which is correct (60 updates per second). But TotalGameTime is 0, I don't understand why.

So, if I start to add from the third update (time += gameTime.ElapsedTime), ElapsedGameTime is equal to TotalGameTime, otherwise there will be always a 0.0166667 difference.

Can someone explain that to me?

UPDATED: code

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

using System.Diagnostics;

namespace TestTime
{
    class TimeTest2
    {
        TimeSpan totalTimeElapsed;
        TimeSpan frequency = TimeSpan.FromSeconds(5.5f);

        int times = 0;
        int timesCheckpoint = 1;

        public void load()
        {

        }

        public void initialize()
        {
            totalTimeElapsed = TimeSpan.Zero;
        }

        public void update(GameTime gameTime)
        {
            times++;
            String debug = "";
            TimeSpan zero = TimeSpan.Zero;

            if( times > 2 )
            {
                totalTimeElapsed += gameTime.ElapsedGameTime;
            }

            if( totalTimeElapsed != gameTime.TotalGameTime )
            {
                debug += " Diff time:"+times+" ["+totalTimeElapsed.ToString() + " != " + gameTime.TotalGameTime.ToString() + "]";
            }

            TimeSpan checkpoint = TimeSpan.FromSeconds(5.5f*timesCheckpoint);
            if( gameTime.TotalGameTime >= checkpoint )
            {
                debug += "5.5f MARK ";
                timesCheckpoint++;
            }

            if( !debug.Equals("") )
            {
                addDebug(debug + "  -" + gameTime.TotalGameTime.ToString());
                addDebug("");
            }
        }

        public void draw()
        {

        }

        public void addDebug(string str)
        {
            Debug.WriteLine(str);
        }
    }
}


texts: How should I cycle my game to be more scalable?

texts:
I'm trying to improve my game emulator so it can handle more users. I currently have one separate thread and execute all processing there.

The cycles processes players and rooms, rooms are individual maps that users can belong to, with other users where they can walk, talk and interact with each other

Currently my game server starts having issues where there are more than 2,000 users online, or when a single room has more than 60 users inside it.

Here is the main game cycle

private Task _gameCycle;
private int _cycleSleepTime = 25;

public Game()
{
    _cycleActive = true;

    _gameCycle = new Task(GameCycle);
    _gameCycle.Start();
}

private void GameCycle()
{
    while (_cycleActive)
    {
        Root.GetGame().GetRoomManager().OnCycle();
        Root.GetGame().GetPlayerManager().OnCycle();

        Thread.Sleep(_cycleSleepTime);
    }
}

RoomManager's OnCycle:

var sinceLastTime = DateTime.Now - _cycleLastExecution;

if (sinceLastTime.TotalMilliseconds >= 500)
{
    _cycleLastExecution = DateTime.Now;

    foreach (var room in _rooms.Values.ToList())
    {
        if (room.isCrashed)
        {
            continue;
        }

        if (room.ProcessTask == null || room.ProcessTask.IsCompleted)
        {
            room.ProcessTask = new Task(room.ProcessRoom);
            room.ProcessTask.Start();
            room.IsLagging = 0;
        }
        else
        {
            room.IsLagging++;

            if (room.IsLagging >= 30)
            {
                room.isCrashed = true;
                UnloadRoom(room.Id);
            }
        }
    }
}

PlayerManager's OnCycle:

if (_clientPingStopwatch.ElapsedMilliseconds >= 30000)
{
    _clientPingStopwatch.Restart();

    var toPing = new List<IGameClient>();

    foreach (var client in _clients.Values.ToList())
    {
        if (client.GetConnection().PingCount < 6)
        {
            client.GetConnection().PingCount++;

            toPing.Add(client);
        }
        else
        {
            lock (_timedOutConnections.SyncRoot)
            {
                _timedOutConnections.Enqueue(client);
            }
        }
    }

    var start = DateTime.Now;

    foreach (var client in toPing.ToList())
    {
        try
        {
            client.SendPacket(new PongComposer());
        }
        catch
        {
            lock (_timedOutConnections.SyncRoot)
            {
                _timedOutConnections.Enqueue(client);
            }
        }
    }
}

if (_timedOutConnections.Count < 1)
{
    return;
}

lock (_timedOutConnections.SyncRoot)
{
    while (_timedOutConnections.Count > 0)
    {
        IGameClient client = null;

        client = (IGameClient)_timedOutConnections.Dequeue();

        if (client != null)
        {
            client.Disconnect();
        }
    }
}

Each room has its own task (thread). It processes a lot, user movement, chat messages, items, status updates. I figured rather than waiting for each room to process in RoomManager's OnCycle, use a new thread and try to process multiple at the same time, after all the server is multi-core.

Room's ProcessRoom

public void ProcessRoom()
{
    if (isCrashed || mDisposed)
    {
        return;
    }

    try
    {
        if (GetRoomUserManager().GetRoomUsers().Count == 0)
        {
            IdleTime++;
        }
        else if (IdleTime > 0)
        {
            IdleTime = 0;
        }

        if (Promotion != null && Promotion.HasExpired)
        {
            EndPromotion();
        }

        if (IdleTime >= 60 && Promotion == null)
        {
            Root.GetGame().GetRoomManager().UnloadRoom(Id);
            return;
        }

        GetRoomItemHandler().OnCycle();
        GetRoomUserManager().OnCycle();
        GetRoomUserManager().SerializeStatusUpdates();
        GetWired().OnCycle();
    }
    catch (Exception e)
    {
        _logger.Exception(e);
        OnRoomCrash(e);
    }
}


texts:
I need to port a Cocos2D-x project to Web (JS+HTML5). I'm trying to compile cocos2D-x samples using the emscripten project for cocos2d-x, and I've followed this tutorial http://www.cocos2d-x.org/projects/cocos2d-x/wiki/Emscripten_usage without success.

First, I followed the emscripten-specific guide using Linux Mint 15 with this tutorial:
https://github.com/kripken/emscripten/wiki/Tutorial

And also on Windows 7 64-bit following this another tutorial: https://github.com/kripken/emscripten/wiki/Using-Emscripten-on-Windows

The emscripten samples worked ok. Then, I downloaded the Cocos2D-x project:

git clone https://github.com/cocos2d/cocos2d-x.git
git submodule update --init --recursive

This version from github, has the "proj.emscripten" project. But, when I try to compile the cocos2D-x project and samples with:

make -f Makefile.emscripten -j 8

...after compiling several modules, it stops at "cocos2d-x/extensions/proj.emscripten" with this error:

mingw32-make[1]: Leaving directory `c:/dev/GitHub/cocos2d-x/CocosDenshion/proj.emscripten'
mingw32-make -C extensions/proj.emscripten all
mingw32-make[1]: Entering directory `c:/dev/GitHub/cocos2d-x/extensions/proj.emscripten'
makefile:12: *** recipe commences before first target.  Stop.
mingw32-make[1]: Leaving directory `c:/dev/GitHub/cocos2d-x/extensions/proj.emscripten'
Makefile.emscripten:21: recipe for target `all' failed
mingw32-make: *** [all] Error 2

This happens on both systems: Windows and Linux. I've installed the same version of the required dependencies that apears on those tutorials. Does anybody know what I'm doing wrong? Is there any easier way to get cocos2D-x running on the web without using the cocos2D-x proj.emscripten?

EDITED: There is an error on cocos2d-x/extensions/proj.emscripten/Makefile file. Changing the line 11 from this:

-I../network

...to this:

-I../network \

...solves this problem. Now compiles some more modules, but now I'm getting compiler errors, like

error: no member named 'bind' on namespace 'std'

could be a problem with the C++ compiler standards C++0x, C++11...?


texts:
I am trying to implement a group formation behavior where all the units in my group follow a leader and maintain their position throughout. So far I am able to move them, rotate and follow the leader. I have also implemented character separation and obstacle avoidance behaviors for all my units and the leader. However I want all the units to maintain the same relative position to the leader throughout the behavior ie say for example if one of the unit falls far behind the group due to an obstacle in its path, it should converge back to the main group to its initial relative position so that the formation of the group is not broken and stays the same throughout

I have stored all my units in a list and offset them from the leader at the start of the game. But I want their offset position to be maintained  throughout each update in the game. I am not able to do that.

Below is my code so far

public List<GameObject> followersList = new List<GameObject>();

    void Start()
            {
               for (int i = 0; i < followersList.Count; i++ )
                {
                    if(i%2 == 0)
                      followersList[i].transform.position = new Vector3(gameObject.transform.position.x + (2 + i*2 ), gameObject.transform.position.y, gameObject.transform.position.z - (2 + (i*2 )));
                    else
                      followersList[i].transform.position = new Vector3(gameObject.transform.position.x - (2 + i*2), gameObject.transform.position.y, gameObject.transform.position.z -  (2 + (i*2 )));
                }
        }

    private void VShapeFlockWander()
        {
            Followers = GameObject.FindGameObjectsWithTag("follower");
            Wander(gameObject);
            foreach (GameObject Follower in Followers)
            {
                followerDirection = (gameObject.transform.position - Follower.transform.position).normalized;
                Vector3 normal = CheckFollowerCollisionAvoidance(Follower);
                Vector3 followerSepVector = CheckFollowerSeparation(Follower);
                followerSepVector.y = 0;
                followerDirection += (normal + followerSepVector);
                Quaternion rot = Quaternion.LookRotation(followerDirection);
                Follower.transform.rotation = Quaternion.Slerp(Follower.transform.rotation, rot, Time.deltaTime * 3.0f);
                Follower.transform.position += (Follower.transform.forward * Time.deltaTime * acceleration);
                if (acceleration < vShapeWanderSpeed)
                {
                    acceleration += 0.01f;
                }
            }
        }

in the code above all the followers represent the units and the gameObject is the target leader to follow. All the other behaviors like separation and collision avoidance are working fine. Only thing I want to achieve now is for all the followers to maintain their relative position to the leader throughout.

I tried using a Dictionary for each follower as key and its initial difference to the target as the value. Then somehow use that difference factor and make them move in a stable formation but I cannot get it to work either


texts: How are one-to-many relationships usually expressed in ECS architecture?

texts:
I'm trying to implement a simple ECS to help understand the concepts, and I am having a bit of trouble wrapping my head around how it would be used in cases where there is not a 1-to-1 mapping between entities and components.

For instance, an example of ECS, as I understand it, is that you might have a "drawable" component defined, which contains a mesh ID and a material ID required for drawing.  This is easy to understand  in the case you want a game like Super Mario, where each character is represented by exactly one sprite at any time, but what if you need more than one mesh to draw some characters?

Is it common to allow more than one component of the same type on an entity?  Or else would you typically have an entity for each drawable component, and implement some kind of "join table" to map sub-components to a parent?


texts: How to clip cut-off using different frustrum than that of original camera? How to cut plane by pyramid shape?

texts:
SOURCE : http://amd-dev.wpengine.netdna-cdn.com/wordpress/media/2012/10/Mitchell_LightShafts.pdf

This process is part of creating light draft effect. And I am suggested to do the described process in order to enhance performance and I really want to do it.

However I am clueless on how I can apply "frustrum perspective matrix" from other camera to my camera perspective to chop off that square plane into shapes that fit into the "frustrum perspective matrix".

I am guessing I need to do this on CPU side first? But that's as far as my wild guess goes


texts: How to stop the Unity Editor from continuously rendering?

texts:
Look closely at the image below. Even though the game is not running the scene shows that green wheel is spinning. This means the scene is being rendered constantly and my battery is dying.

I know Unity used to not do this and was in fact one of the reasons I liked Unity over some other engine that defaulted to always running and would make my laptop fans start up even when just sitting idle in the editor.

Is there any way to get Unity to render on demand. Meaning, only render when I interact with it, when I move the camera or change a setting like it used it?

I saw in preferences there's an "interaction mode" setting but the best it can be set to is don't render faster than 30fps. That's not useful.

Is there some other setting to get the editor to only render when interacted with?


texts:
I want to replace the main character of my 2D game by an Xbox avatar. How can I do that?
How can I add an avatar to my project?
How can I draw an avatar?

For example, I draw my main character like that:

spriteBatch.Begin();
  spriteBatch.Draw(Main_Character,Main_Character_Position,Color.White);
spriteBatch.End();

What must be changed to draw an avatar?


texts: How do I deal with closely coupled systems in a game engine?

texts: Let's say a game engine had a central game class as well as multiple systems (as objects) that are stored within it. These systems (such as input, rendering, sound, etc) would also be updated by this main game class. What if the input manager detects that the close button on the window if pressed. It would cause the game to shutdown by, say, calling a quit method inside the game class. This would be an example of a closely coupled system which is typically not good for future expansion of these systems. How would a closely coupled system like this be dealt with in order to make it more loosely coupled?


texts:
I have a top/down grid based multi-player game. So I have a 2D array on the server that holds the entire map and a much smaller 2D array on the client that holds only what the client needs to see of the bigger server map. For now we'll say the client 2D is 5x5 but the server is 400x400.

When the player starts, the server see's what tile it's on and gets the 5x5 area around the player (with the player being at the center of that) and sends the tile info to them. The client then updates their 5x5 array and draws the objects in the tiles. This is all great and working.

Now, when the player moves I want to basically always keep the 5x5 array updating around them, loading and unloading the objects in those tiles from the server. Now in reality it'll be bigger than 5x5 but I'm using this for testing purposes only since it's smaller to manage.

I don't want to always send the 5x5 array (will be larger in final version) to the player because it's a waste of bandwidth to do so. If the player moves right 1 tile then the majority of the information in their 5x5 array is still the same. Really it's only the right most column that changed and needs to be updated while every other column gets shifted 1 to the left. The same happens if they move up, down, left, or any of the diagonals.

The question I'm after would be around how the server can track and easily send just the changes of tiles for clients. So on the server I send tile updates once a second, NOT when they tell me they changed tiles. When I send them data I store their current position as last position, so this means I can get the 5x5 array from their last position (which this is what their 5x5 array looks like) and I can get the new 5x5 array from their current position. I the need to know what changed from the last position 5x5 array to this new 5x5 array and only send them those changes along with how to shift their 5x5 array around to match this new 5x5 array. Is there any neat tricks out there for comparing 2 2D arrays to find out such information? Does anyone have any other ideas on how to handle this situation? I'm open to new ideas around this.


texts: How should I parse user input in a text adventure game?

texts:
Parsing user commands in a text adventure is a spectrum from Adventure's simple "go north" to some mind-bogglingly clever ones in hhgttg.

I seem to remember reading nice how-tos in computer magazines back in the 80s, but now I find almost nothing on the 'net except a brief Wikipedia ref.

How would you do it?

Update: I went with the simplest approach possible in my Ludum Dare entry.


texts: HLSL Gaussian blur pixelshader: blur is not occurring

texts:
I am trying to use postprocessing to create a gaussian blur, however, no blur is to be seen, what am I doing wrong?

I have included the full code at the bottom of this post in a google docs link, but here are the most important bits and pieces.

Part of the xna draw method:

RenderTarget2D renderTarget;
renderTarget = new RenderTarget2D(this.device, screenWidth, screenHeight, true, pp.BackBufferFormat, pp.DepthStencilFormat);
this.device.SetRenderTarget(renderTarget);
this.device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.DeepSkyBlue, 1.0f, 0);
Rectangle screenRectangle = new Rectangle(0, 0, screenWidth, screenHeight);

// Set the effect parameters (the 'simple' technique creates a red lambertian shaded model, like is shown on the image below)
effect.CurrentTechnique = effect.Techniques["Simple"];
effect.Parameters["TextureWidth"].SetValue(screenWidth);
device.DepthStencilState = DepthStencilState.Default;
device.BlendState = BlendState.Opaque;

// Draw the model
mesh.Draw();

// Render our scene
this.device.SetRenderTarget(null);

effect.CurrentTechnique = effect.Techniques["GaussianBlur"];

spriteBatch.Begin(0, BlendState.Opaque, null, null, null, effect);
spriteBatch.Draw((Texture2D)renderTarget, screenRectangle, Color.White);
spriteBatch.End();

The pixelshader:

float Pixels[13] =
{
   -6,
   -5,
   -4,
   -3,
   -2,
   -1,
    0,
    1,
    2,
    3,
    4,
    5,
    6,
};

float BlurWeights[13] =
{
   0.002216,
   0.008764,
   0.026995,
   0.064759,
   0.120985,
   0.176033,
   0.199471,
   0.176033,
   0.120985,
   0.064759,
   0.026995,
   0.008764,
   0.002216,
};

float4 GaussianPixelShader(float2 TextureCoordinate : TEXCOORD0) : COLOR
{
    // Pixel width
    float pixelWidth = 1/TextureWidth;

    float4 color = {0, 0, 0, 1};

    float2 blur;
    blur.y = TextureCoordinate.y;

    for (int i = 0; i < 13; i++)
    {
        blur.x = TextureCoordinate.x + Pixels[i] * pixelWidth;
        color += tex2D(TextureSampler, blur.xy) * BlurWeights[i];
    }

    return color;
}

What I have further found out by testing

The code in the GaussianPixelShader does get executed (if I set it to just return a black color it gives an entire solid black screen) but just doesn't seem to work/do the blurring.

Images

This is how currently my model looks (I cant see any blurring but maybe the blurring is just too light): image.

Full Code

Link to the shader code and the link to the xna/c# code.


texts: Are interleaved vertex data formats better than non-interleaved formats?

texts:
I have been reading up on data formatting for 3D objects so that I can render my meshes as fast as possible in OpenGL. I am quite new to OpenGL so bear with me.

The format for interleaving your meshes goes something like:

 position, normal, texture1, texture2  //this I understand

Most formats for 3D meshes, however, don't use this structure. From my understanding the interleaved format is fast for execution but isn't necessarily the best in terms of size, since you never really have as many unique normals as you do vertices, since (if you are using hard shading) all normals for a face would be the same.

A hard shaded basic cube for example has 8 unique vertices and 6 unique normals.

So my question is, is it worth it to set up an interleaved format like this despite the fact that if you had 3 separate buffers you would use MUCH less data?

Also (remember I'm new) is it somehow possible to do pack your vertex information like:

 all positions, all normals, all tex1, all tex2 //so all of one type in a sequence

and have different sets of indices for each type? Or is that just dumb?


texts: I've been working on this FPS game and I've gotten to the point where I need to start adding the weapons in and have been having trouble creating (unsure of what engine to use) them.  Is there an easier way to create models for unity 3D?


texts:
I'm trying to find some actual latency benchmarks for using WebSockets in HTML5 games. If I were to go down this route, I'd probably end up using (as you might expect) Node.js and Socket.IO.

However, most search results I find tend to discuss what is possible or how it would be done. I'm more concerned about what kind of performance you can get out of this platform.

These are the only demos that I've found that include a latency meter for the user:

http://rawkets.com/

http://o.smus.com/client/

Most of the time it stays around 100-200ms.. Not sure how reasonable that number is for other games out there, although I have come across people using long-polling on top of Node.js, which gets you some pretty bad lag..


texts: Checking if player is grounded using tilemap collision detection

texts:
beginner here just trying to learn the basics. I was following this tutorial but I ran into some trouble. Heres a screenshot of unity

So the tutorial calls for tagging the terrain with "Grounded" and essentially checks if the 2D collision box for GroundCheck collides with anything with a "Grounded" tag using the Move2D and Grounded scripts below. Note that the Move2D script is a component of the Player gameobject.
Move2D
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Move2D : MonoBehaviour
{
    public float movespeed = 5f;
    public float jumpforce = 10f;
    public bool isGrounded = false;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        Jump();
     Vector3 movement = new Vector3(Input.GetAxis("Horizontal"),0f, 0f);
     transform.position += movement * Time.deltaTime * movespeed;
    }
    void Jump(){
        if (Input.GetButtonDown("Jump") && isGrounded == true){
        gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0f, 5f), ForceMode2D.Impulse);
        }
    }
}

Grounded.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Grounded : MonoBehaviour
{
    public GameObject Player;
    // Start is called before the first frame update
    void Start()
    {
         Player = gameObject.transform.parent.gameObject;
    }

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

    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if(collision.collider.tag == "Ground")
        {
            Player.GetComponent<Move2D>().isGrounded = true;
            Debug.Log("test");
            print("GROUNDED");
        }
    }

    private void OnCollisionExit2D(Collision2D collision)
    {
        if(collision.collider.tag == "Ground")
        {
            Player.GetComponent<Move2D>().isGrounded = false;
        }
    }
}

The error I'm running into is that it appears unity isn't recognizing that the player has collided with the tilemap collision box, so the bool isGrounded is just perpetually false and the player is unable to jump. Any help would be appreciated!
EDIT: below are screenshots of configs of Grid, gound, and GroundCheck in that order


texts: Game Maker Studio - how do I disable mouse click for a duration of time?

texts:
I Have a button that starts in a rest state, and then after clicking on the button, it animates out. I want to disable the mouse click for around 30 steps after the button has been clicked, otherwise the player will be able to constantly click on the button, which resets the animation and messes up my menu.

Is there any way to disable the mouse click for a duration of time before enabling it again?

This is the code I have used to try and make the variable "click" alternate between true and false (it is supposed to remain false while alarm[0] is between 30 and 0).

Initially (in the create event)

click = false;
alarm[0] = -1;
alarmReset = true;

this is the code found in the step event:

if(mouse_check_button_pressed(mb_left))
{
    if(alarmReset == true)
    {
    click = true;
    alarm[0] = 30;
    alarmReset = false;
    }
}

if (alarm[0] > 0 )
{
    if (alarm[0] < 30)  click = false;
}
if (alarm[0] < 0 ) alarmReset = true;

When running this code, "click" is initially false, but when I click, it gets set to true, and then is never set to false again. Any help would be appreciated.


texts:
Is it possible to detect when an object and a bitmap collide. I have an arraylist of sprites that I am shooting with an image. I tried using this method here but as soon as the bitmap appears the sprite disappears, this is in the Sprite class:

public boolean isCollision(Bitmap other)
{
    if(other.getWidth() > x && other.getWidth() < x + width && >other.getHeight() > y && other.getHeight() < y + height);
    return true;
}


texts: Framerate limited by lack of mouse movement?

texts: Using Torque, it appears that the program is running at around 25fps when the mouse is still, but as long as I keep the mouse moving, the framerate can hit well over 300fps. What in the world would cause the framerate to be tied to mouse movement?


texts:
Are there any alternatives to voxel based terrains?

Such terrain should be fully destructable, allow for arches, overhangs, preserve sharp features where needed and keep consistent topology.

  Maybe you can explain the problem that makes you ask this question?
  Voxel based terrain is basically just using a 3D grid of data to store
  data. There are lots of ways to render that data, but it doesn't get
  much simpler for storing it. –  Byte56

Current isosurface extraction methods aren't most effective/bug-free.

Cubical Marching Squares seem to solve most of the issues, however it is a relatively new method and there aren't too many resources about it. (I've found single university paper)

Even if we stick to CMS, when we want to add multi-material support, we can either divide surface into multiple meshes, or pass a texture array or texture atlas to shaders, then we are limited to set amount of textures and additionally increase memory-usage alot.


texts:
Usually, the camera's near value is set to sth like 0.1f. However, this (assuming 1.0f = 1 metre) makes everything that's closer than 10 cm from the camera invisible. On the other hand, when working with big open terrains too small near value results in this (yes, that's a sandy coast and water :P):

instead of this:

(Apparently, when the difference in distance between too objects is too small, you get artifacts. Something to do with precision, I guess, and apparently the precision is dependent on the near camera value.)

My question is - is it possible to set near value to something like 0.001f and not get the above artifacts?


texts: Why does my Perlin Noise Terrain have rough parts on the edges?

texts:
I followed this tutorial: https://gamedevacademy.org/complete-guide-to-procedural-level-generation-in-unity-part-1/
The important bits of my code are below. I tried messing around with different parameters for a while, and I'm not sure how to fix the noticeable lines between tiles.
void GenerateTile()
    {
        Vector3[] meshVertices = this.meshFilter.mesh.vertices;
        int tileDepth = (int) Mathf.Sqrt(meshVertices.Length);
        int tileWidth = tileDepth;

        // calc heightmap
        float[,] heightMap = this.noiseMapGenerator.GenerateNoiseMap(tileDepth, tileWidth, this.mapScale, -this.transform.position.x, -this.transform.position.z, waves);

        // update texture and mesh
        Texture2D tileTexture = BuildTexture(heightMap);
        this.tileRenderer.material.mainTexture = tileTexture;
        UpdateMeshVertices(heightMap);
    }

public float[,] GenerateNoiseMap(int mapDepth, int mapWidth, float scale, float offsetX, float offsetZ, Wave[] waves)
    {
        // Instantiate noiseMap
        float[,] noiseMap = new float[mapDepth, mapWidth];

        // Populate noiseMap
        for (int zidx = 0; zidx < mapDepth; zidx ++)
        {
            for (int xidx = 0; xidx < mapDepth; xidx ++)
            {
                float noise = 0f;
                float norm = 0f;
                float x_val = (xidx + offsetX)  / scale;
                float z_val = (zidx + offsetZ) / scale;

                // Layer multiple waves on top of each other
                foreach (Wave wave in waves)
                {
                    noise += wave.amplitude * Mathf.PerlinNoise( (x_val * wave.frequency + wave.seed), (z_val * wave.frequency + wave.seed));
                    norm += wave.amplitude;
                }

                // Normalize and assign
                noise /= norm;
                noiseMap[zidx, xidx] = noise;
            }
        }
        return noiseMap;
    }


texts: Model texturing not seamless at certain zooms? (C# XNA)

texts:
I found a very odd glitch with my game this morning. XNA doesn't render certain textured models properly, while other models are completely unaffected. And it's not even like my models are made incorrectly - even one of my spheres doesn't render properly at certain zoom levels. Agh, it's hard to explain, here's a picture:

The arrow on the left is in blender. The right two pictures are from within my game. At first, I thought that this was some sort of bleeding / collision issue of the arrow and the space-y background. But when I removed the background, the issue was still there.

So what are all those weird pink dots and seams? This is what my texture looks like:

Oddly enough, all of the other models in my game render correctly, except for the space sphere you see behind the arrow. (It only looks incorrect at other zoom levels, although no pink dots, just more black seams)

So I tried to find a similarity between the two malfunctioning objects, the arrow and the sphere. It occurred to me that they were the only objects whose textures did not cover the entire model, but instead were tiled. So like the UV unwrapping was not totally contained in the texture... here's a picture of what the UV looks like in blender:

Based off of this, I concluded that somehow XNA is not tiling the texture properly when it maps it to the objects. Since blender renders the model correctly and XNA doesn't, I'm assuming the problem is with XNA. (although correct me if I'm wrong)

So finally, my question is: I'm totally lost - does anybody know how to fix this?

Thanks!

EDIT: As requested in comments, here is my drawing code. It's nothing special, just your basic model draw code.

class OrderedDrawModel
{
    Model M;
    Matrix Transform;
    float Transparency;
    Vector3 Ambience;
    public float Distance;
    float Reflect;
    public OrderedDrawModel(Model M, float Transparency, Vector3 Ambience, Matrix Transform, float Distance, float Reflectivity)
    {
        this.M = M;
        this.Transparency = Transparency;
        this.Ambience = Ambience;
        this.Distance = Distance;
        this.Transform = Transform;
        Reflect = Reflectivity;
    }
    public void Draw(GraphicsDeviceManager graphics, Camera_Edit C)
    {
        Matrix[] T = new Matrix[M.Bones.Count];
        M.CopyAbsoluteBoneTransformsTo(T);
        foreach (ModelMesh mesh in M.Meshes)
        {
            foreach (BasicEffect basicEffect in mesh.Effects)
            {
                basicEffect.World = T[mesh.ParentBone.Index] * Transform;
                basicEffect.View = C.view;
                basicEffect.Projection = C.projection;
                basicEffect.LightingEnabled = true;

                basicEffect.AmbientLightColor = Ambience;
                basicEffect.DirectionalLight0.DiffuseColor = Color.White.ToVector3();
                basicEffect.DirectionalLight0.Direction = Vector3.Normalize(new Vector3(-3, -3, 1));
                basicEffect.DirectionalLight0.SpecularColor = new Vector3(Reflect, Reflect, Reflect);

                graphics.GraphicsDevice.BlendState = BlendState.AlphaBlend;
                basicEffect.Alpha = Transparency;
            }
            mesh.Draw();
        }
    }
}

I create the object with this line:

DrawModel(Arrow, 1.0f, Matrix.CreateScale(5f), new Vector3(0, 0, 0), 0.4f);
        //Model  alpha transform_matrix        ambience            specular

Which adds it to a list of back-to-front ordered models that get drawn by calling their draw method.


texts: SGC toolkit for PyGame and resizeable windows

texts: Can I create a resizeable main window if I use the SGC GUI toolkit for PyGame? If so, how?


texts: fastest way to check for surrounding tiles

texts:
I'm working on a tile map where each type of tiles has 12 states with 12 different sprites associated with it, what I'm trying to say is that whenever I place a tile let's say a road tile, that tile should adjust itself automatically according to the 4 tiles surrounding it, so for example if the tile above it is a road tile and the tile below it is also a road tile, it should automatically adjust itself into a vertical road tile... there is 12 states a tile can have:
1-closed(not surrounded by any similar tile)
2-horizontal(similar tiles up and down)
3-vertical(similar tiles right and left)
4-open from up and left(similar tiles to the left and above)
5-open from left and down(...)
6-open from down and right(...)
7-open from right and up(...)
8-open from up & left & down(3 similar tiles up, left and down)
9-open from left & down & right(...)
10-open from down & right & up(...)
11-open from right & up & left(...)
12-open from all 4 directions(all surrounding tiles are similar)
the problem is that I don't know how to check for surrounding tiles and choose the right tile state without having a huge mess of if statements and performance waste, and I don't have enough experience with algorithms and data structures to figure it out myself.
how can check all 12 states the fastest way possible ?
thanks!


texts: How could I access game data from a dev machine at runtime from a mobile platform?

texts:
When working on a game on a mobile platform, having read/write access to game data (assets, configuration files) stored on the dev machine at runtime would enable building of tools to quickly iterate, debug, and analyze the game at runtime.

For iOS & Android, is there any way to have access to these data files from the dev machine while the game is running on the mobile device?

Please do not recommend a tool, or a 3rd party engine that does this.


texts:
I have a new browser based game that I've worked on for a few months. Obviously all that effort goes to waste if no one sees it.

I know there's topics to do with games promotion, but browser games are a different field entirely.

How can I promote my browser game?


texts: How to blend bullet sprite from white to yellow in libgdx

texts: Does anyone have a clue that will make my bullet sprite fade from yellow to white? As the bullet is created it will be white but when it trails on it will turn yellow. Any ideas how? Is it a simple process or does it require a lot of code writing?


texts: What is the purpose of the macro UNITY_EDITOR?

texts:
I found on a tips guide in Unity that I can do:

#if UNITY_EDITOR
do_something()
#endif

And do_something() will only be executed on Unity editor. Even more, when I build the game, that section of the code won't be compiled.

I found that as something very interesting, I thought it could be useful for example to use it on DrawGizmos methods since they can only be used on Unity Editor, and you don't need them on a finished product.

What has it been designed for? Is there anything bad that could come from using it?


texts:
I am looking for some guidance on how to simplify my nodes on a path when a user builds on the fly.

Imagine a path like this with a gap:

Logically 3 nodes are required 2 connected one isolated.

But now the user builds another inbetween these nodes like this:

You can see the idea is now the nodes have simplified automatically and i only now have 2 nodes on my path.

My question is how would i approach the logic for this so the code can update accordingly? I currently store my path data as an array of nodes which have a property that lists an array of other nodes that link to them. This is what it would look like before the user adds a new tile to the map:

var path    = [];
    path[0] = {'x':1,'y':3,'linksTo':[1],'id':0};
    path[1] = {'x':1,'y':4,'linksTo':[0],'id':1};
    path[2] = {'x':1,'y':1,'linksTo':[3] ,'id':2};
    path[2] = {'x':1,'y':0,'linksTo':[2] ,'id':3};

I use JavaScript - but the language isn't strictly important only the logical approach here.

I should be more clear, the paths can go in 8 compass directions in total the diagonals will be 45 degree angles rather than any other type of shallow angle. But the image just merely shows an example of a path running north to south.


texts: Colour intersection of two alpha-blended sprites

texts:
In XNA, is it possible to merge two alpha blended sprites so they look like one contiguous shape, eliminating the merge of colour at the overlap? At the moment when I try, the intersection is quite visible:

I'd like it to look more like this mockup:

This is the drawing code for this example, but it's similar to what's being used in the actual game:

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.Black);

        spriteBatch.Begin(SpriteSortMode.FrontToBack, null, SamplerState.PointClamp, null, null);

        for (int x = 10; x <= 1000; x += 10)
            for (int y = 10; y <= 1000; y += 10)
                spriteBatch.Draw(Content.Load<Texture2D>("dot"), new Vector2(x, y), null, Color.Gray, 0, Vector2.Zero, 1, SpriteEffects.None, 0.1f);

        spriteBatch.Draw(Content.Load<Texture2D>("circle"), new Vector2(200, 200), null, Color.FromNonPremultiplied(255, 255, 255, 50), 0, Vector2.Zero, 1, SpriteEffects.None, 0.5f);
        spriteBatch.Draw(Content.Load<Texture2D>("circle"), new Vector2(300, 200), null, Color.FromNonPremultiplied(255, 255, 255, 50), 0, Vector2.Zero, 1, SpriteEffects.None, 0.5f);

        spriteBatch.End();

        base.Draw(gameTime);
    }

I suspect the answer is somehow combining the textures before passing them to the spritebatch to be drawn, but I'd prefer to avoid that if at all possible.

Thanks for any help!


texts: How can I use 9+ vertices with CollisionPolygon2D?

texts:
I am using CollisionPolygon2D to implement collision detection for polygons with 3-16 vertices. It works for polygons with 3-8 vertices, but additional vertices (9+) don't seem to register at all.
This is how I implement collision detection for a nonagon in C#:
var unit = 256f / 96f;

_collisionShape2D = _node.CreateComponent<CollisionPolygon2D>();
_collisionShape2D.As<CollisionPolygon2D>().VertexCount = 9;
_collisionShape2D.As<CollisionPolygon2D>().SetVertex(0, new Vector2(-0.3515625f, -1.000000f) / 2 * unit);
_collisionShape2D.As<CollisionPolygon2D>().SetVertex(1, new Vector2(+0.3515625f, -1.000000f) / 2 * unit);
_collisionShape2D.As<CollisionPolygon2D>().SetVertex(2, new Vector2(+0.8593750f, -0.515625f) / 2 * unit);
_collisionShape2D.As<CollisionPolygon2D>().SetVertex(3, new Vector2(+1.0000000f, +0.140625f) / 2 * unit);
_collisionShape2D.As<CollisionPolygon2D>().SetVertex(4, new Vector2(+0.6250000f, +0.750000f) / 2 * unit);
_collisionShape2D.As<CollisionPolygon2D>().SetVertex(5, new Vector2(0000000000f, +1.000000f) / 2 * unit);
_collisionShape2D.As<CollisionPolygon2D>().SetVertex(6, new Vector2(-0.6250000f, +0.750000f) / 2 * unit);
_collisionShape2D.As<CollisionPolygon2D>().SetVertex(7, new Vector2(-1.0000000f, +0.140625f) / 2 * unit);
_collisionShape2D.As<CollisionPolygon2D>().SetVertex(8, new Vector2(-0.8593750f, -0.515625f) / 2 * unit);

Note, the nonagon is a Sprite2D with a width and height of exactly 256 pixels. In my project, 1 world unit equals 96 pixels; hence, why I multiply by unit.
If this were an octagon, it would work as expected; however, that ninth vertex doesn't seem to register. What actually happens is the eight vertex connects with the first vertex and the ninth is ignored entirely. The same applies to polygons with any number of additional vertices (decagon, hendecagon, and so forth). This leads me to believe CollisionPolygon2D simply does not work for polygons with 9+ vertices.
According to the official documentation:

Polygon shapes are solid convex polygons. A polygon is convex when all line segments connecting two points in the interior do not cross any edge of the polygon. A polygon must have 3 or more vertices.
Polygons vertices winding doesn't matter.

The nonagon in question is convex as far as I am aware. This is what it looks like:

Courtesy of Wikipedia.
As you can see, none of the angles exceed 180, indicating it is indeed convex. The following demonstrates the collision produced in my example:

I tried replacing CollisionPolygon2D with CollisionChain2D using the exact same vertices to see if that would work instead, but I get really weird collision behavior (as if the size is either very small or just nonexistent; for instance, the object does not rotate as you'd expect when it falls and hits other objects).
For craps and giggles, I decided to add a tenth vertex, which equals the first, thinking maybe I needed to "close" the shape; that theory didn't play out well either...
I did get CollisionChain2D to work for some concave polygons with <=6 vertices, but it doesn't appear to work at all for convex polygons with any number of vertices.
What am I missing here?


texts: i am a c++ programmer , and I want to develop games . I chose sfml , because I wanted to see what happens behind the scene better . I have an idea to make , and the desired platform is mobile devices(android , ios) . I have seen that sfml , support for touch and other capabilities of mobile devices , but I have no idea , how I can write a code , that works on all of them .


texts: creating a simulation game,  what type of knowledge is needed?

texts:
I am a beginner in game development. As a part of learning and fun, want to create a game in java-script and html5. I am planning a game that we were used to play in childhood, that is "new business"- a monopoly game, in that we used to buy ,rent,sell places and bank we get some money to play and etc. are features. Its just simple ludo like game.

So can anyone suggest me from where to start? what will be the designing?

Is it possible to create it only in a html5 and java-script.


texts: I'm familiar with the notion of entity-component-system architecture, and its advantages over traditional class trees.  That being said, are there scenarios where one wouldn't want to use entity-component-system architecture?


texts: I'm using OnGUI to draw a rect when I "box select" or "drag select". The texture that gets drawn is a PNG file made in Paint.Net with the opacity - alpha channel set quite low. In Unity however, when I go to box select, the texture is completely opaque. How do I get Unity to honor the alpha set in Paint.Net? I also wouldn't mind using Unity itself to adjust the opacity, but I haven't found such an option in the import texture part of the inspector.


texts:
I try to run a simple renderer on my win7 machine but it dies at the first glGenBuffers call.
The computer has an Intel HD3000 card, with the latest driver (OpenGL 3.0 support).
I use glew 1.10 (self compiled with mingw).
The linker command is:

g++ -LC:\Program Files\Microsoft SDKs\Windows\v7.1\Lib -Lc:\opt\glew-1.10.0\lib -LC:\opt\SDL-1.2.15\lib\x86 -o pysicsdemo.exe src\main.o src\Box.o -lOpenGL32 -lglu32 -lSDLmain -lSDL -lglew32.dll

And the result is 0x0. Most probably glew can't load the extension, but why?


texts: How to implement a stack of game states in C++

texts:
I'm new to C++ and as a college proyect I'm building a 2D platformer with some classmates, I recently read that it's a good idea to have a stack of gamestates instead of a single global variable with the game state (which is what I have now) but I'm not sure how to do it.

Currently this is my implementation:

class GameState
{
    public:
        virtual ~GameState(){};
        virtual void handle_events() = 0;
        virtual void logic() = 0;
        virtual void render() = 0;
};

class Menu : public GameState
{
    public:
        Menu();
        ~Menu();
        void handle_events();
        void logic();
        void render();
};

Then I have a global variable of type GameState:

GameState *currentState = NULL;

And in my Main I define the currentState and call it's methods:

int main(){
    currentState = new Menu();
    currentState.handle_events();
}

How can I implement a stack or something similar to go from that to something like this:

int main(){
    statesStack.push(new Menu());
    statesStack.getTop().handle_events();
}


texts: Instances in the Unity Profiler Timeline

texts:
What do Instances mean when you click on an operation in the Timeline section of Unity Profiler?

In this example:

  Total: 11.90 ms (10 Instances)


texts:
I'm having a hard time modeling weather.
Modeling a single aspect is trivial - some sinusoidal pattern + random noise. However more than 1 is blowing my mind. I cannot have wind, falling leaves, rain, and snow all to be random. Simple collisions like rain and snow should never happen.
On top of this I'd like an "intensity" level for maybe each. But this can come after the main logic.
Weather is stored in MySQL.
All your suggestions are welcome, but please don't suggest pinging some zipcode and pulling weather from there.

Utilizing suggestions from, actually, all answers below I've come up with this not-to-scale distribution:

Each feature will be computed with a random noise, and the combination of the 3 will produce overlay effects.
(temp < 0) and (humid > 65) => snow


texts:
I have read that the Windows messages are recommended way over DirectInput to control mouse and keyboard.

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

  The use of DirectInput for keyboard and mouse input is not
  recommended. You should use Windows messages instead.

Why is it so? Because the DirectInput is still in version 8? Isn't it extending anymore?


texts:
I have what appears to be a depth or order rendering problem which I have never seen happen before. My terrain and water are rendered with my displacement shader, and at the moment all other models are rendered with my standard shader, and I am using deferred rendering.
Now, as you can see in the images, I have a sphere that is half cut off, as though d3d thinks that the water is somehow in front of the sphere, which it is not. If I move down to water level, you can see the whole sphere.
If I render the same sphere with my displacement shader, there is no problem at all. If I go into my displacement shader class, and cut out the hull and domain shader stages, then the terrain and water start to do the weird z buffer issue that the sphere is having.
Is there something conceptual anyone can think of without me having to post hundreds of lines of code? However, happy to post code if needed.

Thank you

UPDATE:
I've narrowed it down to the domain shader - the line that physically changes the output triangles' position. When I comment out this line, it solves the problem, although then I have no tessellation. Do I need to do some kind of manual depth writing after changes the position?

Domain Shader:

cbuffer cbDomainInfo
{
    float3 g_vEyePosition;
    float _padding;
};

struct PatchTess
{
    float flEdges[ 3 ] : SV_TessFactor;
    float flInside : SV_InsideTessFactor;
};

struct DomainInput
{
    float4 vPosition    : POSITION;
    float2 vTexcoord    : TEXCOORD0;
    float3 vNormal      : NORMAL;
    float3 vViewVec     : TEXCOORD1;
    float flAlpha       : ALPHA;
};

struct DomainOutput
{
    float4 vPosition    : SV_POSITION;
    float2 vTexcoord    : TEXCOORD0;
    float3 vNormal      : NORMAL;
    float3 vViewVec     : TEXCOORD1;
    float flAlpha       : ALPHA;
};

Texture2D g_texDispMap;
SamplerState g_samSampler;

[ domain( "tri" ) ]
DomainOutput DS( PatchTess input, float3 uvwCoord : SV_DomainLocation, const OutputPatch<DomainInput, 3> patch )
{
    DomainOutput output;

    output.vPosition = uvwCoord.x * patch[ 0 ].vPosition + uvwCoord.y * patch[ 1 ].vPosition + uvwCoord.z * patch[ 2 ].vPosition;
    output.vNormal = uvwCoord.x * patch[ 0 ].vNormal + uvwCoord.y * patch[ 1 ].vNormal + uvwCoord.z * patch[ 2 ].vNormal;
    output.vTexcoord = uvwCoord.x * patch[ 0 ].vTexcoord + uvwCoord.y * patch[ 1 ].vTexcoord + uvwCoord.z * patch[ 2 ].vTexcoord;
    output.vViewVec = uvwCoord.x * patch[ 0 ].vViewVec + uvwCoord.y * patch[ 1 ].vViewVec + uvwCoord.z * patch[ 2 ].vViewVec;
    output.flAlpha = uvwCoord.x * patch[ 0 ].flAlpha + uvwCoord.y * patch[ 1 ].flAlpha + uvwCoord.z * patch[ 2 ].flAlpha;

    output.vNormal = normalize( output.vNormal );

    float flMipInterval = 20.f;
    float flMipLevel = clamp( ( distance( output.vPosition, float4( g_vEyePosition, 1.f ) - flMipInterval ) ) / flMipInterval, 0.f, 6.f );

    float flHeightMap = g_texDispMap.SampleLevel( g_samSampler, output.vTexcoord, flMipLevel ).r;

    //TODO: Pass in height scale via cbuffer
    //This next line causes the problem:
    output.vPosition += float4( ( 20.f *( flHeightMap - 1.f ) ) * output.vNormal, 1.f );

    return output;
}


texts: Unity 3d C# - Can’t move through the air while jumping

texts:
The code below allows my character to jump and move which works fine, except I can't move while jumping. I can jump in one place or jump in a certain direction but nothing else. I can't fix it, can someone help?

using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;

public class PlayerMotor : MonoBehaviour {

private CharacterController controller;

public float speed = 1.0F;
public float jumpSpeed = 1.0F;
public float gravity = 1.0F;
private Vector3 moveDirection = Vector3.zero;
void Update() {
    CharacterController controller = GetComponent<CharacterController>();
    if (controller.isGrounded) {
        moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
        moveDirection = transform.TransformDirection(moveDirection);
        moveDirection *= speed;
        if (Input.GetButton ("Jump")) {
            moveDirection.y = jumpSpeed;
        }
    }
    moveDirection.y -= gravity * Time.deltaTime;
    controller.Move(moveDirection * Time.deltaTime);
}

Thanks in advance :)


texts: GameMaker Studio 2: DnD - How do I change Idle animation to Walking Animation

texts:
I have an idle animation into an object. I am able to have it moved to one point, left & right but but the problem is transitioning from Idle to Walking Forward. I did tried step but I realized that it's for animation ticks, and I can't really find any tutorials on it yet.

How do make a smooth animation transition from Idle to Walking?


texts: How to detect that user has touched UI canvas in Unity 4.6?

texts:
In my 2d game I have a HUD with some buttons on it. To make it I am using new UI system, which was presented in Unity 4.6. When user is touching button, I am running method, which was declared in EventSystem. But the problem is in that I need to make difference between touch in any part of screen and touch directly on UI, because when I am touching to any part of screen my character starts fighting. And when I am touching the UI image,  my character starts fighting and only after that the method that was attached to UI image EventSystem starts. So I need to check what I am touching on screen. For desktop platform everything is okay, when I am running this code:

if (Input.GetMouseButtonDown(0))
{
    EventSystem eventSystem = EventSystem.current;
    if (eventSystem.IsPointerOverGameObject())
    {
        return;
    }
}

And for mobile platforms I am using this code, but it doesn't work. The system doesn't check that user pressed on UI image.

public class TouchController : MonoBehaviour {
    Canvas BonusesAndPotionsCanvas;
    GameObject BonusesAndPotions;
    void Start ()
    {
        BonusesAndPotions = GameObject.FindGameObjectWithTag ("bonuses_and_potions");
        BonusesAndPotionsCanvas = BonusesAndPotions.GetComponent<Canvas> ();
    }

    void Update()
    {
        EventSystem eventSystem = EventSystem.current;
        if (eventSystem.currentSelectedGameObject != null)
            return;
        for (var i = 0; i < Input.touchCount; ++i)
        {
            if (Input.GetTouch(i).phase == TouchPhase.Began)
            {
                Vector2 worldPoint = Camera.main.ScreenToWorldPoint( Input.GetTouch(i).position );
                if (IsPointerOverUIObject(BonusesAndPotionsCanvas, worldPoint))
                    return;
            }
        }
    }

    private bool IsPointerOverUIObject(Canvas canvas, Vector2 screenPosition)
    {
        PointerEventData eventDataCurrentPosition = new PointerEventData(EventSystem.current);
        eventDataCurrentPosition.position = screenPosition;

        GraphicRaycaster uiRaycaster = canvas.gameObject.GetComponent<GraphicRaycaster>();
        List<RaycastResult> results = new List<RaycastResult>();
        uiRaycaster.Raycast(eventDataCurrentPosition, results);
        return results.Count > 0;
    }
}

Can anyone help me? I will be very glad for any help!


texts:
I'm trying to move my camera with the player but I'm trying to move/lerp over time, so that the camera allows the player to get a small radius from the center as it gets up to speed, and the camera will "catch up" when the player slows or stops.

I've written code that increases the movement speed of the camera the further the player gets - ideally you should only be able to go a set radius before the camera just "follows" you.

This works, except it's too jittery when the player is moving. The larger the distance, the more noticeable the jitter. I've tried different speeds but nothing seems to satisfactorily solve the issue.

Player.cs Update():

var moveHorizontal = player.GetAxis("Move Horizontal") * rigidBody.mass;
var moveVertical = player.GetAxis("Move Vertical") * rigidBody.mass;

var forceDirection = new Vector3(moveHorizontal, 0, moveVertical);

rigidBody.AddForce(forceDirection);

Camera's Follow.cs:

void Awake() {
    offset = transform.position - player.transform.position;
}

void LateUpdate() {
    var dist = Vector3.Distance(transform.position - offset, player.transform.position);

    if (dist != 0) {
        transform.position = Vector3.Lerp(
            transform.position,
            player.transform.position + offset,
            Time.deltaTime * dist * speed);
    }
}

Per the first answer, I've also tried setting my player's rigibody to "Interpolation" mode, and I update my follow script with the suggested smoothing code:

// Compute our exponential smoothing factor.
float blend = 1f - Mathf.Pow(1f - followSharpness, Time.deltaTime * 30f);

transform.position = Vector3.Lerp(
    transform.position,
    player.transform.position + offset,
    blend);

This works initially, but I get awful jitter once my player collides with an object. Plus, interpolation mode appears more susceptible to framerate drops but that's an aspect of my game I haven't worked on yet.


texts: Predicted trajectory becomes less accurate in a side-on collision

texts:
In my 2D billiards game, I have it so that when the user clicks and drags with their mouse, a Physics2D.CircleCast is projected from the cueball to wherever the mouse is. If the circle happens to hit the red ball, a line is rendered from the red ball's position to the direction of the normal of the collision. So it's supposed to predict where the red ball will go when it gets hit by the cueball.

If you look at the first gif below, you'll see that it works if the red ball gets hit at its center (or close to it). The red ball ends up moving more or less along the predicted line.

However, if you look at this second gif, you'll see that if the red ball gets hit closer to its edge, the predicted line is much less accurate.

Why is this and how can I fix it?

This is the prediction code I use:

 if (Input.GetMouseButton(0) && cueBall)
 {
        Vector2 mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
        var direction = (mousePos - (Vector2)cueBall.position).normalized;
        var hit = Physics2D.CircleCast(cueBall.position, _radius, direction, Mathf.Infinity);

        if (hit)
        {
            _lineMain.Draw(cueBall.position, hit.point);
            _ghostBall.SetPosition(hit.point - (direction * _radius));
            _lineTarget.Draw(hit.point, hit.point - hit.normal); //This is the predicted trajectory.
        }
 }


texts: Having the player face themselves after the mid-game

texts:
I am writing a game, in the vein of a jRPG, in which you begin playing as the main villain. You don't know it. You think you are playing the hero and the more successful you are and the stronger you make them the harder they will be to defeat at the very end of the game.

My main concern is anyone who puts in a significant effort early game could feel punished for it. It is also troublesome if the player finds the challenge of the final boss insurmountable because of actions from very early in the game. Is there a way I can signal early on in the second act that if they over-powered the villain it may haunt them? And there is also the possibility the twist will get out and people will just game it from the beginning. It is my intent to get some replay value out of it by having people do multiple runs based on different villain playthroughs. But is it a distraction if everyone learns the twist. Or conversely is it better if I reveal it myself in-game so everyone knows what they are working at from the start?

How do I make my potentially disengaging design hold up without turning people away?


texts:
When two audio's are played at the same time... the sound is cancelling out. How do I fix this weird phenomenon?

I have some code where there is audio on button click and audio in ten second intervals (in a background service). I have the following code to stop the button audio when the ten second interval plays, and it works fine:

public static void myPop(Context context){
    AudioManager manager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
    if(!manager.isMusicActive()) {       //Only if there isn't any other audio playing
        MediaPlayer pop = MediaPlayer.create(context, R.raw.pop);
        pop.start();
    }
    else{
        Log.v(TAG, "Audio is already playing");
    }
}

This works fine, and it stops one audio from playing (pop) to let the other audio play (the one from the background service). Now, I am getting the issue when they both play at the same time. For example, when I tap the button at the exact same time as when the audio from the background service is about to start. When they are both played at the same time, the audio just gets cut off.

Is there any way to give a preference to the background service audio? Somehow say that: If two audio pieces start at the exact same time, I want to let the background service audio to play.

To think of this visually:

I want to say that if I have the choice between apples and oranges, pick apples. AKA If I have two audio players playing at the same time, pick one (the apple).

Image source


texts: ConsumeStructuredBuffer, what am I doing wrong?

texts:
I'm trying to implement the 3rd exercise in chapter 12 of Introduction to 3D Game Programming with DirectX 11, that is:

Implement a Compute Shader to calculate the length of 64 vectors.

Previous exercises ask you to do the same with typed buffers and regular structured buffers and I had no problems with them.

For what I've read, [Consume|Append]StructuredBuffers are bound to the pipeline using UnorderedAccessViews (as long as they use the D3D11_BUFFER_UAV_FLAG_APPEND, and the buffers have both D3D11_BIND_SHADER_RESOURCE and D3D11_BIND_UNORDERED_ACCESS bind flags).

Problem is: my AppendStructuredBuffer works, since I can append data to it and retrieve it from the application to write to a results file, but the ConsumeStructuredBuffer always returns zeroed data. Data is in the buffer, since if I change the UAV to a ShaderResourceView and to a StructuredBuffer in the HLSL side it works.

I don't know what I am missing:

Should I initialize the ConsumeStructuredBuffer on the GPU, or can I do it when I create the buffer (as I amb currently doing)?.
Is it OK to bind the buffer with a UAV as described above? Do I need to bind it as a ShaderResourceView somehow?
Maybe I am missing some step?

This is the declaration of buffers in the Compute Shader:

struct Data
{
    float3 v;
};

struct Result
{
    float l;
};

ConsumeStructuredBuffer<Data> gInput;
AppendStructuredBuffer<Result> gOutput;

And here the creation of the buffer and UAV for input data:

D3D11_BUFFER_DESC inputDesc;
inputDesc.Usage = D3D11_USAGE_DEFAULT;
inputDesc.ByteWidth = sizeof(Data) * mNumElements;
inputDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_UNORDERED_ACCESS;
inputDesc.CPUAccessFlags = 0;
inputDesc.StructureByteStride = sizeof(Data);
inputDesc.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_STRUCTURED;

D3D11_SUBRESOURCE_DATA vinitData;
vinitData.pSysMem = &data[0];

HR(md3dDevice->CreateBuffer(&inputDesc, &vinitData, &mInputBuffer));

D3D11_UNORDERED_ACCESS_VIEW_DESC uavDesc;
uavDesc.Format = DXGI_FORMAT_UNKNOWN;
uavDesc.ViewDimension = D3D11_UAV_DIMENSION_BUFFER;
uavDesc.Buffer.FirstElement = 0;
uavDesc.Buffer.Flags = D3D11_BUFFER_UAV_FLAG_APPEND;
uavDesc.Buffer.NumElements = mNumElements;

md3dDevice->CreateUnorderedAccessView(mInputBuffer, &uavDesc, &mInputUAV);

Initial data is an array of Data structs, which contain a XMFLOAT3 with random data.

I bind the UAV to the shader using the Effects framework:

ID3DX11EffectUnorderedAccessViewVariable* Input = mFX->GetVariableByName("gInput")->AsUnorderedAccessView();

Input->SetUnorderedAccessView(uav); // uav is mInputUAV

Any ideas?

Thank you.


texts:
I would like to know how you would go about drawing a single pixel to a RenderTexture in Unity.

In XNA, it was just a matter of setting the graphic device's active renderTarget, and drawing to it.

In Unity, I am unable to figure out how to do this properly.  I attempted to use Graphics.DrawTexture, but that seems to be horribly slow.

I imagine there is something that can be done with GL, but I haven't been able to make it draw in side the RenderTexture properly.

Here was my attempt with DrawTexture:

    RenderTexture.active = rt;
    GL.PushMatrix();
    GL.LoadPixelMatrix(0, 128, 128, 0);

    for (int x = 0; x < 128; x++)
    {
        for (int y = 0; y < 128; y++)
        {
            Graphics.DrawTexture(new Rect(x, y, 1, 1), texture, mat);
        }
    }

    GL.PopMatrix();
    RenderTexture.active = null;


texts: Increase restitution (bounciness) of an object in a JavaScript formula

texts:
I'm going slightly around the houses on this one.  I originally started a thread over on Stack Overflow about it but then it seemed to diverge into mathematics,  with no joy from the SO community over there (https://math.stackexchange.com/questions/295485/modify-formula-for-bouncing-object-to-increase-restitution).  So my final attempt before I admit complete failure is to ask here.  I don't know if you guys do JavaScript, nor how similar this may be to any traditional gaming language, but it's worth asking.

Basically I have the following JavaScript formula representing a bouncing object with gravity, from the standard jQuery UI library: http://code.jquery.com/ui/1.10.0/jquery-ui.js (search for 'Bounce: function'). A demo here shows it in action: http://jsfiddle.net/NtkNB.

Bounce: function ( p ) {
    var pow2,
        bounce = 4;

    while ( p < ( ( pow2 = Math.pow( 2, --bounce ) ) - 1 ) / 11 ) {}
    return 1 / Math.pow( 4, 3 - bounce ) - 7.5625 * Math.pow( ( pow2 * 3 - 2 ) / 22 - p, 2 );
}

It works nicely but I need to increase the 'bounciness' of the object.  I believe this is called 'restitution'.

I've played around with the numbers but it's admittedly just trial and error (mostly error!) and just can't get it to work as desired.  I wondered if someone here might be able to understand this and could say whether it's actually possible to increase the restitution of the object within the bounds of this equation, or if not, how it could be modified such.

I totally appreciate any help anyone can give on this one as I've sunk so many hours into this without any joy whatsoever.

Many thanks.


texts: Modify a character's rotation without altering it's movement

texts:
I have a character that moves around using a virtual joystick on screen (mobile game joystick) however the player doesn't face forward to the position the joystick is pointing. Whenever I modify the rotation values on script it goes off the rails and moves erratically. What can I do to achieve this movement without altering it's translation?

Here is my script:

     void Update()
{

    horizontal = inputJoystick.horizontal();
    vertical = inputJoystick.vertical();

    moveDirection = new Vector3(horizontal, 0, vertical);
    moveDirection = transform.TransformDirection(moveDirection);
    moveDirection *= speed;

    //rotationDirection = new Vector3(horizontal, 0, vertical);
    //transform.rotation = Quaternion.LookRotation(rotationDirection, Vector3.up);
    controller.Move(moveDirection * Time.deltaTime);

}


texts: Health bar - calculating health bar's position from percentage

texts:
I'm making a simple health bar in Unity 3D. Health bar UI is made from images. I'm having a problem with setting bar's position based on health percentage.
Here's a script part:

    percentHealth = (currentHealth / maxHealth) * 100; //get's health percentage.

    HealthBarHealth.transform.localPosition = new Vector3(healthBarCurrentX, 0); //moves health bar

I want healthBarCurrentX to be calculated from these values:

percentHealth - percentage calculated from max health and current.
healthBarMaxX = 0f - health bar's position at 100% health.
healthBarMinX = -273.5f - bar's position at 0% health.

So when health is 50%, currentX is at -136.65, etc.


texts:
Hi I'm using C# and MonoGame, and have the world matrices of 2 objects. I need to get the difference between them, so I can effectively parent the second object onto the first. The aim is to get to a point where any changes to the parent transform can be applied to the child object too, by doing child.Transform = parent.Transform * offset.

I'm using the following code:

// ...

Matrix m1 = info.BoneTargets[i].Transform;
Matrix m2 = rigidbodyDefaultWorlds[transform.RigidBodyIndex];

Matrix transformFromTargetToRigidBody = Matrix.Invert(m1) * m2;
Debug.Assert((m1 * transformFromTargetToRigidBody).Equals(m2)); // FAIL

// ...

The Assert fails though, so I assume my math is wrong. I did try all other variations of the invert(a) * b formula though and none of them worked either.

For completion here are the matrix values:

M1  {M11:1 M12: 2.384186E-07 M13:-6.211763E-22 M14:0} {M21:0             M22:0             M23:1            M24:0} {M31:2.384186E-07  M32:-1            M33:0             M34:0} {M41:0.0005292654 M42:-0.03780181 M43:0.752234  M44:1}
M2  {M11:1 M12:-2.384186E-07 M13:0             M14:0} {M21:-3.884332E-14 M22:-1.629207E-07 M23:1            M24:0} {M31:-2.384186E-07 M32:-1            M33:-1.629207E-07 M34:0} {M41:0.01058531   M42:0.7560362   M43:-17.54894 M44:1}
TR  {M11:1 M12:-4.768372E-07 M13:-3.884332E-14 M14:0} {M21:4.768372E-07  M22:1             M23:1.629207E-07 M24:0} {M31:-3.884332E-14 M32:-1.629207E-07 M33:1             M34:0} {M41:0.01005606   M42:0.7938381   M43:-18.30118 M44:1}
OUT {M11:1 M12:-2.384186E-07 M13:-6.211763E-22 M14:0} {M21:-3.884332E-14 M22:-1.629207E-07 M23:1            M24:0} {M31:-2.384186E-07 M32:-1            M33:-1.629207E-07 M34:0} {M41:0.01058531   M42:0.7560362   M43:-17.54894 M44:1}

EDIT: Actually, now I'm thinking the formula is this...

child.World = childTransformWithOffsetTranslation * parentWorld


texts: Where can I obtain the latest stable aggregated builds of JOGL?

texts: I have checked many different sites including jogamp but couldn't manage to find any zipped,rared or jared collection of builds and javadocs.


texts: How do I get HDRP render enabled so that the shader graph will work

texts: I'm using Unity 2019.2.17 personal, and I imported the shader graph package and created a pbr shader graph.  I get a warning: the render pipeline is not compatible with the master node.  I assume it means I need to be using HDRP or LWDRP.  I can't figure out how to enable HDRP.  How do i do this?


texts: Rotate an object smoothly by 90 degrees on key press in unity3D

texts:
[I saw few similar question on stackexchange but none is solving the purpose.]

I want to rotate a 3D object by 90 degrees on different axis on respective inputs. For example if 'a' is pressed, the object should rotate left by 90 degrees. transform.Rotate(0,90,0); is working but it is not rotating the object smoothly.

I am new to C# and js so cannot manually code but I tried the codes given in this answer at Rotate an object smoothly on the Y axis in Unity. The below code works but it it has two problems -
code:

void Update () {
SwingOpen();
}

void SwingOpen()
{
    Quaternion newRotation = Quaternion.AngleAxis(90, Vector3.up);
    transform.rotation= Quaternion.Slerp(transform.rotation, newRotation, .05f);
}

Problem 1: The above code rotates object without any keyboard inputs.
I added the condition if (Input.GetKeyDown (KeyCode.RightArrow)) but now the object rotates partially on every keyboard input. I want to rotate it by 90 degrees on a single key press.

Problem 2: It will never actually rotate the object by 90 deg. It will always be tending towards 90 deg. I want exact 90 deg rotation to allow multiple 90 deg rotations for 'n' number if inputs.

How can I solve this? Please help. Please let me know if the question isn't clear enough.

[EDIT]

I applied the below script but it is giving me some totally unexpected output

Code:

public float speed = 1;
private int xtimesHit = 0;
private int ytimesHit = 0;
private int ztimesHit = 0;

void Update () {
    if( Input.GetKeyDown( KeyCode.RightArrow ) ){
        ztimesHit--;
    }
    if( Input.GetKeyDown( KeyCode.LeftArrow ) ){
        ztimesHit++;
    }

    if( Input.GetKeyDown( "a" ) ){
        ytimesHit++;
    }
    if( Input.GetKeyDown( "d" ) ){
        ytimesHit--;
    }

    if( Input.GetKeyDown( "w" ) ){
        xtimesHit++;
    }
    if( Input.GetKeyDown( "s") ){
        xtimesHit--;
    }

    this.transform.rotation = Quaternion.Lerp(this.transform.rotation, Quaternion.Euler(xtimesHit*90,ytimesHit*90,ztimesHit*90), Time.deltaTime*speed);

}

On running this script
If I press rightarrow once followed by 's' the object rotates on 'z' axis and 'x' axis  correctly but there after if I press arrowkeys or 'a/s' in both the cases the object rotates on y axis. I dont understand why this is happening.

I want it to rotate w.r.t. the world axis always.


texts: How to orbit an object at certain speed in Unity?

texts:
I want to move an object around a circle. So I have this code below:

    static public int theta = 0;

void Update(){

    Vector3 position = this.transform.position;

    position.x = 0 + 50 * Mathf.Cos (theta) * Time.deltaTime;
    position.y = 0 + 50 * Mathf.Sin (theta) * Time.deltaTime;
    this.transform.position = position;
    theta += 1;
}

The object orbits, but it orbits so fast!!! I want the object to rotate like 1 orbit per second only.  How to do that?

ANSWER TO THIS PROBLEM, THANKS!

static public int theta = 0;

void Update(){

    Vector3 position = this.transform.position;

    position.x = 0 + 50 * Mathf.Cos (theta) * Time.deltaTime;
    position.y = 0 + 50 * Mathf.Sin (theta) * Time.deltaTime;
    this.transform.position = position;
    theta += 1 * Time.deltaTime;
}


texts: MMORPG design question: Storing a tile map on the client computer, security concerns

texts:
in my game the client logs in and receives a map made of tiles (they differ in height and terrain type) from the server. I'm storing these tiles in a SQLite database on the client. The next time the client logs in, it communicates to the server that it already has the map. This saves network load and cpu on the server and decreases loading time.

Now I wonder if I'm doing the right thing. Because it would be very easy for the player to modify the tiles in his local SQLite database, turn a mountain into flat land client-side and walk right through it.

I will of course implement a system on the server that picks one or a few players at a time and checks if their reported positions are valid (as in, they aren't hacking), but I can't constantly run these checks on everyone for performance reasons.

This brings up the following questions:

Can I encrypt the SQLite database locally?
Would I hide the key in the code?
Is that safe? Could the client find the key?
Can the map be altered on the client even if I don't store it in a database?

Thanks everyone


texts:
I'm really trying to understand this from a mathematical viewpoint. After all, numbers are numbers, the chirality or handedness depends on how one interprets it.

Say I've three basis vectors x (1, 0, 0), y (0, 1, 0) and z (0, 0, 1). The same basis vectors would be seen differently by the two systems but the numbers remain the same.

When we do a cross product of x and y we'd get z in both systems, again the numbers of the result are the same, it's just the interpretation of the observer.

Then why do I see questions about handedness all the time? Is there a place where a game developer needs to differentiate and work in converting between the two really? Eric Haines in a related article uses the term "right-handed data". What does this really mean, aren't they all numbers? Why would they force a coordinate system on the user? Also do APIs like GL or DX force a system at some point? I've read somewhere that, in OpenGL the camera is always at origin looking at -Z direction, while it's the opposite in DirectX.

It'd be great if someone can list out where this convention really makes a difference and why.

EDIT: I think can explain it more explicitly since many seem to misunderstand the question (sorry, I'm not a native speaker of this tongue). Why do people talk about converting an asset for handedness? Say a triangle with coords (0, 0, 0), (0, 1, 0) and (1, 0, 0) would mean the same in both systems mathematically, where is the handedness here?


texts: Eclipse/LibGDXgame doesn't load textures

texts: Our LibGDX project doesn't load textures after building on PC/Android but when it's built from Eclipse using  Ctrl + F11 (Run/Debug) everything is fine. What could be causing that?


texts: How to get smooth circular input from a thumbstick in XNA?

texts:
I have a mouse-based game that I'm trying to get to work nicely with the Xbox gamepad.  My major issue is trying to get the cursor to move smoothly like it does with the mouse.  Using GamePadDeadZone.IndependentAxes makes it hard to move at slight angles, so I switched to GamePadDeadZone.Circular.

It turns out that the values that I'm getting from the controller are diamond shaped instead of being circular.  Pushing all the way up gives me (0,1), and pushing right gives me (1,0), but pushing to the top-right gives me (.7,.7).

This leads to a quite noticeable slowdown when traveling at angles.  My game requires the player to move carefully at times and quickly at others, but it's near impossible because you'll move faster or slower depending on the angle of the thumbstick.  How can I get truly circular data back?


texts: How do I avoid users hacking my network games from the client side?

texts:
I've decided to make an online game; the server sends packets of information to the client application, which is going to simulate what it gets from the server. The client makes a part of the design of the game, and sends the new state back to the server for processing.

The clients can send fake information to the server, and inform the server that I've done the task successfully, without trying. Assume a Counter-Strike game; the client may send a fake packet to the server and tell the server that I've defeated someone. How can I avoid this violation?


texts: What happened to the Journal of Game Development?

texts:
The lengthy mission statement from its website states:

  The lack of game-specific research has prevented many in the academic community from embracing game development as a serious field of study. The Journal of Game Development (JOGD), however, provides a much-needed, peer-reviewed, medium of communication and the raison d'etre for serious academic research focused solely on game-related issues. The JOGD provides the vehicle for disseminating research and findings indigenous to the game development industry. It is an outlet for peer-reviewed research that will help validate the work and garner acceptance for the study of game development by the academic community.  JOGD will serve both the game development industry and academic community by presenting leading-edge, original research, and theoretical underpinnings that detail the most recent findings in related academic disciplines, hardware, software, and technology that will directly affect the way games are conceived, developed, produced, and delivered.

The Journal of Game Development was established in 2003. It's hard to find any information about the issues but at four issues per year, I estimate the last issue was distributed sometime in 2005 or 2006. It had a good editorial board of college professors and a founding editor from Ubisoft. The list of articles looks good. The price was reasonable.

So what happened to it? Its website recently went down but you can see the last Archive.org version.

The editor-in-chief is a professor at my school so I intend to ask him in person in a week or two, but I thought I'd see what you might be able to dig up about it first. Of course I will be sure to add an answer with his official word on the matter at that time.


texts: What is the definition of framerate-independent motion and why is important to have it in games?


texts: How to draw unity gizmos with new input system?

texts:
I am using the new Unity Input system for my game.
When I press a key, for example "Q", I want gizmos to be drawn.
However, I can't subscribe to a keypress event with a Gizmo drawing function, because it says it needs to be inside of OnDrawGizmos(). Furthermore, I can't subscribe with that function because it says it doesn't take any parameters, and I need to pass InputAction.CallbackContext context as a parameter, for it to be considered okay by the event system.
Here's the code for how I did it before:
public void OnDrawGizmos()
{
    if (Input.GetKey(KeyCode.Q))
    {
        DrawStuff();
    }
}

How can I recreate this?


texts: How can I find the tangent and normal at an interpolated point on a Catmull-Rom/Hermite spline?

texts:
I have an implementation of a simple Catmull-Rom spline. It works, but I'm trying my hardest to be able to place vertices at extrusions along the curve. For this I need the normal (and tangent in the process) to be able to find the correct locations off of the curve. I cannot find any information anywhere, at least nothing that I can understand, on how to quickly calculate the tangent for a given t value on the curve. I've tried to do the derivative myself but I quickly realized I had no idea what I was doing.

How can I find the derivative/tangent/normal for a point at a t value on a Catmull-Rom spline?

Just to be extra clear, here is an incredibly rough picture of what I need.

I need to sample a point at a location along the curve and find an orthogonal vector, represented here by the blue lines. At the end of the blue lines I will place vertices. I have a working implementation of this already but it is for a bezier curve.


texts: Streamline Facebook and Google Play Game Services integration in Android Game

texts:
This has been confusing me a lot .

I am creating a simple 2D platformer which I wish to make social. So I thought of letting users do the following:

Share their in game objective completion/ their high score etc with their friends.
Challenge their friends to have a better score / better multiplier etc from their's
View leaderboards of high score , most distance traveled etc both social and global.

So My First preference was Facebook , simply because people have better social connections there.

But then Google Play game services integration has another advantage, It makes you game available in their game services app and may be boost your game ranking in play store if you have game services integrated. But then I'' need to have leaderboards(same ones) for google plus as well. That 'll be too confusing for people.

I do not want people to sign in twice in my app. That'll simple cut down and disperse the number of people getting social with the game.

I personally want to use facebook alone but then google game services may be boosts my app in store.

Can someone tell me a solution to use them both frictionlessly and get the most out of them in my game