texts: How do I make the player invulnerable using Fabric modding?

texts:
I am making a Minecraft mod using the fabric mod loader and I want to make the player invulnerable for a duration when they eat a certain food item.
I don't know how to manipulate anything concerning entities or players so I am asking for some guidance.


texts: Aim prediction along a parabola - How to make a Tower Defence Mortar aim accurately

texts:
I am building a very basic tower defence game in Unity3D where one tower is your standard long range mortar/artillery.

I want the projectile it fires to follow a parabola curve to make its movement seem like a mortar. This movement is not dependant on any physics (as I can make a projectile follow a curve  but I could implement the Unity3D physics if the method used would benefit from it.

My question is: What technique should I use to ensure the projectile hits the locked unit whilst taking into account that the unit is moving along a possibly non linear path (defined with my A* implementation.) I have not implemented any code as of yet as I wanted to consult the masses for any wisdom you can provide!

My initial idea was to fix the time the projectile would take along its parabola curve (regardless of distance) and try and track the position the unit would be at after this time delay. Is this along the right lines or are there alternative methods to consider when aiming a projectile that follows a curved path instead of a linear one?

Thank you for your time.


texts: How to calculate gravity vector based on device rotation?

texts:
I have basic scene where the cube sits on platform

What I want is if the device is rotated 90 degrees to the left, cube should fall down as shown below

I came up with a solution to tackle that by modifying the Physics2D.Gravity vector so it should be like following

Device rotation 0, vector(0, -9.81).
Device rotation -90, vector(-9.81, 0).
Device rotation 180, vector(0, 9.81).
And so on (Rotation would be anything between 0 to 360 degrees).

I don't know how to calculate that vector based on rotation degree.
Any suggestion is much appreciated.
Thanks


texts: How do I take Direct3D9 full screen using SlimDX?

texts:
I'm writing a Direct3D9 application wrapped by SlimDX. I'm trying to take my application full screen but I am having problems. I can reset the device so that it covers the entire screen, however, it seems as though the device window loses focus. The cursor belongs to that of the window beneath my device window. When I click on the screen(while in full screen mode) the window beneath my device window gets focus. This shouldn't happen.

In my c# code for managing the device I have converted DXUT(from the DirectX SDK) to c#...There is a lot of code to cover but I was hoping for a theoretical answer.

What is happening to the device as I take the app full screen? Why does the window beneath the device window get focus while the device window continues to render and cover the screen?

Could my problem have anything to do with the fact that Windows Forms draws with GDI? I found a post here that describes a problem that differs in result but may be along the same lines wrt cause.


texts: How to achieve a hard edge at this geometrical intersection?

texts: Im trying to make this edge appear smooth, soo that the faces on each side seem to meet up smoothly. But I want the green edges around this to be hard and sharp. I am using 3ds max, and this is the result.


texts: How can I prevent picking up health items when I'm already at max health?

texts:
This is what I have so far..

public class Per10HealthCollect :MonoBehavior

    void OnTriggerEnter(Collider other)
    {
        if (GlobalHealth.healthValue >= 91)
        {
            GlobalHealth.healthValue = 100;
        }
        else
        {
            GlobalHealth.healthValue += 10;
        }
        GetComponent< CapsuleCollider>().Enabled = false;
        this.gameObject.SetActive(false);
    }
}


texts: I am trying to write a big text using BitmapFont in libGDX . But it shows on one line and the user can see only the first part of the text . How can I make that bitmapFont made new line automatically and show whole text on the screen ?


texts: Why does my first person camera attached to a rigid body vibrates?

texts:
I'm trying to make a first-person character with a rigid body. I need a rigid body because I want to add areas where the gravity comes from different directions so I also need to rotate the character accordingly. And as far as I know you cant rotate a character controller.

So I wrote a script for movement and camera rotation.

The problem I now face is that the camera vibrates. I recorded this video to show it.

Why do I get this and how do I fix this?

Movement code:

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

public class PlayerMovementRigidBody : MonoBehaviour
{
    public float speed = 10.0f;
    public Rigidbody rb;
    public LayerMask groundLayers;

    public float jumpForce = 7;
    public CapsuleCollider col;

    float transelation;
    float straffe;

    // Start is called before the first frame update
    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        rb = this.GetComponent<Rigidbody>();
        col = GetComponent<CapsuleCollider>();
    }

    // Update is called once per frame
    void Update()
    {
        transelation = Input.GetAxis("Vertical") * speed;
        straffe = Input.GetAxis("Horizontal") * speed;
        bool jumping = Input.GetKeyDown(KeyCode.Space);

        transelation *= Time.smoothDeltaTime;
        straffe *= Time.smoothDeltaTime;

        /*if (IsGrounded())
        {
            rb.useGravity = false;
        }
        else
        {
            rb.useGravity = true;
        }*/

        if (IsGrounded() && Input.GetKeyDown(KeyCode.Space))
        {
            rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
        }

        if (Input.GetKeyDown("escape"))
        {
            Cursor.lockState = CursorLockMode.None;
        }

    }

    void FixedUpdate()
    {
        transform.Translate(straffe, 0, transelation);
    }

    private bool IsGrounded()
    {
        return Physics.CheckCapsule(col.bounds.center, new Vector3(col.bounds.center.x, col.bounds.min.y, col.bounds.center.z), col.radius * .9f, groundLayers);
    }
}

Mouse look code:

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

public class MouseLookRigidBody : MonoBehaviour
{
    public float mouseSensitivity = 100f;

    public Transform playerBody;

    Rigidbody rig;

    float xRotation = 0f;

    // Start is called before the first frame update
    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        rig = this.transform.parent.gameObject.GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    public void Update()
    {
        float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;

        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);

        transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
        playerBody.Rotate(Vector3.up * mouseX);

    }
}


texts: Testing HTML5 canvas games on low resource computers

texts:
I've made a game in HTML5 & JS and want to test it on varying types of user setups as I've heard it doesn't perform too well on older MacBooks.

How can I accomplish this? I'm thinking of something like browserstack.com but for GPU, CPU and memory testing.


texts: LibGDX: How to make an object falls with random speed

texts:
I'm trying to make an object (ball) fall into position Y and when the ball collides with the base. The sprite changes and along with the change I want the speed of the fall to change according to the sprite

public void create () {
    circleBall = new Circle();
    rectangleBase = new Rectangle();
    ball = new Texture("ball.png");
}

public void render () {
    spriteBatch.begin();
    fallBall();
    rand();
    spriteBatch.end();
}

void fallBall(){
    fallSpeed++;
    if(posYBall > 0){
        posYBall -= fallSpeed * 2 / 2;
    }
}

void rand(){
    int rand1 = random.nextInt(15 - 1) + 1;
    int rand2 = random.nextInt(10 - 1) + 1;
    int rand3 = random.nextInt((55 - 35) + 1) + 35;
    collisionBallBase(rand1, rand2, rand3);
}

void collisionBallBase(int rand1, int rand2, int rand3){
    if(Intersector.overlaps(circleBall, rectangleBase)){
        if(rand1 <= 5){
            ball = new Texture("ball.png");
        }else if(rand1 <= 10){
            ball = new Texture("ballb.png");
        }else{
            ball = new Texture("ballc.png");
        }

        if(rand2 >= 5){
            ballDirection = 4;
        }else{
            ballDirection = -4;
        }
        fallSpeed = -rand3;
    }
}


texts:
I am using Unity 2D for the past 2 weeks and when it came for changing rooms i got disappointed. Its not like ex. Gamemaker where you press a button and the room becomes persistent. I have though a way of making the scenes persistent and thats:

*Save all the variables that make the scene as it is(positions, etc.)

*Change scene.

*Move back to the same scene.

*Apply the saved data.

So, will this work? If it doesnt work or if its not good, what is the easiest way of doing that?

Thanks in advance


texts: Moving and rotating to a position with forces and impulses

texts:
Carrying on from this question, I'm still stuck trying to implement the behaviour mentioned in this tutorial. My movement has improved slightly thanks to the help I received:

But the character still does this weird loop after reaching one of the waypoints.

AiSystem::steerToNextNode() is the relevant function that I'm having the problem with. It's the one doing the rotation with impulses:

//a few possibly non-obvious things:
//angle = npcBody->body()->GetAngle()
//angularVelocity = npcBody->body()->GetAngularVelocity()
//inertia = npcBody->body()->GetInertia()
//pos = npcBody->getWorldCenter()
//targetPos = nextNode->pos()

#define DEGTORAD 0.0174532925199432957f
#define RADTODEG 57.295779513082320876f

void AiSystem::steerToNextNode(ComponentEntity *npc, QSharedPointer<Action> action) const
{
    Path *path = action->path();
    Q_ASSERT(!path->isEmpty());

    QSharedPointer<PhysicsComponent> npcPhysics = npc->component<PhysicsComponent>();
    Box2dBody *npcBody = npcPhysics->body();
    QSharedPointer<PathNode> nextNode = path->front();

    if (!isNextToTargetPos(npc, nextNode->pos())) {
        // We're not close enough to the next node (waypoint); keep going.
        // The following code is based off this tutorial: http://www.iforce2d.net/b2dtut/rotate-to-angle
        float desiredAngle = MathUtils::cartesianDirectionTo(npcBody->getWorldCenter(), nextNode->pos());
        desiredAngle = qDegreesToRadians(desiredAngle);

        // Take the current angular velocity into aaccount, as it affects future time steps.
        float frequency = 60.0; //Hz
        float nextAngle = npcBody->body()->GetAngle() + npcBody->body()->GetAngularVelocity() / frequency ;
        float totalRotation = desiredAngle - nextAngle;

        while ( totalRotation < -180 * DEGTORAD ) totalRotation += 360 * DEGTORAD;
        while ( totalRotation >  180 * DEGTORAD ) totalRotation -= 360 * DEGTORAD;
        float desiredAngularVelocity = totalRotation * frequency;
        // Allow 10 degrees of rotation per time step, to achieve a gradual turn.
        float change = 10 * DEGTORAD;
        desiredAngularVelocity = qMin(change, qMax(-change, desiredAngularVelocity));
        float impulse = npcBody->getInertia() * desiredAngularVelocity;
        npcBody->applyAngularImpulse(impulse);

        // This applies a force in the direction of the current angle (npcBody->body()->GetAngle()).
        PhysicsSystem::moveForward(npcPhysics);
    }
    // unrelated stuff...
}

I've also included functions that it uses in case I'm doing something wrong there:

float MathUtils::cartesianDirectionTo(const QPointF &source, const QPointF &target) {
    QPointF toTarget(target.x() - source.x(), target.y() - source.y());
    float facingTarget = MathUtils::clampAngle(qRadiansToDegrees(atan2(toTarget.y() * -1, toTarget.x())));
    return facingTarget;
}

static float32 stupidForce(float32 mass)
{
    return mass * 15.0f;
}

void PhysicsSystem::moveForward(QSharedPointer<PhysicsComponent> physicsComponent)
{
    float32 force = stupidForce(physicsComponent->body()->getMass());
    float rotation = physicsComponent->body()->rotation();
    QPointF directionVector = MathUtils::directionVector(qDegreesToRadians(rotation));
    physicsComponent->body()->applyForce(directionVector * force, physicsComponent->body()->position());
}

bool AiSystem::isNextToTargetPos(ComponentEntity *npc, const QPointF &targetPos) const
{
    const Box2dBody *npcBody = npc->component<PhysicsComponent>()->body();
    return MathUtils::fuzzyCompare(npcBody->getWorldCenter(), targetPos, mPathFinder.targetLeniency());
}

Can anyone spot any mistakes?


texts: In Unity , How to clear instantiated object when I call the function?

texts:
Here is a function I call out am UI element:

public void LoadCurrentItem(ItemType t)
{
    List<Item> itemList = SessionManager.singleton.GetItemAsList(t);

    if (itemList == null)
        return;
    if (itemList.Count == 0)
        return;
    GameObject prefab = (t == ItemType.consumable) ? eq_left.inventory.slotTemplateUD : eq_left.inventory.slotTemplateLR;
    Transform p = eq_left.inventory.slotGrid;

    int dif = iconSlotCreated.Count - itemList.Count;
    int extra = (dif > 0)?dif: 0;

    for (int i = 0; i < itemList.Count + extra; i++)
    {
        if (i > itemList.Count -1)
        {
            iconSlotCreated[i].gameObject.SetActive(false);
            continue;
        }

        IconBase icon = null;
        if(iconSlotCreated.Count -1 < i)
        {
            GameObject g = Instantiate(prefab) as GameObject;
            g.SetActive(true);
            g.transform.SetParent(p);
            icon = g.GetComponent<IconBase>();
            iconSlotCreated.Add(icon);
        }
        else
        {
            icon = iconSlotCreated[i];
        }

        icon.gameObject.SetActive(true);
        icon.icon.enabled = true;
        icon.icon.sprite = itemList[i].icon;
        icon.id = itemList[i].item_id;
    }

}

It might seem less informative, but my question is simple and stupid:
I want to destroy my GameObject g that instantiates prefab before it instantiates prefab so that I can refresh GameObject g to create eq_left.inventory.slotTemplateUD or eq_left.inventory.slotTemplateLR

How can I achieve this goal?


texts: Isometric displaying two different images in different positions

texts:
I'm creating a simple Isometric game using HTML5 and Javascript, but I can't seem to get the display to work, at the moment i have 9 tiles that have X and Y positions and the player has a X and Y position, the players X and Y properties are set to 100, and the tiles are as shown

tiles[0] = new Array(3);
tiles[1] = new Array(3);
tiles[2] = new Array(3);
tiles[0][0] = new point2D( 100, 100);
tiles[0][1] = new point2D( 160, 100);
tiles[0][2] = new point2D( 220, 100);
tiles[1][0] = new point2D( 100, 160);
tiles[1][1] = new point2D( 160, 160);
tiles[1][2] = new point2D( 220, 160);
tiles[2][0] = new point2D( 100, 220);
tiles[2][1] = new point2D( 160, 220);
tiles[2][2] = new point2D( 220, 220);

Now I use this method to work out the isometric position

function twoDToIso( point )
{
var cords = point2D;
cords.x = point.x - point.y;
cords.y = (point.x + point.y) / 2;
return cords;
}
point2D is

function point2D( x, y)
{
this.x = x;
this.y = y;
}

Now this i'm sure does work out the correct positioning, but here is the output Isometric view

I just need to move my player position a tiny bit, but is that the best way to display my player position in the right position?

Canvas

P.S. the tile width is 120 and height is 60 and the player is width 30 by height 15


texts: Can't find Model Substance Painter - Lost in the Void

texts: I must have zoomed out too far, turned the camera in the wrong direction, whatever. The model is lost, I cannot find it in the 3D View. This is a complex project and I don't want to start over. I have tried orthographic view and all known keyboard shortcuts. But I am still lost in the void and I can't find my 3D Model. I'm about to plant a bomb at Substance Painter HQ or at least give them a phone call wishing death on them all.


texts: What would be a good Facebook credits price point for a puzzle game on Facebook?

texts: I have a successful puzzle game and I'm thinking about doing a new version and bringing that new version to FB, and selling it using FB credits. Does anyone have ideas on what the FB credits price point should be? I have some idea, and obviously I know what some of the virtual goods price points are, but I'm curious what peoples views would be on a price point for an entire game, and if the availability of free facebook credits could hurt sells etc.


texts: GameObject that should have a fixed speed keeps accelerating

texts:
I'm using a coroutine to make a GameObject move from a random point A to a random point B. The GameObject should move along this trajectory at fixed intervals and at a constant speed.

However, each time my coroutine that executes the movement is called, the GameObject is a little bit faster.

private IEnumerator movement () {

        // Initialize position and rotation
        float distanceX = endTransform.position.x - startTransform.position.x;
        float distanceZ = endTransform.position.z - startTransform.position.z;
        float angleAroundY = 90.0f - Mathf.Rad2Deg*(Mathf.Atan2 (distanceZ, distanceX));

        this.gameObject.transform.position = startTransform.position;
        this.gameObject.transform.rotation = startTransform.rotation * Quaternion.Euler (90.0f, angleAroundY, 0.0f);

        // Move from point A to point B
        while (this.gameObject.transform != endTransform.transform) {
            float step = speed * Time.fixedDeltaTime;
            this.gameObject.transform.position = Vector3.MoveTowards (this.gameObject.transform.position, endTransform.transform.position, step);
            yield return null;
        }
        yield return null;
    }

I checked and the step variable is constant.


texts: How to deal with OpenGL and Fullscreen on OS X

texts:
I do most of my development on OS X and for my current game project this is my target environment. However when I play games I play on Windows. As a windows gamer I am used to Alt+Tab switching from within the game to the last application that was open.

On OS X I currently can't find either a game that supports that nor can I find a way to make it possible.  My current project is based on SDL 1.3 and I can see that cmd+tab is a sequence that is sent directly to my application and not intercepted by the operating system.

Now my first attempt was to hide the rendering window on cmd+tab which certainly works, but has the disadvantage that a hidden OpenGL window in SDL cannot be restored when the user tabs back to the application.  First of all, there is no event fired for that or I can't find it, secondly the core problem is that when that application window is hidden, my game is still the active application, just that the window disappeared.

That is incredible annoying.

Any ideas how to approximate the windows / linux behavior for alt+tab?


texts:
I'm an experienced developer but recently I've been wanting to get into game programming but as you know game development is an entirely different beast from most other forms of programming (perhaps only bested by operating system development).

That being said I've been reading Game Coding Complete (ISBN 978-1-58450-680-5) by Mike McShaffry.

Originally I was going to try developing with a component model with the assortment of usual components (e.g. SpacialComponent, VisualComponent, EntityLogicComponent, etc..) however Mr. McShaffry recommends using the MVC model which looks very attractive but I'm not sure how I can make it work with the component model if at all possible, but, without components, the MVC model looks sort of the evil monolithic inheritance monster and not very flexible, which I'm not really interested in.

I'm really confused about where to go from this point.

Do you more experienced game coding voodoo experts have any thoughts or recommendations?

Thank you so much!


texts: Does libgdx implement the game loop for you?

texts:
Initially, I assumed that the developer has to implement the game loop because libgdx is a library - not an engine. But then I found out that Graphics has getDeltaTime() and getRawDeltaTime() so I assume that the game loop is already implemented.

If it is implemented, could someone explain what method libgdx uses? I'm mainly referring to this article. My guess is that it uses a semi-fixed time step? If that's the case, then why might getDeltaTime() "be smoothed over n frames?" How exactly is getDeltaTime() smoothed?

If the game loop is not implemented, what is the purpose of getDeltaTime() when you have getRawDeltaTime()?


texts: Combat System - Class Objects as Package and Listener

texts:
So I've been trying to map out a combat system and I have an idea I'm laying out that I'm looking for a sanity check on, as well as suggestions.

The idea is that all things that can do damage (weapons, spells, environmental traps, monsters that deal damage sans weapon) will have a CombatTalker() object attached that will contain information about the amount of damage and damage types (fire, frost, physical, magical, etc.), modifiers that it might have, and any special effects (apply DoT, blind, slow, etc.).

Everything that can take damage will have a CombatListener() object that takes that information and transmogrifies it with the receivers resistances and any special properties it may have.

The CombatTalker() will create a CombatPackage() from a collection class any time there is a collision, and send it to the CombatListener() on the collided objects, supposing it has one.  The CombatPackage() is basically the raw data about the damage and effects.  The CombatTalker() is a wrapper of sorts that generates the CombatPackage() based on the weapon (or whatever) base damage, then the specific details of that individual weapon, and sends it (like a network packet) to the CombatListener().  The CombatListener() unwraps the package, and in reverse applies the resistances then applies any relevant damage and effects.

I know some of that was slightly repetitive, but I was trying to outline the idea completely, which apparently took two paragraphs.

I know this might be slightly complex, but the creatures and players and weapons and spells can change over time, so there isn't just a pool of static data that can be attached to the item.  It needs to be able to read stats from JSON, apply specific information about the damage and send it.  The same goes on the other side in reverse.

Is there a reason that this is "too complex"?  Am I considerably overthinking it, or is this a reasonable method for a combat system?

Thanks!


texts: Diagonal discontinuity in perlin noise terrain

texts:
I'm using Bilinear filtering to interpolate perlin-noise based height data. However, when I render the resulting plane mesh, there is this obvious diagonal discontinuity in the generated terrain.

See Edit below. I'm guessing it could either be an error in how I'm interpolating the data, or in how I am assigning the heights back to the plane vertices. But I haven't been able to fix it. Anybody has seen this type of error? What could it be?
I'm using the bilinear algorithm technique found here. My vertices step laid bottom up, left to right (I.e. vertex 0 is at the bottom left).
Edit: I have tried using a heightmap texture instead of noise generated data and I think the problem lies in how I am flattening the 2D texture data into a 1D array. If I use the overload in those methods that explicitly uses a float[,] array it works with a real texture. If I convert the same texture to a 1D array I see the diagonal discontinuity.
This is the code I'm using to flatten the data
    public static float[] ConvertToXYflat(Color[] data, int res)
    {
        float[] converted = new float[data.Length];
        int idx = 0;
        for (int i = 0; i < res; i++)
        {
            for (int j = 0; j < res; j++)
            {
                converted[idx++] = data[(i * res) + j].r;
            }
        }
        return converted;
    }

The unity docs say that the texture pixels are laid row by row, left to right, bottom to top. That is also the pattern that my vertices have.
This is how the array of heights is constructed.
        // world size dimensions of the plane mesh
        Vector2 dimensions = new Vector2(terrainMesh.Width, terrainMesh.Height);
        int resolution = 1023;
        for (int i = 0; i < positions.Length; i++)
        {
            newHeights[i] = TerrainFilters.TerrainBilinear(nativeHM, positions[i].x, positions[i].z, MaxHeight, -dimensions/2, dimensions, resolution-1);
        }

Filtering method:
public static float TerrainBilinear(NativeArray<float> heightMap, float worldX, float worldZ, float height, Vector2 worldSize, Vector2 dimensions, int resolution)
    {
        float x = ((worldZ - worldSize.y) * resolution) / dimensions.x;
        float z = ((worldX - worldSize.x) * resolution) / dimensions.y;

        int fx = (int)math.floor(x);
        int cx = fx + 1;
        int fz = (int)math.floor(z);
        int cz = fz + 1;

        int res = resolution + 1;

        float hx0z0 = heightMap[fx * res + fz] * height;
        float hx1z0 = heightMap[cx * res + fz] * height;
        float hx0z1 = heightMap[fx * res + cz] * height;
        float hx1z1 = heightMap[cx * res + cz] * height;

        return hx0z0 + (hx1z0 - hx0z0) * (x - (int)x) + (hx0z1 - hx0z0) * (z - (int)z) + (hx0z0 - hx1z0 - hx0z1 + hx1z1) * (x - (int)x) * (z - (int)z);
    }

Then I iterate a second time and add those heights to the original plane vertices like so:
    public void UpdateHeights(float[] heights)
    {
        Vector3[] newVertices = new Vector3[vertices.Length];
        Array.Copy(vertices, newVertices, vertices.Length);

        for (int i = 0; i < heights.Length; i++)
        {
            newVertices[i].y += heights[i];
        }
        mesh.SetVertices(newVertices);
        mesh.RecalculateNormals();
    }

Clearly not the most efficient way, but I need to get the basics working correctly before improving it.


texts: How do I continue a smooth stroke around a corner in zBrush?

texts:
I have been trying to create a series of smooth lines down the outside of a bell shape, around the lip, and then back up the inside. The problem is that I can't seem to accomplish this in a single brush stroke, and every time I've tried to join up multiple strokes, the join always looks really obvious.

Is there any way to "pause" a stroke so that you can rotate your view, and then resume it smoothly? Or is there any other way in general to go about something like this?


texts:
I have reviewed the relevant WinForms/XNA samples here and here.

However, my requirements are slightly different.

Given the following:

I am developing a multiplayer (Client - Server) game
There will be three projects in the solution, one for Client and Server respectively, plus an additional one containing the core game/engine
The instances will share common code from this engine project (core Game Engine functionality)
I require the Server instance to also allow management of the server (e.g. connection list etc.) via a Windows Form
Finally, and importantly, I am proposing to use the Dependency Injection pattern on initialisation of the client/server instances to inject the relevant network management class as required - similar to the approach here

What is the best way to achieve this? Specifically, are there any flaws with organising the projects in the solution the way I have proposed above? For the Server project, do I start it as an XNA project and then call the Winform, or vice versa?

Thank you for any advice you can spare.

Edit - a brief example of the "dependency injection" style pattern I plan to use. Forgive me if this is not an example of "pure" / full / traditional DI!

// Create the server
using (var game = new ExampleGame(new ServerNetworkManager()))
{
    game.Run();
}

// Create the client
using (var game = new ExampleGame(new ClientNetworkManager()))
{
    game.Run();
}


texts: Displaying a grid based map using C++ and sdl

texts:
I am trying to create a roguelike game using c++ and SDL. However, I am having trouble getting it to display the map, which is represented by a 2d array of a tile class.

Currently, my code is this:

for (int y = 0; y!=MAPHEIGHT; y++)
{
    for (int x = 0; x!=MAPWIDTH 1; x++)
    {
        apply_surface( x * TILEWIDTH, y * TILEHEIGHT, mymap[x][y].image, screen );
    }
}

However, running this code causes it to both dither for a while before opening the SDL window, and (usually) tell me there is an access violation.
How can I display my map?


texts: What are these rendering artifacts and how can I fix them?

texts:
Here is the artifact:

Here is some clarifying information:

This appears only at 480 units from the origin, and seems to get worse (to a point) as I move away.
All water should have sand rendered behind it, but the sand should be occluded (since I will eventually be rendering the water semi-transparently).

Here is my guess:

This looks like z-fighting, but my issue with this hypothesis is that none of these polygons are co-planar.


texts: Is it possible to get match information, for instance, the score, from valve servers (eg. Dota2/CS:GO)

texts:
I've been searching for information but couldn't find any. I don't even know if this is the appropiate place to ask. If it's not, please delete the question and forget me.

I'd like to know if there is an API or something that lets me petition a server where a match is being played, and retrieve the current score or some other information regarding that match.

I am interested in Counter Strike: Global Offensive matches, for instance.

Thanks.


texts: How to pause and resume a game in XNA using the same key?

texts:
I'm attempting to implement a really simple game state system, this is my first game - trying to make a Tetris clone.  I'd consider myself a novice programmer at best. I've been testing it out by drawing different textures to the screen depending on the current state.

The 'Not Playing' state seems to work fine, I press Space and it changes to 'Playing', but when I press 'P' to pause or resume the game nothing happens. I tried checking current and previous keyboard states thinking it was happening to fast for me to see, but again nothing seemed to happen. If I change either the pause or resume, so they're both different, it works as intended.

I'm clearly missing something obvious, or completely lacking some know-how in regards to how update and/or the keyboard states work.

Here's what I have in my Update method at the moment:

    protected override void Update(GameTime gameTime)
    {
        KeyboardState CurrentKeyboardState = Keyboard.GetState();

        // Allows the game to exit
        if (CurrentKeyboardState.IsKeyDown(Keys.Escape))
            this.Exit();

        // TODO: Add your update logic here

        if (CurrentGameState == GameStates.NotPlaying)
        {
            if (CurrentKeyboardState.IsKeyDown(Keys.Space))
                CurrentGameState = GameStates.Playing;
        }

        if (CurrentGameState == GameStates.Playing)
        {
            if (CurrentKeyboardState.IsKeyDown(Keys.P))
                CurrentGameState = GameStates.Paused;
        }

        if (CurrentGameState == GameStates.Paused)
        {
            if (CurrentKeyboardState.IsKeyDown(Keys.P))
                CurrentGameState = GameStates.Playing;
        }

        base.Update(gameTime);
    }


texts: How'd they do it: TF2 payload cart glow?

texts: How did the creators of TF2 make the glow on the payload cart visible through walls? Is it possible to implement this in Unity's shaderlab?


texts: Is it OK to reuse art from open-source games?

texts:
There are a lot of open source games, such as Flare (Diablo clone).

Is it OK to re-use the art they put in their open source game and make a profit?


texts: How can I apply UV mapping in parent space?

texts:
I'm trying to apply UV mapping in parent space - ie. taking into account the object's own transformation matrix but no matrices further up the transformation hierarchy.

For example, I'd want to be able to transform a cube mesh (rotate/scale) and have UVs based on that, not the mesh vertices themselves. Then any transforms above that would not impact that object’s UVs.

What’s the best way to access the local transform matrix of an object in a shader in Unity?

I know that I can use objectToWorld to get access to the entire hierarchy’s flattened transform matrix, but I want to specifically access only the bottom most transform (the local one produced by the transform component on an object)

Do I have to pass this in as a custom variable each frame? Or is there a better method to use?


texts: How can I make it so the baller/ball does not keep moving after it bounces?

texts:
I am pretty new to Unity so how I did it may not be the best way, but when the character jumps it is inconsistent. When I press the up arrow key really quickly and then stop the jump will be further than it is supposed to be and it starts to glide. I want all the jumps to be the same size and the player can't bounce again until it is on the ground. Also if I start playing to quickly within the first second or two the ball jumps really far but if I wait a couple seconds it bounce like normal.

Here is my code:

    using UnityEngine;
    using System.Collections;

    public class MovePlayer : MonoBehaviour {

    public float distance;
    public float fspeed;
    public float uspeed;
    public float addToDistance;
    bool jumping = false;

    //PRIVATE
    private Rigidbody rigidBody;

    void Awake()
    {
        rigidBody = GetComponent<Rigidbody>();
        rigidBody.freezeRotation = true;
    }

    void FixedUpdate()
    {
        if (!jumping)
        {
                if (Input.GetButtonDown ("up")) {
                    rigidBody.AddForce (new Vector3 (0, uspeed, fspeed));
                }

                if (Input.GetButtonDown ("down")) {
                    rigidBody.AddForce (new Vector3 (0, uspeed, -fspeed));
                }

                if (Input.GetButtonDown ("right")) {
                    rigidBody.AddForce (new Vector3 (fspeed, uspeed, 0));
                }

                if (Input.GetButtonDown ("left")) {
                    rigidBody.AddForce (new Vector3 (-fspeed, uspeed, 0));
                }
         }

     }

    void OnCollisionEnter(Collision other)
    {
    if (other.gameObject.CompareTag("Ground"))
        jumping = false;
    }

    void OnCollisionExit(Collision other)
    {
    if (other.gameObject.CompareTag("Ground"))
        jumping = true;
    }
}


texts:
Share your methods or algorithms for painting areal objects, I will be very grateful.  I have points List <Vector2> or List <Vector3>, there are textures with different settings:

And I need to fill the area.
For example, I have 4 coordinates, I painted a square by clicking the button:


texts: Java OpenGL Perspective matrix not working

texts:
I'm trying to render a simple triangle with OpenGL in Java using LWJGL3.
Everything is working great, but the projection matrix (perspective) is not working. In C++ I just used to apply the glm::perspective() method which works just great. But in Java, I implemented it myself since there are no libraries like GLM handling it.
So here the code for the perspective in Java :

public mat4 perspective(float fov, float aspectRatio, float zNear, float zFar){
    mat4 perspective = new mat4();

    float halfTanFov = (float) Math.tan(Math.toRadians(fov/2));
    float range = zNear - zFar;

    perspective.m00 = 1f / halfTanFov * aspectRatio;
    perspective.m11 = 1f / halfTanFov ;
    perspective.m22 = - (zFar - zNear) / range;
    perspective.m23 = -1;
    perspective.m32 = (2f * zFar * zNear) / range;

    return perspective;
}

Of course I tested this multiplication and a compared a result with my TI output, and it worked great.
Other information, the default constructor for the mat4 class is putting all the values to 0.
here is the code :

public void setZero(){
    m00 = 0; m01 = 0; m02 = 0; m03 = 0;
    m10 = 0; m11 = 0; m12 = 0; m13 = 0;
    m20 = 0; m21 = 0; m22 = 0; m23 = 0;
    m30 = 0; m31 = 0; m32 = 0; m33 = 0;
}

the viewMatrix() in the other hand is working great. It's a simple implementation of the lookAt() method.
So when it's lookAtMatrix * modelMatrix * position where the position is a vec4 the result is good.
But when I try to add the projection matrix for the MVP : perspective * lookatMatrix * model * position the result is nothing.
Here where I do it in the code :

public mat4 getViewProjection() {
    mViewProjection = MatrixTransform.getInstance().lookAt(mPosition, mPosition.add(mDirection), mUp);
    return mViewProjection;
}
public mat4 getMVP(mat4 model){
    return mPerspective.mult(getViewProjection()).mult(model);
}

And here is my simple GLSL shader (for the vertex shader ) :

#version 430

layout(location=0) in vec3 position;
uniform mat4 MVP;

void main(void){
    gl_Position = MVP * vec4(position, 1);
}

I tried other implementation of the perspective without success, so I guess my mistake is somewhere else, but sadly enough, I can't figure out where. If someone could help, it'd be great ! thank you.
If you other informations, please ask me and I'll post it.

EDIT :
Here is how I put a mat4 into a uniform :

    public void uniform(String variableName, mat4 matrix){
            int loc = glGetUniformLocation(mId, variableName);
            FloatBuffer buffer = BufferUtils.createFloatBuffer(16);
            matrix.putIntoBuffer(buffer);
            buffer.flip();
            glUniformMatrix4(loc, false, buffer);
    }

and the method putIntoBuffer() :

public void putIntoBuffer(FloatBuffer buffer){
    buffer.put(m00);
    buffer.put(m01);
    buffer.put(m02);
    buffer.put(m03);

    buffer.put(m10);
    buffer.put(m11);
    buffer.put(m12);
    buffer.put(m13);

    buffer.put(m20);
    buffer.put(m21);
    buffer.put(m22);
    buffer.put(m23);

    buffer.put(m30);
    buffer.put(m31);
    buffer.put(m32);
    buffer.put(m33);
 }


texts: How to find the minimum number in a float array C# Unity

texts:
i have a for loop that detects the position of every game object in a list and gets the difference between that object and an object anchored in the center and then stores all values in a float array. what should happen next is find the minimum distance in that array and make that object (the object with the smallest distance) move towards the anchored center. the problem is that no matter what i do, it always gets the maximum number (which is the furthest game object). here is what i have so far:

public RectTransform panal;
public GameObject[] characters;
public RectTransform center;
private float[] distance;
private float minDistance;
private bool isDragging = false;
private int distanceBetweenCharacters;
private int minCharNum;

private void Start()
 {
   int charLength = characters.Length;
   center = GameObject.Find("CenterCompare").GetComponent<RectTransform>();
   distanceBetweenCharacters = 200;
 }

private void Update()
 {
     for (int i = 0; i < characters.Length; i++)
     {
         distance[i] = Mathf.Abs(characters[i].transform.position.y - center.transform.position.y);
     }

     float minDistance = Mathf.Min(distance);
     Debug.Log(minDistance);

     for (int a = 0; a < characters.Length; a++)
     {
         if (minDistance == distance[a])
         {
             minCharNum = a;
         }
     }

     Debug.Log(minCharNum);

     if (!isDragging)
     {
         LerpToChar(minCharNum * distanceBetweenCharacters);
     }
 }

 void LerpToChar(int position)
 {
    float newY = Mathf.Lerp(panal.anchoredPosition.y, position, Time.deltaTime * 5f);
    Vector2 newPosition = new Vector2(-386, newY);
    panal.anchoredPosition = newPosition;
 }

 public void StartDrag()
 {
     isDragging = true;
 }

 public void EndDrag()
 {
     isDragging = false;
 }

I assume that the problem is with the array because when i set the minCharNum to a specific integer, it works just fine. What am i doing wrong exactly? Any help is very much appreciated.


texts: How to use X,Y, and Z instead of Pitch, Roll and Yaw

texts: I'm learning Unreal engine, and I'm rather disappointed because it uses pitch roll and yaw instead of the standard x, y, and z that I'm used to.  Is there any way to convert this easily, or is there a preference, or do  I have to get used to using y,z,x, instead of x,y,z.


texts: Collision detection between two arrays with nested loops: why do I get a crash?

texts:
I'm creating a game where waves of enemies are coming to me and I have to kill them.

So far, I'm doing great: it took me hours to come up with this nested loop to check for collision detection and when I ran it the game was running great... but for a few kills only. Sometimes I manage to play it even for a few minutes until it crashes, sometimes I shoot twice and it crashes, and I always get this error:

"Uncaught TypeError: Cannot read property 'x' of undefined
    at collision (collision.js:6)"

I just cannot figure out whats going on. If someone can help me I will be so grateful, I saw similar topic but I couldn't find the answer there.

function collision(){
    for(var l = bullets.length - 1; l >= 0; l--){
        for( var k = enemies.length - 1; k >= 0; k--){
            var e = enemies[k];
            var b = bullets[l];
            if(b.x > e.x && b.x < e.x + e.imgWidth/4 && b.y > e.y && b.y < e.y +
            e.imgHeight/4 ){
                e.enemiesHealth -= 50;
                b.deletion(); // basically assigns true to b.toDelete
                e.deletion(); // basically assigns true to e.toDelete
            }
            else if (b.toDelete){
                bullets.splice(l, 1);
            }
            else if(e.toDelete && e.enemiesHealth == 0){
                enemies.splice(k, 1);
                kills += 1;
            }
        }
    }
}


texts:
I'm working on a project and I'm using some 3rd party sprites just to get it off the ground; recently I've come into a hitch. Slick2D doesn't seem to want to load my images. That is, it will warn me that images are the wrong bit-depth. All the images are in 16-bit PNG form (PNG is required for transparency). Is there any way I can disable the warning (being the bad guy programmer (the console print for each individual load REALLY SLOWS DOWN the image)) or is there another solution?

I was thinking about converting all images (using imagemagick) to .gif (with an alpha channel). Would there be any loss in quality between formats?

EDIT: I tried using imagemagick but some of the sprites use pure black so I can't do that without wrecking the image.

EDIT2: using "identify" on any of the images show them as being 8-bit.. but Slick2D won't load them. What the hell? D:

EDIT3: Issue solved (ish). If you are googling this then just disable the java png loader from slick by sticking this somewhere in your code (like the main method):

System.setProperty("org.newdawn.slick.pngloader", "false");


texts: How do you vibrate or cause a shake effect to a body of type static or dynamic or kinematic. I tried applying forces to a dynamic body in the timeStep, which did not work, as well I tried ApplyLinearImpulse many times a sec within the timeStep, which again did not give me the result. So right now Iam experimenting with adding a static circle body as a hinge point to my rectangular body and create a revolute joint between them. May be then applying a force could result in Tension between the 2 bodies? Does anybody know about this? have any ideas please let me know?


texts:
I tried to make a simple miltiplayer game with the unity tutorial. The Code of the Player looks like this:

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

 public class PlayerController : NetworkBehaviour {

     public GameObject bulletPrefab;
     public Transform bulletSpawn;

     public Camera cam;

      // Update is called once per frame
     void Update () {
         if (!isLocalPlayer) {
             return;
         }

         float x = Input.GetAxis ("Horizontal") * Time.deltaTime * 150.0f;
         float z = Input.GetAxis ("Vertical") * Time.deltaTime * 3.0f;
         transform.Rotate (0, x, 0);
         transform.Translate (0, 0, z);

         if(Input.GetKeyDown(KeyCode.Space)){
             CmdFire();
         }

     }

     void Start()
     {
         cam.gameObject.SetActive(false);
         if(isLocalPlayer)
         {
             cam.gameObject.SetActive(true);
         }

     }

     [Command]
     public void CmdFire(){
         GameObject bullet = (GameObject)Instantiate (bulletPrefab, bulletSpawn.position, bulletSpawn.rotation);
         bullet.GetComponent<Rigidbody> ().velocity = bullet.transform.forward * 6.0f;

         // Spawn the bullet on the client
         NetworkServer.Spawn(bullet);

         Destroy (bullet, 2f);
     }

     public override void OnStartLocalPlayer ()
     {
         GetComponent<MeshRenderer> ().material.color = Color.blue;
     }
 }

The Code of the health class like this :

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

 public class Health : NetworkBehaviour {

     public const int maxHeath = 100;
     [SyncVar(hook="OnChangeHealth")] public int currentHealth  = maxHeath;

     public RectTransform healthBar;
     public RectTransform publicHealthBar;

     private int maxHealthBarSize;

     public bool destroyOnDeath;

     private NetworkStartPosition[] spawnPoints;

     void Start(){
         if (isLocalPlayer) {
             spawnPoints = FindObjectsOfType <NetworkStartPosition>();

             maxHealthBarSize = (int) healthBar.sizeDelta.x;
         }
     }

     public void TakeDamage(int amount){

         if (!isServer) {
             return;
         }

         currentHealth -= amount;

         if (currentHealth <= 0) {

             if (destroyOnDeath) {
                 Destroy (gameObject);
             }
             else {
                 currentHealth = maxHeath;
                 RpcRespawn ();
             }

         }

     }

     void OnChangeHealth(int health){
         if(isLocalPlayer)
         {
             healthBar.sizeDelta = new Vector2(((float)health / maxHeath) * maxHealthBarSize, healthBar.sizeDelta.y);
         }
     }

     [ClientRpc]
     void RpcRespawn(){
         if (isLocalPlayer) {

             Vector3 spawnPoint = Vector3.zero;
             if (spawnPoints != null && spawnPoints.Length > 0) {
                 spawnPoint = spawnPoints [ Random.Range (0, spawnPoints.Length) ].transform.position;
             }

             transform.position = spawnPoint;
          }
     }

 }

But the health bar is only updating on 1 client. This means : A shoots B -> B's Healthbar updates -> B shoots A -> A's healthbar doesn't update.Does anyone know howw to fix the issue? (Is it unity or me?) Probably me :)


texts:
I've written a TGA image loader in Java which is working perfectly for files created with GIMP as long as they are saved with the option origin set to Top Left (actually TGA files are meant to be stored upside down - Bottom Left in GIMP). My problem is that I want my image loader to be capable of reading all different kinds of TGA, so my question is: How do I flip the image upside down?

Note that I store all image data inside a one-dimensional byte array, because OpenGL (glTexImage2D to be specific) requires it that way.


texts: Why do my .wav sound effects delay before playing the first time on iOS?

texts:
First off, I'm using Unity 5.2.3. I have a bunch of .wav sounds that I play like this:

     Debug.Log(m_audioAssets.m_soundBanks[(int)m_currentSoundBank].m_multiplier[data].loadState);
     m_multiplierSource.clip = m_audioAssets.m_soundBanks[(int)m_currentSoundBank].m_multiplier[data];
     m_multiplierSource.Play();

The Debug.Log is just there temporarily, to verify that the sounds' loadState is "loaded". It is, every time they play. But the first time they play on my iPhone, there is a noticable delay before they start. After playing the first time, they work fine.

What am I supposed to do to get these sounds to preload properly? I have their "Preload Audio Data" boxes checked in the import settings, and they're set to "Decompress on Load".


texts: How do you get the collision plane when using AABBs?

texts:
My collision detection initially seemed to work well enough, but my answer to this question shows that I have went with SAT testing now instead. My goal was to find the plane at which to slide the player when a collision happens, not to implement a commonly used method that 'works well enough' such as Minimum Displacement.

A more accurate and unique question would probably be how to find the first plane of collision in a (possible) multi-object collision of 1 aabb to 1+ aabb objects. My answer below is what I've went with, but please add your own and I'll happily accept them if they provide more than my own answer.

As the picture below demonstrates, from one frame to the next, if the red square moved from bottom up as the arrow points, I need something to show that the bottom face of the black square is what was collided with (or the top face of the red square).

From the book "Real Time Collision Detection by Christer Ericson" I am using the following code to get the first and last contact times of an AABB to AABB collision. I iterate through all cubes around the player in the direction of their current velocity (ensuring their velocity is handled in small increments if too large) and get the first contact time, then I sort all collisions by said contact time. I've modified the code below to report which edge was collided with (if it didn't start out with a collision), and with all of these things I can get the answer I needed.

// Intersect AABBs ‘a’ and ‘b’ moving with constant velocities va and vb.
// On intersection, return time of first and last contact in tfirst and tlast
int IntersectMovingAABBAABB(AABB a, AABB b, Vector va, Vector vb,
float &tfirst, float &tlast)
{
// Exit early if ‘a’ and ‘b’ initially overlapping
if (TestAABBAABB(a, b)) {
tfirst = tlast = 0.0f;
return 1;
}
// Use relative velocity; effectively treating ’a’ as stationary
Vector v = vb - va;

// Initialize times of first and last contact
tfirst = 0.0f;
tlast = 1.0f;
// For each axis, determine times of first and last contact, if any
for (int i = 0; i < 3; i++) {
if (v[i] < 0.0f) {
if (b.max[i] < a.min[i]) return 0; // Nonintersecting and moving apart
if (a.max[i] < b.min[i]) tfirst = Max((a.max[i] - b.min[i]) / v[i], tfirst);
if (b.max[i] > a.min[i]) tlast = Min((a.min[i] - b.max[i]) / v[i], tlast);
}
if (v[i] > 0.0f) {
if (b.min[i] > a.max[i]) return 0; // Nonintersecting and moving apart
if (b.max[i] < a.min[i]) tfirst = Max((a.min[i] - b.max[i]) / v[i], tfirst);
if (a.max[i] > b.min[i]) tlast = Min((a.max[i] - b.min[i]) / v[i], tlast);
}
// No overlap possible if time of first contact occurs after time of last contact
if (tfirst > tlast) return 0;
}
return 1;
}


texts:
I'm making an Omerta clone/mafia game and trying to work out a kill algorithm. Just a basic formula to decide how many bullets player A needs to kill player B.

The inputs are: players rank (out of 10), and a players kill skill (out of 100). The algorithm needs to return how many bullets are needed for that player to win.

If you're shooting someone a higher rank, or higher kill skill, it should require more bullets.

Anyone ever done anything like this and can offer some tips?

Example chart:


texts:
I have an FBO in a deferred 4.3 OpenGL renderer, in which I setup the depth buffer of that FBO like this:

GLCALL(glGenRenderbuffers(1, &mDepthbuffer));
GLCALL(glBindRenderbuffer(GL_RENDERBUFFER, mDepthbuffer));
GLCALL(glRenderbufferStorageMultisample(GL_RENDERBUFFER, 0, GL_DEPTH32F_STENCIL8, windowWidth, windowHeight));
GLCALL(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, mDepthbuffer));
GLCALL(glBindRenderbuffer(GL_RENDERBUFFER, 0));

Normally when I debug I can output the color attachments to screen easily, like this for normals:

GLCALL(glReadBuffer(GBuffer::GBUFFER_COLOR_ATTACHMENT_NORMAL));
GLCALL(glBlitFramebuffer(0, 0, mWindowWidth, mWindowHeight, 0, 0, mWindowWidth, mWindowHeight, GL_COLOR_BUFFER_BIT, GL_LINEAR));

But how can I do the same for the depth buffer contents, as it is not a color buffer?


texts: How to display number of collisions on UI in Unreal Engine using nodes only?

texts: I am using Unreal Engine and I want to show on UI the number of collisions using nodes only. How can I achieve that?


texts: Libgdx - How to rotate a single ShapeRenderer object

texts:
So, looked at a couple of questions similar to this, led me straight into dead ends. I have an object drawn out in ShapeRenderer, and I wish to rotate only that one object. I have tried shapeRenderer.rotate(x, y, 1, 1), however all of my ShapeRenderer objects rotate. Anyone know how one would go about rotating a single ShapeRenderer object that is defined by an array of vertices? I've posted how I have drawn my object below.

    //LEFT
    shapex[0] = x - 59/2;
    shapey[0] = y + 53/2;

    shapex[1] = x - 18/2;
    shapey[1] = y + 30/2 ;

    shapex[2] = x - 6/2;
    shapey[2] = y + 53/2;

    shapex[3] = x - 16/2;
    shapey[3] = y -51/2;

    shapex[4] = x - 21/2;
    shapey[4] = y + 1/2;

EDIT: I have tried to use polygon, however I see no good tutorials showing how to use it.


texts: How to interrupt movement where the model can lag behind

texts:
I have a movement system for my characters where the model is allowed to lag behind the character's actual position. In a way it is like the model is being dragged on a string behind the actual position. This works well to smooth out the movement when the character is running around corners or changing direction, because the pathfinder will supply a list of waypoints that are otherwise followed in a straight line.

The only problem I have is when the character is interrupted in his movement, if for instance he spots an enemy and wants to shoot at him. In this case the rendered model will often be a bit behind the actual position.

What is currently happening is that the character changes state to shoot, but this is not immediately reflected in the model, because it is still moving (lerping) towards the actual position. As a result, when the model finally gets there, it will not have time to play the full shoot animation, so it appears like the character just lifts his weapon halfway to aim, then lowers it again.

What is the best way to resolve this issue? It seems like there is no perfect solution...


texts: What caused "falling out of the world" and what fixed it?

texts:
A lot of early 3D games had the problem where you'd be trundling merrily along and suddenly everything was black, with an island of what looked like the hollow facade shell of the scene you'd been walking through rising into the distance above.  Because you'd fallen out of the world.  I remember this being a particular and long-standing problem for Bethesda Softworks, though they certainly weren't alone.  It's been a while since I've seen it in the wild, so it seems we've gotten past it.  My question is two-part:

1) What was the cause, or causes, of this?  (My guess is that it's to do with floating-point-precision related seams between polygons, interacting with point-modeled character position, i.e. floor chunk A ends at position 1.0, floor chunk B starts at position 0.9998 and for a microsecond your position is 0.99992, and boom, you fall through the world.  But that's just a guess.)

2) How did it get fixed?


texts: Why is my player spinning after a collision?

texts:
I've made a very simple 2D top down prototype with Unity. This is the code I use for the player:
public class PlayerTurnsController : MonoBehaviour
{
    private Rigidbody2D m_rb;
    public float Speed;

    Vector2 m_movement;

    void Start()
    {
        m_rb = GetComponent<Rigidbody2D>();
    }

    private void Update()
    {
        var moveHorizontal = Input.GetAxis("Horizontal");
        var moveVertical = Input.GetAxis("Vertical");
        m_movement = new Vector2(moveHorizontal, moveVertical);
    }

    void FixedUpdate()
    {
        m_rb.MovePosition(m_rb.position + m_movement * Speed * Time.fixedDeltaTime);
    }
}

At the start and while moving everything seems OK. But when I bump into some Colliders, the player sprite starts spinning when it should just stop (not pressing any button anymore)
I already tried:

To set the rotation only when the m_Movement-Vector is > 0.1f. But this didn't change anything.


texts:
I'm trying to learn how to use VBO (Vertex Buffer Objects) by putting together a simple program that draws a quad to the screen using OpenTK (C# OpenGL bindings).

Unfortunately I'm not seeing anything on screen.  If I draw the same quad in immediate mode it shows up fine.

Since it wasn't working I tried adding Color Data too (in case this was the problem) but it didn't help.

Any help would be greatly appreciated!

    private uint indexBufferId;
    private uint vertexBufferId;
    private uint colorBufferId;

    private void InitialiseData()
    {

        // Set-up index buffer:
        ushort[] indices = new ushort[] { 0, 1, 2, 3 };

        GL.GenBuffers(1, out indexBufferId);
        GL.BindBuffer(BufferTarget.ElementArrayBuffer, indexBufferId);
        GL.BufferData(
            BufferTarget.ElementArrayBuffer,
            (IntPtr)(indices.Length * sizeof(ushort)),
            indices,
            BufferUsageHint.StaticDraw);

        // Set-up vertex buffer:
        float[] vertexData = new float[] {
            50.0f, 50.0f,
            100.0f, 50.0f,
            100.0f, 100.0f,
            50.0f, 100.0f };

        GL.GenBuffers(1, out vertexBufferId);
        GL.BindBuffer(BufferTarget.ArrayBuffer, vertexBufferId);
        GL.BufferData(
            BufferTarget.ArrayBuffer,
            (IntPtr)(vertexData.Length * sizeof(float)),
            vertexData,
            BufferUsageHint.StaticDraw);

        // Set-up color buffer:
        float[] colorData = new float[] {
            1.0f, 1.0f, 1.0f, 1.0f,
            1.0f, 1.0f, 1.0f, 1.0f,
            1.0f, 1.0f, 1.0f, 1.0f,
            1.0f, 1.0f, 1.0f, 1.0f
        };

        GL.GenBuffers(1, out colorBufferId);
        GL.BindBuffer(BufferTarget.ArrayBuffer, colorBufferId);
        GL.BufferData(
            BufferTarget.ArrayBuffer,
            (IntPtr)(colorData.Length * sizeof(float)),
            colorData,
            BufferUsageHint.StaticDraw);

    }

    protected override void OnRenderFrame(FrameEventArgs e)
    {

        base.OnRenderFrame(e);

        GL.Clear(ClearBufferMask.ColorBufferBit);

        // Bind vertex buffer:
        GL.BindBuffer(BufferTarget.ArrayBuffer, vertexBufferId);
        GL.EnableClientState(ArrayCap.VertexArray);
        GL.VertexPointer(2, VertexPointerType.Float, 0, IntPtr.Zero);

        // Bind color buffer:
        GL.BindBuffer(BufferTarget.ArrayBuffer, colorBufferId);
        GL.EnableClientState(ArrayCap.ColorArray);
        GL.ColorPointer(4, ColorPointerType.Float, 0, IntPtr.Zero);

        // Bind index buffer:
        GL.BindBuffer(BufferTarget.ElementArrayBuffer, indexBufferId);

        // Draw:
        GL.DrawElements(
            BeginMode.Quads,
            1,
            DrawElementsType.UnsignedShort,
            IntPtr.Zero);

        // Disable:
        GL.DisableClientState(ArrayCap.VertexArray);
        GL.DisableClientState(ArrayCap.ColorArray);

        SwapBuffers();

    }


texts: Breakout Collision: Detecting the side of collision

texts:
I am writing a breakout clone (my first game) and am totally stuck as to how I figure out which side of the brick was hit.

I have a collision detection method that looks like this:

DetectCollision(Object a, Object b)

   x = distance(a.x, b.x);
   y = distance(a.y, b.y);

   if (x is smaller than the combined width &  y is smaller is than combined height {
       return true;
   }
return false;

This works totally fine, but I need to know the side of the collision, and location relative to the center in order to respond properly.

I've spent the past few days snooping around but am lost.


texts: How Does Ultima 7 manage different floors in 2d

texts:
In U7, you can move among floors without the function "tranport" the player to another place, as for example the first ff ones.

How can it tell whenever the character is moving from floor z to floor z+1? (of course, it uses stairs, but what is the logic behind this?) How does pathfinding in those cases work?


texts: How to create/edit a weapon in ut2004's unrealed?

texts: I've searched a lot, but almost all of the ut2k4 Unrealed tutorial websites/blogs have disappeared. How do I create or edit a weapon in Unrealed?


texts:
I am looking for a good method to determine which objects will be considered for collision with other objects.

My current idea is that each object has the following properties:

alwaysCollidesWith = [list of objects that will always trigger a collision check]
neverCollidesWith = [lost of objects that will never be considered]
teamCollidesWith = [list of objects that will be checked, provided they belong to a different team]

For example:
-projectiles never have to be checked for collisions with other projectiles
-players are always checked for collisions with players, regardless of team
-projectiles are only considered for collisions if they collide with another teams players

Does anyone see any weaknesses with this approach? Can anyone recommend a better approach?


texts: Unity seperation of prefabs with two dimensional terrain generation

texts:
I have the following function:

public void Spawn ()
        {

                GameObject g = ((GameObject)Instantiate (hills [Random.Range (0, hills.Length)], new Vector3 (0.0f, transform.position.y, transform.position.z), Quaternion.identity));
                g.transform.position = new Vector3 ((subs [subs.Count - 1].transform.position.x + (g.renderer.bounds.size.x) + (subs [subs.Count - 1].renderer.bounds.size.x) / 2), transform.position.y, transform.position.z);
                g.transform.parent = this.transform;
                NonLoopingScrollScript nls = (NonLoopingScrollScript)g.GetComponent ("NonLoopingScrollScript");
                nls.Setup (movSpeed, 0.0f);
                subs.Add (g);

        }

Which is being used to spawn terrain, the way this works is I have an array(hills) which is composed of a bunch of prefabs which together will make up terrain in the background of the game. This function is what actually instantiates the next prefab when it is needed, this prefab is then added to a list (subs). My problem is simply the spacing between the prefabs as I would like there to be no space, yet sometimes the objects overlap or there is a gap between the prefabs.

Explanation of code: In the first line I instantiate a random prefab with the argument:

hills [Random.Range (0, hills.Length)]

The next argument is where I am having trouble, what I am currently doing is setting the x value of the new prefab to the x value of the transform plus half the x width of both the previous prefab, and the new prefab. This is the issue as the spacing is not as desired. Then i simply set the y and z value to that of the spawner object and the rest of the code is irrelevent, save for where at the end of the function I then add the new gameobject to the end of the list.

I hope this was clear, if not please do not hesitate to ask questions.

Edit: The seperation of the prefabs works fine when there is only one type of prefab, but when I have several it doesn't. Here is an image of what I mean:


texts:
I've made a simple script which makes a mesh with a collider act like a button. However the mesh button get clicked through the UI.
I figured out how to fix this in editor, however this problem still occurs on the android device (did not test iOS)

    using UnityEngine;
    using UnityEngine.Events;
    using UnityEngine.EventSystems;

    public class MeshButton : MonoBehaviour {
        public bool Interactable = true;
        public UnityEvent onClick;

        private void OnMouseDown() {
            if (Interactable) {
                if(IsPointerOverGameObject()) return;
                onClick.Invoke();
            }
        }

        private bool IsPointerOverGameObject()
        {
#if UNITY_ANDROID || UNITY_IPHONE
            Touch touch = Input.touches[0];
            return EventSystem.current.IsPointerOverGameObject(touch.fingerId);
#else
            const int fingerId = -1;
            return EventSystem.current.IsPointerOverGameObject(fingerId);
#endif

        }
    }


texts: How do I draw a line from a set of points in unity to use as terrain in a 2D game?

texts:
I'm trying to make a 2D game in unity. My terrain is randomly generated and what I'm trying to do is make a bunch of points with different x coordinates and then draw a line through them to use as my ground/terrain.

Originally I wanted to make a polygon out of the points by specifying two additional vertices which would basically be the camera bounds and fill the whole thing in, but I'm not sure that's feasible, so I'll settle for just having a line as a platform.

How would I go about doing this?


texts: Where to attach global scripts in Unity?

texts: As far as Iknow in Unity, every script must be attached to an object. But what is the case with global scripts? For example in a tetris-like game to which object should I attach the element spawner and mover scripts? Or should a the element handle its movement for itself? Is there any best practice for this problem?


texts:
I have written a lighting shader file that is used as the fragment shader part of a deferred lighting pipeline.

Unfortunately, each iteration seems to be adding 0.5ms to my frame time, so any more than a handful of dynamic lights results in unbearable slowdown.

So clearly I'm doing something stupid but I'm kinda new to optimising HLSL, so anything obvious you can spot would be greatly appreciated. Here is the shader code:

#include "DLLightingInclude.hlsli"

static const float MAX_DIFFUSE_ANGLE = 1.57079637;

Texture2D NormalGB : register(t0);
Texture2D DiffuseGB : register(t1);
Texture2D SpecularGB : register(t2);
Texture2D PositionGB : register(t3);

SamplerState NormalSampler : register(s0);

cbuffer CameraProperties : register(cb0) {
    float3 CameraPosition;
}

cbuffer LightProperties : register(cb1) {
    float3 LightPosition;
    float LightRadius;
    float3 LightColor;
};

void GetGBValues(
    in int2 screenPosition,
    in float2 texturePosition,
    out float3 normal,
    out float3 diffuseAlbedo,
    out float3 specularAlbedo,
    out float specularPower,
    out float3 position)
{

    int3 screenPos3 = int3(screenPosition, 0);
    normal = normalize(NormalGB.Sample(NormalSampler, texturePosition).xyz);
    diffuseAlbedo = DiffuseGB.Load(screenPos3).xyz;
    float4 specularValues = SpecularGB.Load(screenPos3);
    specularAlbedo = specularValues.xyz;
    specularPower = specularValues.w * 50.0f;
    position = PositionGB.Load(screenPos3).xyz;
}

FS_OUT_SPLIT main(FS_IN input) {
    FS_OUT_SPLIT result;

    float3 N;
    float3 diffuseAlbedo;
    float3 specularAlbedo;
    float specularPower;
    float3 position;

    GetGBValues((int2) input.Position, input.TexCoord, N, diffuseAlbedo, specularAlbedo, specularPower, position);

    float3 L = LightPosition - position;
    float lightDistance = length(L);
    float invAttenuation = max(0.0f, 1.0f - (lightDistance / LightRadius));
    float NdotL = max(dot(N, L), 0.0f);
    float angle = acos(NdotL / (lightDistance * length(N)));

    float3 diffuseTerm = LightColor * diffuseAlbedo * (MAX_DIFFUSE_ANGLE - angle);
    float3 V = CameraPosition - position;
    float3 H = normalize(L + V);
    float3 NdotH = dot(N, H);
    float3 specularTerm = pow(saturate(NdotH), specularPower) * LightColor * specularAlbedo * min(NdotL, 1.0f);

    result.BackBuffer = result.PreBloomBuffer = float4(diffuseTerm * invAttenuation + specularTerm * invAttenuation, 1.0f);

    return result;
}

And the included file, DLLightingInclude.hlsli, looks like this:

struct VS_IN {
    float3 Position : POSITION;
    float2 TexCoord : TEXCOORD0;
};

struct VS_OUT {
    float4 Position : SV_POSITION;
    float2 TexCoord : TEXCOORD0;
};

typedef VS_OUT FS_IN;

struct FS_OUT {
    float4 Color : SV_TARGET0;
};

struct FS_OUT_SPLIT {
    float4 BackBuffer : SV_TARGET0;
    float4 PreBloomBuffer : SV_TARGET1;
};

I can't really see anything particularly obvious in what I've written- but like I say, I'm kind of a noob at this.


texts: Rotate a plane defined by its normal and its distance

texts:
First apologies for the amount of pictures, it's a bit hard trying to explain my problem without pictures. Hope I've provided all the relevant code. If you feel you want to know about how I am doing something else, please tell me and I will include it.

I've been trying to work around rotating a plane in 3D space, but I keep hitting dead ends. The following is the situation:

I have a physics engine where I simulate a moving sphere inside a cube. To make things simpler, I have only drawn the top and bottom plane and moved the sphere vertically. I have defined my two planes as follows:

CollisionPlane* p = new CollisionPlane(glm::vec3(0.0, 1.0, 0.0), -5.0);
CollisionPlane* p2 = new CollisionPlane(glm::vec3(0.0, -1.0, 0.0), -5.0);

Where the vec3 defines the normal of the plane, and the second parameter defines the distance of the plane from the normal. The reason I defined their distance as -5 is because I have scaled the the model that represents my two planes by 10 on all axis, so now the distance from the origin is 5 to top and bottom, if that makes any sense.

To give you some reference, I am creating my two planes as two line loops, and I have a model which models those two line loop, like the following:

top plane:
std::shared_ptr<Mesh> f1 = std::make_shared<Mesh>(GL_LINE_LOOP);
std::vector<Vertex> verts = { Vertex(glm::vec3(0.5, 0.5, 0.5)), Vertex(glm::vec3(0.5, 0.5, -0.5)), Vertex(glm::vec3(-0.5, 0.5, -0.5)), Vertex(glm::vec3(-0.5, 0.5, 0.5)) };
f1->BufferVertices(verts);

bottom plane:
std::shared_ptr<Mesh> f2 = std::make_shared<Mesh>(GL_LINE_LOOP);
std::vector<Vertex> verts2 = { Vertex(glm::vec3(0.5, -0.5, 0.5)), Vertex(glm::vec3(0.5, -0.5, -0.5)), Vertex(glm::vec3(-0.5, -0.5, -0.5)), Vertex(glm::vec3(-0.5, -0.5, 0.5)) };
f2->BufferVertices(verts2);

std::shared_ptr<Model> faceModel = std::make_shared<Model>(std::vector<std::shared_ptr<Mesh>> {f1, f2 });

And like I said I scale the model by 10.

Now I have a sphere that moves up and down, and collides with each face, and the collision response is implemented as well.

The problem I am facing is when I try to rotate my planes. It seems to work fine when I rotate around the Z-axis, but when I rotate around the X axis it doesn't seem to work. The following shows the result of rotating around Z:

However If I try to rotate around X, the ball penetrates the bottom plane, as if the collisionplane has moved down:

The following is the code I've tried to rotate the normals and the planes:

for (int i = 0; i < m_entities.size(); ++i)
    {
        glm::mat3 normalMatrix = glm::mat3_cast(glm::angleAxis(glm::radians(6.0f), glm::vec3(0.0, 0.0, 1.0)));

        CollisionPlane* p = (CollisionPlane*)m_entities[i]->GetCollisionVolume();
        glm::vec3 normalDivLength = p->GetNormal() / glm::length(p->GetNormal());
        glm::vec3 pointOnPlane = normalDivLength * p->GetDistance();
        glm::vec3 newNormal = normalMatrix * normalDivLength;

        glm::vec3 newPointOnPlane = newNormal * (normalMatrix * (pointOnPlane - glm::vec3(0.0)) + glm::vec3(0.0));

        p->SetNormal(newNormal);
        float newDistance = newPointOnPlane.x + newPointOnPlane.y + newPointOnPlane.z;
        p->SetDistance(newDistance);
    }

I've done the same thing for rotating around X, except changed the glm::vec3(0.0, 0.0, 1.0) to glm::vec3(1.0, 0.0, 0.0)

m_entites are basically my physics entities that hold the different collision shapes (spheres planes etc). I based my code on the answer here Rotating plane with normal and distance

I can't seem to figure at all why it works when I rotate around Z, but not when I rotate around X. Am I missing something crucial?


texts: Gamemaker: images appear blurred in application

texts:
I'm making a practice game (generic space invaders clone) in Gamemaker Studio. However, there appears to be a problem with the images. While they look acceptable in Gamemaker Studio (not amazing, due to stretching effects, but acceptable for a practice project):

However, once I compile the project down to an application I get this blurring effect:

Can anyone tell me what's causing this, and how to turn it off?


texts: What Game Development books should my partner/myself read?

texts:
My partner and I are starting to get into game development on the iPhone. I'm a programmer and he's not. We are looking for some good language agnostic game programming books. Hopefully things that will explain basic game development principles without focusing too much on the particulars of a language and more on the concepts needed to build and design games.

We will probably focus on 2D games (at the beginning anyways) so no need for books on in depth 3D math, complex AI, etc.

Any suggestions?


texts: Make a child sprite match the layer ordering of its parent

texts:
I have my project settings set up to order the sprites' visual layering based on their y position.
If I add a sword as a child to my character, the sword won't have the same order as the parent so things can look like
Sword --> enemy--> player

instead of
enemy --> sword --> player

(because I want the sword to be in front of the character)
I thought of setting the pivot point of the sword sprite so when nested inside the parent sprite, it would be around the same height as the player's pivot point so they would have the same order. I feel like this wouldn't be the best solution because when I will animate the sword to attack, I wont be able to rotate it around the position I want.....unless I make it the child of an empty object?
How can I solve this issue?


texts: What should I use (controls, methods) to make a 2D tile based map editor?

texts:
I'm making a 2d game where each tile is a square and it's viewed at straight angle, no skewing, no rotation, it's pretty simple.

Two weeks ago I tried using DataGridView, but as the number of rows and columns increased, it became frustratingly slow, then I read how it should've happened to me earlier, because this control is not supposed to work with large number of cells, and I have at least 7500 cells in my smallest level, which made it unbearable to use.

This is what I expect from my new editor:
Most importantly, tile type. Tile images or their color codes are fine (seeing map as it is in-game is cool, but the faster, the better).

Secondly, all tile parameters (in text, preferrably editable in a popup or sidebar).

I'm using my own format, so I'm most probably not going to use third party product. Besides, I'm trying to learn how to do it myself.


texts:
Possible Duplicate:
  Tools to make a trailer…

I've developed some 3d experiences using unity3d and they are pretty much experimental at this level. Now the problem is that I need to make video captures in HD to showcase them.
I've tried Camtasia 7 with divx compression, and still the quality is not Up to standard and number of dropframes are quite high. I'm running on a Core i7 cpu with geforce GT240. So I was thinking If it's possible to capturing the video remotely so one pc is in charge of capturing and one running the application.
Or is there any better way to get the highest quality with least dropframes?
Number of draw calls are around 2k(I know sounds crazy, but I can't make changes right now.)

Grazies.


texts: How can I import a Google Sketchup model with textures?

texts: I'm using Unity 4 and trying to import a SketchUp Model into Unity and other Engines - but I can't get it to import correctly. Can anyone help me out?


texts: create ipa without RoboVM in a project libgdx

texts:
I am creating an application with libgdx , and I wish I could produce an IPA without using RoboVM , because since version 1.9 became a fee . I saw on the original documentation that you can do with the gradlew.

https://github.com/libgdx/libgdx/wiki/Gradle-on-the-Commandline#packaging-the-project

command:

gradlew ios:createIPA

but I saw that still requires robovm . you can create an IPA without robovm ? or if there is a plugin that makes the IPA.

I use Android studio (IntelliJ)

Thank you


texts: Coroutine constantly updating animator transition

texts:
I have a problem for a while now and I am running out of ideas:
I have a made a coroutine used to implement animations in the attacks, something like this

private IEnumerator FirstAttack()
    {

        comboCounter = 1;
        myAnimator.SetInteger("comboSequence", comboCounter);
        currentState = PlayerState.attack;
        yield return null;

        yield return new WaitForSeconds(AttackTemplate.SetDuration(0.9f));
        comboCounter = 0;
        myAnimator.SetInteger("comboSequence", comboCounter);

        currentState = PlayerState.walk;

    }

This coroutine works perfectly fine. The problem occurs when I try to concatenate this with another coroutine to perform something like a combo sequence; to do so I basically add a while cycle that checks if I am pressing the attack button while there is a time opening for the second attack to connect. The result is this:

private IEnumerator FirstAttack() {

        comboCounter = 1;

        myAnimator.SetInteger("comboSequence", comboCounter);

        currentState = PlayerState.attack;
        yield return new WaitForSeconds(AttackTemplate.SetDuration(0.6f) - comboTimer);//Problem: if i reduce the time below the animation time of the second animation, the second animation won't go until the end

        StartCoroutine(IntervalCounter());
        comboCounter = 0;
        myAnimator.SetInteger("comboSequence", comboCounter);
        currentState = PlayerState.walk;

    }

    private IEnumerator SecondAttack()
    {

        comboCounter = 2;
        myAnimator.SetInteger("comboSequence", comboCounter);
        currentState = PlayerState.attack;
        yield return null;

        yield return new WaitForSeconds(AttackTemplate.SetDuration(0.9f));
        comboCounter = 0;
        myAnimator.SetInteger("comboSequence", comboCounter);

        currentState = PlayerState.walk;

    }

    private IEnumerator IntervalCounter()
    {
        comboTimer = AttackTemplate.SetComboTimer(0.4f);
        while (comboTimer >= 0)
        {
            Debug.Log(comboTimer);
            comboTimer -= Time.deltaTime;
            if (Input.GetKeyDown(KeyCode.Mouse0))
            {
                Debug.Log("Chained");
                StartCoroutine(SecondAttack());
                yield break;
            }
            yield return null;
        }

    }

My problem is that after adding the while loop the transition to the first animation keeps being updated, to be precise the one going from Any State to Basic Attack Tree in the following image.

If I press the attack button this transition will be repeated as long as the coroutine working. I tried to wrap around the first two lines in which i set the animator to do nothing if the integer managing the combo sequence, comboCounter is already set to 1 (which is the value related to the first attack), like this

        if (comboCounter != 1)
        {
            comboCounter = 1;
            myAnimator.SetInteger("comboSequence", comboCounter);
        }else if(comboCounter == 1) {

        }

But it keeps repeating. I wanted to use something like WaitUntil, but I tried just to put it and having a bool always false, in order to suspend the coroutine indefinitely, but in that period it keeps updating the animator. Do you have any ideas why is that? How do I prevent a coroutine from running all the time?


texts: Unity3D Joystick Buttons Xbox360 & PS3 have Inconsistent Button Inputs?

texts:
I've been browsing through Google and researching button inputs in Unity, and I came across this page. When looking at it I noticed that the B button on the Xbox360 controller is set to Button 1, but Button 1 on the PS3 controller is set to X. On a side-note, I noticed that BlazBlue: Continuum Shift EXTEND on Steam also has this issue when it comes to button inputs as an Xbox360 Controller inputs exactly as shown and a PS3 controller uses Square for Confirm and X for Cancel.
Does this inconsistency in buttons exist and how can I fix this problem so that A=X, B=O, X=Square, and Y=Triangle for my Windows-distributed game if it does? I guess a more appropriate question would be what the button mappings are for PS3 and Xbox360 formatted controllers?


texts: How to convert .max files to .egg on linux

texts:
I am very new to 3d graphics and game engines and panda3d and python. I followed few panda3d tutorials and now I want to test them with few new models. High majority of 3d models in the internet are in .max format.

Is there a way to convert these models to a format that can be used with panda3d. (.egg or .bam, I think). I am using linux. Thank you


texts: How can I hide game asset files in my release build?

texts:
My SFML 2.0 release build has a file path to game assets relative to the .exe file, so folders such as Fonts, SoundEffects, etc. are explicitly listed in Windows Explorer with the .exe. I'd like to somehow have these game asset folders not appear in Explorer.

I know I can mark the folders "hidden" in folder properties, but I've seen games that only have an .exe and nothing else, yet the game plays properly. How do I do that?


texts: How can I find all shortest paths using A*?

texts:
It is possible for A* Path Finding to return all the shortest paths given a graph/map?

For example, given the map below:

-----------
--a--X--b--
-----------

The said map can return four (4) distinct path.

-----1-----
--a11X11b--
-----------

-----------
--a22X22b--
-----2-----

----333----
--a3-X-3b--
-----------

-----------
--a4-X-4b--
----444----

The paths follow the Manhattan Heuristic and a Eight (8) directional transition with a default G-value of 1.0f for testing.

The question given the Pseudocode of A* will only return me one (1) of the four (4) distinct paths which I wish to return all four (4) paths instead.


texts: Why when loading a scene it's taking too much time?

texts:
I have two scenes in the Hierarchy when running the game.
And this script attached to empty GameObject:

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

public class LoadScenes : MonoBehaviour
{
    // Use this for initialization
    void Start()
    {
        if (!SceneManager.GetSceneByName("The Space Station").IsValid())
        {
            SceneManager.LoadScene(1, LoadSceneMode.Additive);
            StartCoroutine(WaitForSceneLoad(SceneManager.GetSceneByName("The Space Station")));
        }
    }

    public IEnumerator WaitForSceneLoad(Scene scene)
    {
        while (!scene.isLoaded)
        {
            yield return null;
        }
        SceneManager.SetActiveScene(SceneManager.GetSceneByBuildIndex(1));
    }
}

But it's taking like 3-4 seconds until it's getting to the line:

SceneManager.SetActiveScene(SceneManager.GetSceneByBuildIndex(1));


texts: implementing shadows into my 2D GLSL-based lighting system

texts:
I'm writing a lighting system in OPENGL using GLSL shaders, and I'm pretty happy with the light casting I have so far, but I'm totally stuck on casting shadows. Everything I've found online on this issue involves shadow-mapping in 3D, but I'm working in 2D and I'm not even sure shadow-mapping is the right approach here. So, here's some basic info on what I have so far:

My frag shader does all the lighting work, so I'll just post that one here:

#version 330

struct LightSource {
    vec2 pos;
    float intensity;
    vec3 c;
};
///texture in use
uniform sampler2D tex;

///BOOLEAN -> object has texture?
uniform uint hastex;

///BOOLEAN -> lighting is enabled?
uniform uint islit;

///color of fragment if no texture is applied
uniform vec4 fcolor;

///number of lights in scene
uniform int lightCount;

///MAX 25 lights in scene
uniform LightSource lights[25];

///dimensions of window
uniform vec2 wsize;

in vec2 ftexcoord;

///resulting color of fragment
layout(location = 0) out vec4 color;

void main() {
    vec4 initColor;
    if (hastex)
        initColor = texture(tex, ftexcoord);
    else
        initColor = fcolor;
    if (islit) {
        vec4 begColor;
        begColor.rgba = vec4(0.0, 0.0, 0.0, initColor.a);
        for (int i = 0; i < lightCount; ++i) {
            ///find fragment's coords in world-sapce
            vec2 fc = vec2(gl_FragCoord.x - (wsize.x / 2), gl_FragCoord.y - (wsize.y / 2));
            ///distance from fragment to light source
            float d = sqrt(pow(fc.x - lights[i].pos.x, 2) + pow(fc.y - lights[i].pos.y, 2));
            ///calculate fragment's illumination
            float n = (1 / sqrt(d)) * lights[i].intensity;
            if (n > 1) n = 1;
            vec4 tc;
            tc.rgba = vec4(n * initColor.r * lights[i].c.x, n * initColor.g *   lights[i].c.y, n * initColor.b * lights[i].c.z, 0.0);
            begColor += tc;
        }

        ///dithering
        float rand = gl_FragCoord.x * 353.0 + gl_FragCoord.y * 769.0;
        float noise = fract(rand / 991.0) / 256.0;

        color = begColor + noise;
    } else {
        color = initColor;
    }
}

Here's a screenshot of this

The problem now is that I just can't for the life of me figure out how to implement shadows here. I've tried several things unsuccessfully.

The only idea I had that even half-worked was just to pass in the positions and sizes of all objects in scene to the shader, then just have the shader try drawing a line from the fragment to the light, and test how many coords it passes through are inside objects, and darken based on that. That kinda worked, the problem is that it involves huge nested for loops with complex math and I was getting around 5 fps with that technique.

I also tried doing the looping/math I just mentioned in C++ and passing the shadow value of each coord in world-space into the shader, but looping through all of those to find which one is the same as the current fragment had similar performance issues (likely due to the almost 800,000 pixels in the scene).

I even tried changing this code into more of a ray-casting technique, as explained Here, but I had no idea how to translate the rays into GLSL and use them to determine whether a fragment was in a shadow or not, nor could I find any examples of how this could be achieved.

So, having exhausted all the online sources I can find and running out of ideas myself, I ask here, is there a way to implement shadows into this GLSL code that keeps decent performance?  Or is the way I'm going about the lighting so far too flawed to properly implement shadows into?


texts:
I need to create a tile map based level system for Corona SDK that loads files created with Tiled [1]. It also needs to support user touch scrolling and zooming.

I've searched the Corona forums for possible solutions but the ones they talk about don't convince me. They basically have a matrix of Sprite objects which have an image loaded and a given position. That makes scrolling and zooming a bit hard.

Any better ideas?

[1] http://www.mapeditor.org/


texts: How is root motion done in Skeletal animation

texts:
I am using Assimp library to load bone and mesh data and using basic interpolation to accomplish the animation part. Right now I want to move my character position with animation, i.e. root motion.

What I tried is just advance the position with translation value of root bone. I transformed this translation value with "world space rotation and translation matrix", which doesn't contain scale. (Do I also need to use scale matrix?)

Here's the simplified version of code: (assume all interpolation is happening in root joint)

 void RootBoneUpdate(float animationTime,AnimationComponent* handle)
 {
    vec3 translation = InterpolatePosition(animationTime);
    quat rotation = InterpolateRotation(animationTime);
    vec3 scale = InterpolateScaling(animationTime);

        TransformComponent transform = currentActor->GetComponent<TransformComponent>();
        RigidBodyComponent rigidBody = currentActor->GetComponent<RigidBodyComponent>();

        worldSpaceBoneTranslation = transformComponent->GetTRMatrix() * tranlsation;

//not modifying Y coordinate
        rigidBody.x = worldSpaceBoneTranslation.x;
        rigidBody.z = worldSpaceBoneTranslation.z;
}

Problem: It's working, but the game actors are moving really fast.

My understanding is that the software used to create animation must have a different coordinate space with bigger scale. Do I need to again scale the worldSpaceBoneTranslation or am I doing something wrong?


texts: How do I find out at runtime if Vulkan and/or OpenGL support is available?

texts:
I'm building an engine, which has Vulkan for its primary rendering engine. But to have at least some backwards compatibility with devices that don't get drivers for (Mainly mobile) it I want to implement an OpenGL fallback. Now, how do I check what API's are available in the current system?

I want to check if Vulkan support exists, if not then if GL support exists and if not that then crash.


texts:
I want to have the type of an event from the event queue to decide certain actions (i.e. if it is a joystick event or a keyboard one), but the dir of events is an empty list:

for e in pygame.event.get():
    print dir(e)

Although in the documentation i read:

  The queue is a regular queue of pygame.event.EventTypepygame object for representing SDL events event objects

i can't access a __dict__ attribute. The above code prints a bunch of empty lists: [] [] [] [] etc. In pygame 1.9.4 installed from pip i could run:

if e.type == pygame.JOYBUTTONDOWN:
    e.__dict__["joy"]

and i could get the number of joystick button pressed, but this is not working in 1.9.4 installed with sudo apt install (on Debian):

print event.__dict__
AttributeError: event member not defined


texts: Generally, what are the core things that one should do in the game loop, and what are some things that one shouldn't do in the game loop?


texts: How to use the Windows Phone SDK Namespaces in my Unity project?

texts:
I'm developing a game with Unity and using C# as the language for the scripts.
I want to use the Device Vibration in my Microsoft Phone which is easily available for Windows Phone Development in Visual Studio using the following:

using Windows.Phone.Devices.Notification;

And then calling the following method:

VibrationDevice testVibrationDevice = VibrationDevice.GetDefault();
testVibrationDevice.Vibrate(TimeSpan.FromSeconds(3));

The above works perfectly when I'm building a Windows Phone App from visual Studio. However i totally need to integrate the above functionality in my Unity game.

Any suggestions, workarounds, tips or even hacks would be really helpful. Thanks in advance.


texts: How to center a game in Flash Projector (like AdamAtomic's CAPSULE)

texts: Adam Atomic's game Capsule is a flash projector. If you press escape, the game goes out of fullscreen and just shows windowed. How do I get my (FLIXEL/AS3) game to show up centered like that?


texts: Loading non-square textures, from a 256x256 spritesheet in lwjgl(JAVA)

texts:
so I'm doing lwjgl, so far I have the loading of 16x16 textures from a 256x256 spritesheet all working, using this code to get the location of the textures:

 public  Vector2f[] calculateUVMapping(int texture, int atlasWidth, int atlasHeight) {
    int textureIndex = texture;

    int u = textureIndex % atlasWidth;
    int v = textureIndex / atlasHeight;

    float xOffset = 1f / atlasWidth;
    float yOffset = 1f / atlasHeight;

    float uOffset = (u * xOffset);
    float vOffset = (v * yOffset);

    Vector2f[] UVList = new Vector2f[4];

    UVList[0] = new Vector2f(uOffset, vOffset); // 0,0
    UVList[1] = new Vector2f(uOffset, vOffset + yOffset); // 0,1
    UVList[2] = new Vector2f(uOffset + xOffset, vOffset + yOffset); // 1,1
    UVList[3] = new Vector2f(uOffset + xOffset, vOffset); // 1,0

    return UVList;
}

This takes the texture ID from left to right, top to bottom in the atlas, starting from 0 and the amount of textures the atlas holds, so to get the first texture in a 256x256 sheet (holds 16 textures in each row and column) I'd do calculateUVMapping(0,16,16), along with he corresponding endings for the vector and variable.

Now, say I want to have a 200x20 texture in another 256x256 sheet, or any nonsquare texture, actually, and I want to apply that to a quad- could this code work for getting the co-ords for it, or what code should I use for those?


texts:
So, I'm new to ECS. The concept is very interesting in contrast to traditional OOP and heavy inheritance. I'm working on a game right now that is open-sourced, but does not actually have a game loop. It works by sending and receiving packets, and acting upon those received packets.

In that case, what would I be looking at in this relationship between Systems and Components? Let's say I have an incoming Movement packet that is telling me to move Player A 5 units to the right. And let's say I have a lot of different types of packet types (let's say up to 100), each for different stuff, like maybe making a purchase at an NPC store. Another one for purchasing at a player store.

Or maybe inviting and expelling players from a party. Or inviting and expelling players from a guild or alliance.

At that point, I start getting a little confused. I can definitely see similarities in ..

Adding/Expelling people from a party, guild, alliance

But each of those packets contain different information at their core. I'm tempted to write a component that Guilds, Alliances, and Parties can use (like AddRemoveMemberComponent), but the information coming in from the packet makes me hesitant.

How would those components handle specifically? Maybe I'm just entangling myself in traditional inheritance, so it's hard for me to see the uniqueness of data. Would I have unique systems for explicitly handling Party, Guild, Alliance expulsions and invitations? And how would I dynamically know what to do with these different packets coming in (different packets for alliance, guild, party).


texts: SDL_Image and typical SDL BMP loading fails completely

texts:
been messing with OpenGL and SDL for a pair of weeks.

The thing is quite weird. I have been loading a texture from a BMP and using a really easy shader to make it work, and so far it has worked very well.

Now, i've refractored my code and made a heightmap loader, with is pretty cool and works nice. I have a ResourceManager class which successfully loads shaders but fails at loading textures.

The structure of that class is simple:

Constructor (empty)
Destructor (empty)
AddTexture (const char* FileName, const char* indexName)
GetTexture (const char* indexName)
typedef map TextureMap
typedef TextureMap::iterator TextureIt
TextureMap Textures

I tried using SDL Load BMP function and SDL_img Load IMG function. The first one makes this weird result:

Close-Up

When the real image is a simple BMP in 32bit format, as always:

Real Texture

And the second method, using SDL_image, simply doesn't show the image.

The 'AddTexture' function:

bool TEXTURE::TextureManager::AddTexture(const char* fileName, const char* indexName)
{
    SDL_Surface* img = SDL_LoadBMP(fileName);
unsigned int id;
glGenTextures(1, &id);
glBindTexture(GL_TEXTURE_2D, id);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img->w, img->h, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, img->pixels);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
SDL_FreeSurface(img);
Textures[indexName] = id;
return true;
}

And the 'AddTexture' SDL_image version:

GLuint id = 0;

SDL_Surface* Surface = IMG_Load(fileName);

glGenTextures(1, &id);
glBindTexture(GL_TEXTURE_2D, id);

int Mode = NULL;
if(Surface->format->BytesPerPixel == 4)
    Mode = GL_RGBA;
else
    Mode = GL_RGB;

glTexImage2D(GL_TEXTURE_2D, 0, Mode, Surface->w, Surface->h, 0, Mode, GL_UNSIGNED_BYTE, Surface->pixels);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

glBindTexture(GL_TEXTURE_2D, 0);

std::cout << "The ID of the tex is " << id << std::endl;

Textures[indexName] = id;

return true;

I create the texture here:

Res->TexManager->AddTextureAlt("res/sum.bmp", "Brick");

And the following code is used to bind the texture:

GLuint TEX = Res->TexManager->GetTexture("Brick");
glBindTexture(GL_TEXTURE_2D, TEX);

The normals and tex coords are alright, i've been using it all the time and it was displaying the tex and light perfectly well before.

I can't find the problem. I just can't. Is someone able to help a poor noob?


texts:
I have 3d vectors that I want to project as 2d vectors to draw my shapes. I got a 3d vector cameraPosition, a 3d vector cameraDirection, a float renderDistance. I need to create an orthogonal / isometric matrix with those values to project my 3d vectors.

Here is what I currently have :

matrix4x4(vec3 camera, vec3 camreaDir, vec3 camreraScale){
    //get isometric projection matrix
    vec3 xImage = vec3(-sinf(camreaDir.x), cosf(camreaDir.x), 0) *
camreraScale.x; //unused member : z
    vec3 zImage = vec3(-sinf(camreaDir.x + camreaDir.z), cosf(camreaDir.x + camreaDir.z), 0) * camreraScale.z; //unused member : z

    matrix[0][0] = xImage.x;
    matrix[1][0] = 0;
    matrix[2][0] = zImage.x;
    matrix[0][1] = xImage.y;
    matrix[1][1] = camreraScale.y;
    matrix[2][1] = zImage.y;
}


texts: Best way to separate display and game logic (threads)

texts:
What is the best way to separate render and game logic threads?

I'd like to make logic-heavy game (ai, machine learning, and network) in which world updates 50-60 times per second.

I want to separate rendering so it will not waste logic's thread power.

I'm planning to use c++ with boost.