texts: Is there a way to use the facebook sdk with libgdx?

texts:
I have tried to use the facebook sdk in libgdx with callbacks, but it never enters the authetication listeners, so the user never is logged in, it permits the authorization for the facebook app but it never implements the authentication interfaces :(

Is there a way to use it?

public MyFbClass()
{
    facebook = new Facebook(APPID);
    mAsyncRunner = new AsyncFacebookRunner(facebook);
    SessionStore.restore(facebook, this);

    FB.init(this, 0, facebook, this.permissions);
}

///Method for init the permissions and my listener for authetication
public void init(final Activity activity, final Facebook fb,final String[] permissions)
    {
        mActivity = activity;
            this.fb = fb;
        mPermissions = permissions;
        mHandler = new Handler();
        async = new AsyncFacebookRunner(mFb);

        params = new Bundle();

        SessionEvents.addAuthListener(auth);

    }

///I call the authetication process, I call it with a callback from libgdx
public void facebookAction()
    {
        // TODO Auto-generated method stub
        fb.authenticate();
    }

///It only allow the app permission, it doesnt register the events
public void authenticate()
    {
        if (mFb.isSessionValid())
        {
            SessionEvents.onLogoutBegin();
            AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(mFb);
            asyncRunner.logout(getContext(), new LogoutRequestListener());
            //SessionStore.save(this.mFb, getContext());
        }
        else
        {
            mFb.authorize(mActivity, mPermissions,0 , new DialogListener());

        }
    }

public class SessionListener implements AuthListener, LogoutListener
    {

        @Override
        public void onAuthSucceed()
        {
            SessionStore.save(mFb, getContext());
        }

        @Override
        public void onAuthFail(String error) {
        }

        @Override
        public void onLogoutBegin() {
        }

        @Override
        public void onLogoutFinish() {
            SessionStore.clear(getContext());
        }
    }

DialogListener() {

            @Override
            public void onComplete(Bundle values)
            {
                SessionEvents.onLoginSuccess();
            }

            @Override
            public void onFacebookError(FacebookError error)
            {
                SessionEvents.onLoginError(error.getMessage());
            }

            @Override
            public void onError(DialogError error)
            {
                SessionEvents.onLoginError(error.getMessage());
            }

            @Override
            public void onCancel()
            {
                SessionEvents.onLoginError("Action Canceled");
            }
}


texts: I'm trying to think of sounds that will help convey the time of day and weather condition. I'm not even sure of all the weather conditions I would consider, and some are obvious. Like if it's raining, the sound of rain. But then I'm thinking, what about for a calm day? If it's morning time, I could do birds chirping or something. Night time could be an owl or something. What are some good combinations of sounds/weather/time to have a good effect?


texts:
I have generated a 1024 X 1024 heightmap using Open simplex noise. Now i want to zoom into a 64X64 area. Every pixel in the 64X64 is not 16X16 on the larger scale.

I tried just generating the area, but problem is, that I want to also calculate normals from it, and the normals are different for the zoomed in area from the big map. The difference comes from the fact that on the big map the height difference between 2 pixels can be quite large, but when zoomed in, new pixels are place between the original 2 so if now normals are calculated, they are totally different.

How can I zoom into an area of a generated heightmap but retain the normals?
On the left is the large scale map and on the right is the zoomed in area. Zoomed in area is the upper left corner of the large scale map. As you can see the normals are completely different. Both of these images are textures. There are no meshes or anything only textures, and there will not be any meshes in future either.

This is how I calculate normals from heightMap.

            u = noiseValues[x + (y - 1) * width];
            r = noiseValues[x + 1 + y * width];
        }
        Vector3 up = new Vector3(0, 1, (noiseValues[index] - u)*100);
        Vector3 across = new Vector3(1, 0, (r - noiseValues[index])*100);

        normal = across.Cross(up).Normalized();
        normal = (normal + new Vector3(1, 1, 1)) / 2.0f;

After updating these lines in normal calculation:

 Vector3 up = new Vector3(0, 1/zoomFactor, (noiseValues[index] - u)*100);
        Vector3 across = new Vector3(1/zoomFactor, 0, (r - noiseValues[index])*100);

This is the result after adjusting normal calculation:


texts: Would it be more efficient to handle 2D collision detection with polygons, rather than both squares/polygons?

texts: I'm working on a 2D game engine and I'm trying to get collision detection as efficient as possible. One thing I've noted is that I have a Rectangle Collision collider, a Shape (polygon) collider and a circle collider. Would it be more efficient (either dev-time wise or runtime wise) to have just one shape collider, rather than have that and everything else? I feel it would optimize my code in the back end, but how much would it affect my game at runtime? Should I be concerned with this at all, as 3D games generally have tens of thousands of polygons?


texts:
At the top
public float secondsToRotate;
private float secondsSoFar = 0.0f;

Then in the Update
private Update()
{
  secondsSoFar += Time.deltaTime;
  float t = secondsSoFar / secondsToRotate;
  Vector3 lerpPoint = Vector3.Lerp(transform.position, -transform.position, t);
  transform.rotation = Quaternion.LookRotation(lerpPoint);
}

but instead of slowly smooth rotating it's just waiting X seconds then rotate too fast like rotating at once.
I wanted it to rotate slowly smooth. for example, if I set the secondsToRotate to 5 so the rotation will take 5 seconds.
The full script :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerSpaceshipAreaColliding : MonoBehaviour
{
    public float rotationSpeed;
    public float movingSpeed;
    public float secondsToRotate;

    private float timeElapsed = 0;
    private float lerpDuration = 3;
    private float startValue = 1;
    private float endValue = 0;
    private float valueToLerp = 0;
    private Animator playerAnimator;
    private bool exitSpaceShipSurroundingArea = false;
    private bool slowd = true;
    private float secondsSoFar = 0.0f;

    // Start is called before the first frame update
    void Start()
    {
        playerAnimator = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        if (exitSpaceShipSurroundingArea)
        {
            if (slowd)
                SlowDown();

            if (playerAnimator.GetFloat("Forward") == 0)
            {
                slowd = false;
            }

            if (slowd == false)
            {
                secondsSoFar += Time.deltaTime;
                float t = secondsSoFar / secondsToRotate;
                Vector3 lerpPoint = Vector3.Lerp(transform.position, -transform.position, t);
                transform.rotation = Quaternion.LookRotation(lerpPoint);
            }
        }
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.name == "CrashLandedShipUpDown")
        {
            exitSpaceShipSurroundingArea = false;
            Debug.Log("Entered Spaceship Area !");
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.name == "CrashLandedShipUpDown")
        {
            exitSpaceShipSurroundingArea = true;
            Debug.Log("Exited Spaceship Area !");
        }
    }

    private void SlowDown()
    {
        if (timeElapsed < lerpDuration)
        {
            valueToLerp = Mathf.Lerp(startValue, endValue, timeElapsed / lerpDuration);
            playerAnimator.SetFloat("Forward", valueToLerp);
            timeElapsed += Time.deltaTime;
        }

        playerAnimator.SetFloat("Forward", valueToLerp);
        valueToLerp = 0;
    }
}

In that place in the script, I'm trying to rotate the player smooth slowly to the opposite direction.  I want also to increase the "Forward" speed when it's rotating while it's rotating but for now the rotation itself is not working at all the player is not rotating.
if (slowd == false)
                {
                    secondsSoFar += Time.deltaTime;
                    float t = secondsSoFar / secondsToRotate;
                    Vector3 lerpPoint = Vector3.Lerp(transform.position, -transform.position, t);
                    transform.rotation = Quaternion.LookRotation(lerpPoint);
                }

The main goal is to create some realistic effect when the player is leaving the colliding area the player will slow down then when the player has stopped to start rotating slowly to the opposite direction and start moving by increasing the "Forward" value while rotating.
Some realistic preventing from the player to leave the colliding area. when he try to leave the area he should move back in the colliding area.


texts: detect collision between two circles and sliding them on each other

texts:
I'm trying to detect collision between two circles like this:

var circle1 = {radius: 20, x: 5, y: 5}; //moving
var circle2 = {radius: 12, x: 10, y: 5}; //not moving

var dx = circle1.x - circle2.x;
var dy = circle1.y - circle2.y;
var distance = Math.sqrt(dx * dx + dy * dy);

if (distance < circle1.radius + circle2.radius) {
    // collision detected

}else{
    circle1.x += 1 * Math.cos(circle1.angle);
    circle1.y += 1 * Math.sin(circle1.angle);
}

Now when collision is detected I want to slide the circle1 from on the circle2 (circle1 is moving) like this:

--circle1---------------------------------circle2-------------------------

I could do this by updating the angle of circle1 and Moving it toward the new angle when collision is detected.

Now My question is that how can I detect whether to update/increase the angle or update/decrease the angle based on which part of circle2 circle1 is colliding with ??

I would appreciate any help


texts:
I ve been playing with ShoeBox lately and when trying to make a frame sheet i see that they don't appear alphabetically (frame_1 , frame_2 , etc). But they appear by best fitting. In Texture-Packer you can sort it by name but i cant see that option in ShoeBox.

How can i do this?
Thanks in advance


texts: How to use setInterval and clearInterval

texts: I have a game that I am making and cannot seem to get the setInterval and clearInterval methods to work.  When I debug it in the browser console it shows that the method is still being called over and over again. I am wondering how can I get it to actually stop and then restart afterwards without going faster than it was before (which often happens with setInterval and clearInterval).  Notice that when it goes back to the menu, and you click Start again that the timer is running multiple times on the money. Any help is much appreciated, please take a look at this fiddle demo: http://jsfiddle.net/Xn4qT/


texts: Reading and writing an anti-aliased texture in Direct3D9

texts:
I'm slightly confused about textures versus surfaces in Direct3D9. Now, it seems fairly simple that you can only read from a texture and only write to a surface, and when you create a texture then you can get surfaces to set as render targets from it.

What I don't quite get is the CreateTexture function. It's CreateRenderTarget equivalent for a surface which is only rendered to and never read has the options of anti-aliasing parameters, whereas CreateTexture doesn't, even though you can explicitly use it to create render targets.

Does that mean that it is impossible to create an intermediate texture for e.g. shadow mapping which has anti-aliasing?


texts:
I'm working on a level editing tool that saves its data as XML.

This is ideal during development, as it's painless to make small changes to the data format, and it works nicely with tree-like data.

The downside, though, is that the XML files are rather bloated, mostly due to duplication of tag and attribute names. Also due to numeric data taking significantly more space than using native datatypes. A small level could easily end up as 1Mb+. I want to get these sizes down significantly, especially if the system is to be used for a game on the iPhone or other devices with relatively limited memory.

The optimal solution, for memory and performance, would be to convert the XML to a binary level format. But I don't want to do this. I want to keep the format fairly flexible. XML makes it very easy to add new attributes to objects, and give them a default value if an old version of the data is loaded.  So I want to keep with the hierarchy of nodes, with attributes as name-value pairs.

But I need to store this in a more compact format - to remove the massive duplication of tag/attribute names. Maybe also to give attributes native types, so, for example floating-point data is stored as 4 bytes per float, not as a text string.

Google/Wikipedia reveal that 'binary XML' is hardly a new problem - it's been solved a number of times already. Has anyone here got experience with any of the existing systems/standards? - are any ideal for games use - with a free, lightweight and cross-platform parser/loader library (C/C++) available?

Or should I reinvent this wheel myself?

Or am I better off forgetting the ideal, and just compressing my raw .xml data (it should pack well with zip-like compression), and just taking the memory/performance hit on-load?


texts:
I am trying to create physics for a ball in Libgdx. The ball starts moving after a pan and everytime the ball collides with a wall, a moveTo action is added to it. But my ball moves with a constant velocity (action time = distance/velocity). I want my ball movement to get slower smoothly.

Here is my method for calculating velocity

private float velocity(float panDistance) {
        float coefficent = 0.3f;
        return panDistance / coefficent;
    }

in act method of the Ball I decrement velocity

  @Override
    public void act(float delta) {
        super.act(delta);
        if (velocity < 100 && velocity > 0) {
            ballImage.clearActions();
        }
     velocity -= 3f*delta;
 }

When gesture detector detects a pan the method below is called.

public void moveTheBall(float tanX, float tanY) {
        if (ballImage.getActions().size == 0) {
            motionVector = (int) (tanX / Math.abs(tanX));
            motionAngleTan = tanY / tanX;
            panDistance = (float) Math.sqrt((tanX * tanX) + (tanY * tanY));
            velocity = velocity(panDistance);
            recursivelyAddActions(motionVector);
        }
    }

in recursivelyAddActions() method

private void recursivelyAddActions(int vectorDirection) {
    // AFTER SOME CALCULATIONS
    distance = (float) Math.sqrt(((predictionX - ballStartingPosX) * (predictionX - ballStartingPosX)) + ((predictionY - ballStartingPosY) * (predictionY - ballStartingPosY)));
        moveToAction = Actions.moveTo(predictionX, predictionY, distance / velocity);
        ballImage.addAction(moveToAction);
    }

this is not smooth and this does not work good. I need an advice to make this work better. Thank you.


texts: Modifying depth values in PixelShader (SharpDX)

texts:
I'm relatively new to DirectX, and am currently converting some WPF 2D graphics code that displays geo-located sonar returns. I am using SharpDX, and rendering via a D3DImage.

I've got the basics working nicely, with very good performance, rendering segments of sonar as a set of quads textured via a texture array of chunks of sonar data.

I am now trying to modify the pixel shader so that it shows the highest "quality" signal return in the case where I have an overlap. Consider that the sonar return spreads from a central point, and (generally) gets worse the further away it is. When we have an overlap, a starting point to showing only the best data is to simply show the pixels that are nearest to the centre of the track, and a simple way I thought to do this would be to modify the depth values in the pixel shader so that the depth varies with the signal distance.

I have added a PS_OUT struct as so:

struct PS_OUT
{
    float4 Colour   : SV_Color;
    float Depth     : SV_Depth;
};

and a simplified version of the PixelShader:

    float quality = 1 - input.domain_uv.x;
    result.Colour = float4(quality, quality, quality, 1);
    result.Depth = quality;
    return result;

where the quality value varies from 0-1, and in this example I am also colouring the output with this quality value:

..which gives the expected colour output, but not the depth output. What I expect (want!) is that the higher quality (lighter coloured) output is preferred over the dark on a per-pixel basis.

I can confirm that depth testing is enabled, as I can vary the z coordinates of my quads and see the results. What seems to be my sticking point is that the depth value I calculate in the pixel shader is simply ignored, and my best guess is that I am missing something obvious - like I need to tell Directx to use it, and not its own calculated values. I can't find any documentation that suggests anything other than modifying the shader semantics is required.

The depth buffer/stencil is set up like this - this is taken from a WPF/SharpDX integration package:

 Set(ref m_depthStencil, DXUtils.CreateTexture2D(this.m_device, w, h,    BindFlags.DepthStencil, Format.D24_UNorm_S8_UInt));
  //Set(ref m_depthStencil, DXUtils.CreateTexture2D(this.m_device, w, h, BindFlags.DepthStencil, Format.D32_Float));
 Set(ref m_depthStencilView, new DepthStencilView(this.m_device, m_depthStencil));

 m_device.ImmediateContext.Rasterizer.SetViewports(new ViewportF[] { new ViewportF(0, 0, w, h, 0.0f, 1.0f) }, 1);
 m_device.ImmediateContext.OutputMerger.SetTargets(m_depthStencilView, m_renderTargetView);

I did try varying the texture format (see commented line), to no avail.

Subsequent to this, I also want to blend the very edges of the joins - but I'll leave that question for another day.

thanks,
Matt

edit: I can simulate the final effect that I am after by adjusting the depths of my quad vertices such that the middle is lower than the outer. Depths are then "real" depths, and the correct pixels are drawn. I don't think, however, that this is going to work as a solution for me because I want to be able to implement a slightly more complicated "quality" metric in the pixel shader. SO the question remains: why are my depth values calculated in the PS being ignored?

Here's an image of overlapping tracks where the "closest" pixel is rendered at all times:


texts: The A,I can't seems to move/strafe on the left continously?

texts:
void Update()
{
    ChasingPlayer();
}

void ChasingPlayer()
{
    if (chasing == true)
    {
        transform.LookAt(player.transform);  //facing player
        transform.position += transform.forward * approaching * Time.deltaTime;  //going towards player
    }

        float distance = Vector3.Distance(transform.position, player.position);
    Debug.Log(distance); //calculating the distance between player and enemy
    if(distance < 10)
    {
        chasing = false;
        transform.position += Vector3.left * 2f * Time.deltaTime;
        Debug.Log("STOP!");
    }
}

I want my A.I to approach to the player but when it reaches within 10 feet(?), I want it to stop moving towards the player and strafe/move to the left or right from there but instead it just moving in a curve movement that leads towards the player. How should i stop the AI within 10 feet(?) and move to the left/right?


texts: How does OpenGL-ES 2 assemble primitives?

texts:
Two things I'm quite confused about.

1) OpenGL ES 2.0 creates primitives before the vertex shader is invoked. Why, then, does it not automatically provide the vertex shader the position of the vertex?

2) OpenGL ES 2.0 supports glDrawElements(), but it does not support glEnableClientState() or GL_VERTEX_ARRAY, so how can this call possibly be used to construct primitives?

NOTE: this is OpenGL ES 2.0, NOT normal OpenGL!

Thanks!

Resolution:

I think my confusion was stemming from the built in variable gl_Vertex that some versions of GLSL support (according to some sources, I couldn't find this in the official documentation at http://www.opengl.org/sdk/docs/manglsl/) which gives you the position of the vector provided to the draw command. This isn't present in GL ES. Further, my code was't working, and as GLSL can be difficult to debug, I had no idea what was going on :)

In this case, using vertex attributes and passing the model-space location of the vertices and my transformation matrix allows me to transform the vertices correctly.


texts: When rendering on two different computers, the texture is glitchy

texts:
I am using Ogre3D, and have been using it for a while. Also lately, I have been using the Opengl Rendering system that is included in Ogre, only because Directx will not compile correctly(Will post errors on request through comment).

But as of now the main problem is when i render my model(it is a plane with simple, unblended pixelated texture), it looks like this on my Laptop(Left Image), but when I render on the desktop(Right Image), it looks the way its supposed to be.

Im pretty sure this problem might not be relevant to this site, but im not sure on where else to post this(if it needs to be moved then so be it), but i felt it would fit here just a bit, since its a game-dev type question.

Anyways, My compiler is MinGW that uses the IDE Code::Blocks.
also the operating system that im using on both computers are windows Vista 32 bit.

Now if anyone would know why this would happen then please do tell(but my guess is that maybe the graphics card is not compatible)

Here are the images:

Left:Laptop

Right:Desktop

there both about the same image, and if you notice on the desktop screenshot: it looks more clearer and you can see the "mountains" better, where on the laptop picture, you cant see any pattern at all...Also, you can notice an odd stopping of light(or maybe called something else), but that has me confused also.


texts: Is there a 3d animation software that prioritizes working with code rather than GUI?

texts:
All of the 3D animating softwares I've faced are centered around using GUI to work: windows, menus, mouse clicks, mouse adjustments, keyboard shortcuts. As a programmer, I find that limiting. In order to have full control over an animation, it'd be interesting to use code. For example, say you wanted to animate a magic sword which color depended on speed. Without programming, that's not possible at all.

Thus I ask: is there a 3D animation softwares that target coding, not GUI work?


texts: What should I worry about when changing OpenGL origin to upper left of screen?

texts:
For self education, I'm writing a 2D platformer engine in C++ using SDL / OpenGL.  I initially began with pure SDL using the tutorials on sdltutorials.com and lazyfoo.net, but I'm now using SDL to create an OpenGL rendering context and then render with OpenGL functions (specifically immediate mode but I'm learning about VAOs/VBOs). I am using SDL only for interface, audio, etc.

SDL uses a coordinate system with the origin in the upper left of the screen and the positive y-axis pointing down. It's easy to set up my orthographic projection in OpenGL to mirror this.

I know that texture coordinates are a right-hand system with values from 0 to 1 -- flipping the texture vertically before rendering (well, flip the file before loading) yields textures that render correctly... which is fine if I'm drawing the entire texture, but ultimately I'll be using tilesets and can imagine problems.

What should I be concerned about in terms of rendering when I do this?

If anybody has any advice or they've done this themselves and can point out future pitfalls, that would be great, but really any thoughts would be appreciated.


texts: How can i get object from TMXTiledMap and store it in Dictionary variable ?

texts:
I've been following a tutorial to make tiled map in cocos2d x 3.0 ,
but i couldnt complete the rest of the tutorial because its for coco2d x 2.0 version,

How can i get a value of property that is stored in an object from TMXObjectGroup variable ?
and my code is:

tileMap = cocos2d::TMXTiledMap::create("ground.tmx");
ground = tileMap->layerNamed("ground");
this->addChild(tileMap);

TMXObjectGroup *objects = tileMap->getObjectGroup("objects");
??? sign = objects->getObject("sign");// it return ValueMap not Dictionary ?!

how can i get a Dictionary of that object so i can get its values ??


texts: Making a wrapping wire (like the Worms Ninja Rope) work correctly with moving geometry

texts:
I have implemented a 2D wire like the one described in this question which is made up of straight line segments between wrapping points. However, while the algorithms described in this answer work just fine for colliding with static geometry, it does not behave correctly when interacting with moving geometry. The method described in this answer does work correctly in some cases, but not when the rope does not move, since the collision detection method does not account for the movement of points.

How would you make the wire behave correctly when interacting with moving geometry?


texts:
My game  will be made up of objects. Essentially the level editor will give me a bunch of objects to choose from and I can drag them in and thus a level is made. The objects could have animation in which case they are responsible for knowing which frame and layer they are on.

So then I can have these:

Animated non-movable objects
Unanimated non-movable objects
Animated movable objects
Unanimated movable objects

So first I was thinking of, when the level starts, build a quadtree for all non-movable objects.

This way I can easily avoid rendering ones which are not in view.

Then from there I can do bounding box check on dynamic objects (or maybe if I add something like Box2D it can do it).

But then comes the rendering.

At first I was thinking of each object rendering itself, but then I cannot do atlasing.

I'd like to do atlasing. I was thinking that animated objects can just use their own frame sheet. But objects which are not animated should use atlasing.

I know this can be categorized as premature optimization, but I don't want to eventually find out that it is horribly slow.

Any design suggestions / comments would be welcome. Does it seem like a good idea to try to atlas in the sort of game I'm making, which is a platformer that is not tile based.


texts: Conundrum with quality and virus reports: is our game releasable?

texts:
I've just got done talking to the CEO of our independent game studio about one of our projects nearing completion. We're considering canning the whole project for a number of reasons:

There are partly, some quality issues. Combat can be fun and in depth but for the most part you can get by with mashing buttons. It leaves the feeling that the advanced combat was really tagged on just to add something. When in reality a lot of work went into it.
The game didn't end up as envisioned. It's become really a mindless combat game when originally story was planned to be important. Now the story is rather nonexistent.
And probably the biggest issue. Rather recently we've been getting reports from testers that the game is being reported as a virus(in a few cases). We looked into this and found it's the way the engine was made. We're using a 3rd party engine and while originally the maker was very approachable, he's become rather unreachable and apathetic to our problems.

Me and him have talked a long time on this and we lean on it not being releasable. This would also though be a very big hit to the lead programmer who's put in a considerable amount of time on this, nearly a year.

What ramifications would happen if this is released? I'm told it could get on steam, and I'm thinking it could be pulled and really hurt our image. Also I mentioned we could be backlisted by our publisher if they consider the virus issue to be deceiving them. Could we be sued? Would you consider it releasable?

I think this is a very important decision every game studio might have to make one day and I'd really like as much input as I can get.

Thank you

[edit]
Also it might matter that we have another version of the game already being made for html5 which is being developed in house with our own custom engine. We're thinking of just focusing on this and learning from our mistakes.


texts: How should I store the objects to render?

texts: From what I understand, in order to show all elements of a 2D game in the proper way, I need to render them in order, from the further away from the camera to the closest. So I should sort them by depth before displaying them. Since sorting a list 60 times per second seems kinda clunky, would it be a better idea to store the objects to render in a binary search tree? Is there an ideal way to do store these objects? Or did I get something wrong? about this?


texts:
I'm curious how multiplayer networking with physics is implemented in racing games.
We have a physical world with multiple fast-moving vehicles controlled by different people.
Let's say that vehicles have weapons and can shoot each other (Twisted Metal, Vigilante v8)

I'm anxious about hits and collisions.
Authoritative server or a better alternative?


texts:
Hey so i've been looking into real time physics engines, which led me to the crazyLaggoa multiphysics engine by thiaga costa, and brought up the question of:

What are some possible ways, ideas that have or have not already been done to make a real time physics engine? How about non-real time?

I know the Lagoa engine uses meshes and a crapload of particles... and then there's the rigid body way of going about things.....
Also i'm only at 2d level in creating games right now so any 2d physics ideas would be great too!


texts: Rotate Character towards Moving direction

texts:
So my Problem is that my Character is always shooting in the way it is looking. Unfortunaly my solution seems to be a very bad one.  I am not really cabable of aiming with my solution. Neither with Controller or Touchscreen Control.
I already commented many Things out as you can see but nothing works correctly for me.
It is a 2D Top-Down Game.

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {
    public int dead = 0;
    //Moving
    public float maxSpeed = 3f;
    public float rotSpeed = 100f;
    public Transform target;
    float zo;
    float opZ;
    //Shooting
    public Vector3 bulletOffset = new Vector3(0, 0.5f, 0);
    public GameObject bulletPrefab;
    int bulletLayer;
    public float fireDelay = 0.25f;
    float cooldownTimer = 0;
    GameObject pau;

    void Start () {
        bulletLayer = gameObject.layer;
        pau = GameObject.FindGameObjectWithTag("MainCamera");

    }

    // Update is called once per frame
    void Update () {
        //Debug.Log("GameP ->" + pau.GetComponent<PauseGame>().isPause);
        if(!pau.GetComponent<PauseGameGameover>().isPause){
        if(dead == 0)
        {
            //Moving
            movePlayer();
            //Shooting
                cooldownTimer -= Time.deltaTime;
            if( CFInput.GetButton("Fire1") && cooldownTimer <= 0 ) {
                shotPlayer();
            }
        }
        }
    }
    void shotPlayer()
    {
            // SHOOT!
            cooldownTimer = fireDelay;

            Vector3 offset = transform.rotation * bulletOffset;

            GameObject bulletGO = (GameObject)Instantiate(bulletPrefab, transform.position + offset, transform.rotation);
            bulletGO.layer = bulletLayer;
    }

    void movePlayer()
    {
        float x = CFInput.GetAxis("Horizontal");
        float y = CFInput.GetAxis("Vertical");
        ////////////////
        /// Rotate the PLAYER
        /// /////////////////////////////
        zo= x*90;
        //Debug.Log("ZO -> " + zo);
        if(y > 0 && x > 0){opZ = 360-zo;} //Oben bis Rechts
        if(y < 0 && x > 0){opZ = 180+zo;} // Rechts bis unten
        if(y < 0 && x < 0){opZ = 180+zo;} //Unten bis Links
        if(y > 0 && x < 0){opZ = -1*zo;} // Links bis oben
        /* Hardcoded Left Right Up Down */
        /*if(y == 0 && x > 0){opZ = 270;}
        if(y == 0 && x < 0){opZ = 90;}
        if(y < 0 && x == 0){opZ = 180;}
        if(y > 0 && x == 0){opZ = 360;}
        if(y == 0.5 && x == 0.5){opZ = 315;}
        if(y == -0.5 && x == 0.5){opZ = 225;}
        if(y == -0.5 && x == -0.5){opZ = 135;}
        if(y == 0.5 && x == -0.5){opZ = 45;}
        //Debug.Log("OPZ: ->" + opZ);
        */
        // Grab our rotation quaternion
        Quaternion rot = transform.rotation;
        // Grab the Z euler angle
        //float z = rot.eulerAngles.z;
        // Recreate the quaternion
        Quaternion rotNew = Quaternion.Euler( 0, 0, opZ );

        transform.rotation = Quaternion.Lerp(rot, rotNew, Time.time * rotSpeed);

        ///////////////////
        // MOVE the PLAYER
        ////////////////////////
        ///

        Vector3 pos = transform.position;

        Vector3 velocity = new Vector3(CFInput.GetAxis("Horizontal") * maxSpeed * Time.deltaTime, CFInput.GetAxis("Vertical") * maxSpeed * Time.deltaTime, 0);

        pos += velocity;

        // Finally, update our position!!
        transform.position = pos;
    }
}


texts: How to make legacy animations run in Unity in unscaled time? (Pause game related)

texts:
I'm relatively new to Unity, and I've been having a very difficult time getting the legacy animations to run in unscaled time.  I need to pause my game, and as soon as it pauses, I need to have my boxes for the pause screen come in from the side.  This sort of works if I use an IEnumerator, but I have to hard-code exactly how long it will take for the animation to come in (.333f seconds) and the game will not pause until the animation fully shifts in.

The major problem with this is that I need to use more moving animations while the game is paused that will be called using the onClick() methods in the pause game's buttons.  Think of my pause menu as somewhat like an old-school RPG's menu like Final Fantasy but with moving GUI animations.
Now, I know that unscaled time is the key to solving this issue, but every explanation I've found online seems to involve the Animator which refuses to work with the legacy? animations.  Either that, or the code they're using makes little sense to me because it may be above my level of comprehension.  Here is what I have as it stands (*note that I have some deltaTime and _lastframetime code but I have no idea how to make use of it):

// Update is called once per frame
void Update () {
    deltaTime = Time.realtimeSinceStartup - _lastframetime;
    _lastframetime = Time.realtimeSinceStartup;

    //Press T or Tab to pause the game
    if (Input.GetKeyDown(KeyCode.T) || Input.GetKeyDown(KeyCode.Tab)) {
        //If not currently paused, then stop time and show the GUI
        if (!pauseGame) {
            Debug.Log("Tab/T properly pressed to pause game.");
            pauseGame = true;
            showGUI = true;
            StartCoroutine(Wait(.333f)); //IEnumerator Wait, then stops
        }else if (pauseGame){
            Debug.Log("Tab/T properly pressed to UNpause game.");
            Time.timeScale = 1;
            pauseGame = false;
            showGUI = false;
        }

        //If we are to show the GUI, play the start animation; otherwise, the exit one
        if (showGUI == true) {
            //startMenuCanvas.animation.
            startMenuCanvas.animation.Play ("pause_menu_anim1");
        } else {
            startMenuCanvas.animation.Play ("pause_menu_anim1_exit");
        }
    }
}

IEnumerator Wait(float seconds){
    Debug.Log ("Waited for " + seconds + " seconds.");
    yield return new WaitForSeconds(seconds);
    Time.timeScale = 0;
}

Ideally, I want to remove the IEnumerator and be able to call the Play animations using unscaled time.  Is there any simple way to do this that I am missing?


texts: How can I get width and height of grouped objects in Unity3D

texts:
Is it possible to get height and width of grouped objects like this?

I tried boxcollider2d.bounds and renderer.bounds. Each shapes in the group has collider component.

Is it possible?


texts: Does XNA/MonoGame have a text caching mechanism, or has an open source one been implemented?

texts:
I'm playing around with MonoGame, and I've noticed the SpriteFont class draws static text very inefficiently. Each time the text is drawn the spacing is recalculated. This isn't a big deal on my quad core PC, but on mobile applications it might be a problem.

Before I go and program some text which caches the arrangement of its letters in an array and then feeds that array to the SpriteBatch, I would like to make sure there isn't something available to do this already, either in MonoGame itself or a class someone has implemented and made available for general use.


texts: Why is the player not resting in the center of the camera?

texts:
Is it possible to create a combination of the following two cameras described in Andrew Russell's answer? XNA Platformer Sample: Supporting multiple resolutions?

I want to implement a scrolling camera that is focused on the player. In addition, I want to scale the viewport, so that the game looks on every resolution the same.

I already tried to combine the two cameras, but the player is not resting in the center of the screen. Currently scaling the viewport to any resolution higher than 800×480 de-centers the character. The character moves out of the viewport after a while.

My code:

Vector2 vp, gameWorldSize = new Vector2(800, 480);
Matrix camera;
float ScaleX, ScaleY, Scale;
float TranslateX, TranslateY;

ScaleX = vp.X / gameWorldSize.X;
ScaleY = vp.Y / gameWorldSize.Y;
Scale = Math.Min(ScaleX, ScaleY);

TranslateX = (vp.X - (gameWorldSize.X * Scale)) / 2f - player.Playerposition.X + gameWorldSize.X / 2;
TranslateY = (vp.Y - (gameWorldSize.Y * Scale)) / 2f - player.Playerposition.Y + gameWorldSize.Y / 2;

camera = Matrix.CreateScale(Scale, Scale, 1) * Matrix.CreateTranslation(TranslateX, TranslateY, 0);

What is wrong? Is it not possible to combine the two cameras?


texts: How to detect line break in a String using UnityScript?

texts:
Code:

var i:int=0;
var text:String;
var compare:String="";
var isFound:boolean=false;
function Start(){
text=AssetDatabase.LoadAssetAtPath("Assets/words.txt",TextAsset).text;
}

function Update(){
    if(!found)
   com("textToSearch");
  }

 function com(s:String){
    if(i<text.Length){
    comText=comText+text[i];
    if(//condition for line break)
    if(comText==s){
       print("found");
       found=true;
    }
   else{
         comText="";
      }
   i++;
   }

 }

In the text document each word ends with a line break. So if I just found a condition for a line break then I can easily search through the document.


texts: How to compose a matrix to perform isometric (dimetric) projection of a world coordinate?

texts:
I have a 2D unit vector containing a world coordinate (the player's direction), and I want to convert that to screen coordinates (classic isometric tiles).

I'm aware I can achieve this by rotating around the relevant axis but I want to see and understand how to do this using a purely matrix approach? Partly because I'm learning 'modern OpenGL' (v2+) and partly because I will want to use this same technique for other things so need a solid understanding and my math ability is a little lacking.

If needed my screen's coordinate system has it's origin at top left with +x & +y pointing right and down respectively. Also, my vertex positions are converted to the NDC range in my vertex shader if that's relevant.

Language is C++ with no supporting libraries.


texts: What's the difference between a game engine and a physics engine? How do they work together, and what's the meeting point between them?


texts:
As a developer I'm used to Subversion for source control and I think it's great for sharing source code between developers.

Now thinking about my graphists and game designers, they need to have a slightly different approach I think.

They need to share binary files
They need to be able to have a thumbnail and preview of their work
I don't want to include their binaries into my game repository (would be much too heavy for developer when updating)

I've seen that some graphists uses personally created website to share their work but I was wondering if some "standard" application existed in order to provide my graphists a cool way of working together.

Is there a common way of dealing with this? Is the way I want to do (only final sprites on my game repo) correct? How do you guys do this as game developers?


texts: Move a ball horizontally left and right but restricting forwards and backwards motion unity 2d

texts:
I am trying to develop an endless runner where there is a sphere as the player and it is moving left and right following the position of a finger on a touch screen. However, when I try to do this I cannot get the player to lock on the Y-axis. I want a constant force that speeds up overtime which I have using the constant force 2d supplied by unity. I have two versions of code, the first follows the finger but the player is able to move up and down as well:

using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour
{
    public GameObject character;
    public float speed = 500.0f;

    void Start()
    {
        Input.multiTouchEnabled = false;
    }

    void Update()
    {
        if (Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Moved)
        {
            Vector2 target = Camera.main.ScreenToWorldPoint(
                              new Vector2(Input.mousePosition.x, Input.mousePosition.y));
            character.transform.Translate(Vector3.MoveTowards(character.transform.position,
                              target, speed * Time.deltaTime) - character.transform.position);
    }
}

The second code I have allows the player to move left and right by tapping rather than following but is still sloppy:

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

public class PlayerMovement : MonoBehaviour
{
    public Rigidbody2D rb;

    public float sidewaysForce = 500f;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        {
            foreach (Touch touch in Input.touches)
            {
                if (touch.position.x < Screen.width / 2)
                {
                    rb.velocity = new Vector2(sidewaysForce * -1, rb.velocity.y);
                }
                if (touch.position.x > Screen.width / 2)
                {
                    rb.velocity = new Vector2(sidewaysForce * +1, rb.velocity.y);
                }
            }
        }
    }
}

Any help on this would be awesome Thanks!!!


texts: TMP Square Characters when adding Chinese

texts: I'm trying to implement Chinese language in my app. But I'm seeing nothing but squares. I've tried to create from file and hex. They can't be added. For example, there are 3000 letters but only 17 are included.


texts: Changing motion clips via script in Unity

texts: is there a way in Unity to access the Motion clip of an Animator State and change it at runtime via script? I am trying to do a character shop in my 2D game. My idea is, when i click a GUI button it would just select different motion clips but the states would stay the same. It's just a simple Jump and Idle state, parameters dont change. I just want to feed in different animation clips for different characters.


texts:
I've got five sounds now for a game I'm working on currently. In the game, you can fight against other civilizations in big battles, but you can also settle on planets in peace.

Some of the songs are more violent, while others are quite peaceful. The question is: what is the best practice for changing between the songs. Is it better if I just look "is it peaceful or not" when the old song ends and then play a new one or should I do that every single frame and change the songs immediately.

The first alternative would sometimes play silent songs in battles (because the song started before the battle and isn't finished yet) and the second one would switch between to different-fast songs properly at the wrong moments so the player would hear a cut.

So I'd like to know what is more natural for the player or if there is a different possibility.

PS: The songs are between 300 and 500 seconds long.


texts:
How can I make a progress bar appear in Unity that doesn't make use of the OnGUI functionality in C#?

I'm doing something with an Oculus and the OnGUI stuff doesn't work too well in a stereoscopic setting. I'm open to hear suggestions or try code samples as I can't seem to think of a way to display this in Unity and every google search brings up OnGUI examples.


texts: Points on lines where the two lines are the closest together

texts:
I'm trying to find the points on two lines where the two lines are the closest. I've implemented the following method (Points and Vectors are as you'd expect, and a Line consists of a Point on the line and a non-normalized direction Vector from that point):

void CDClosestPointsOnTwoLines(Line line1, Line line2, Point* closestPoints)
{
    closestPoints[0] = line1.pointOnLine;
    closestPoints[1] = line2.pointOnLine;

    Vector d1 = line1.direction;
    Vector d2 = line2.direction;

    float a = d1.dot(d1);
    float b = d1.dot(d2);
    float e = d2.dot(d2);

    float d = a*e - b*b;
    if (d != 0) // If the two lines are not parallel.
    {
        Vector r = Vector(line1.pointOnLine) - Vector(line2.pointOnLine);
        float c = d1.dot(r);
        float f = d2.dot(r);

        float s = (b*f - c*e) / d;
        float t = (a*f - b*c) / d;
        closestPoints[0] = line1.positionOnLine(s);
        closestPoints[1] = line2.positionOnLine(t);
    }
    else
    {
        printf("Lines were parallel.\n");
    }
}

I'm using OpenGL to draw three lines that move around the world, the third of which should be the line that most closely connects the other two lines, the two end points of which are calculated using this function.

The problem is that the first point of closestPoints after this function is called will lie on line1, but the second point won't lie on line2, let alone at the closest point on line2! I've checked over the function many times but I can't see where the mistake in my implementation is. I've checked my dot product function, scalar multiplication, subtraction, positionOnLine() etc. etc. So my assumption is that the problem is within this method implementation.

If it helps to find the answer, this is function supposed to be an implementation of section 5.1.8 from 'Real-Time Collision Detection' by Christer Ericson.

Many thanks for any help!


texts: Unity generates bad mipmap, making voxel terrains look bad

texts:
It's just a dirt terrain with grass blocks on the top. (which are just dirt blocks with green tops.)

I sampled a Unity terrain's heightmap, and constructed a voxel terrain based on it, and divided it into chunks, whose meshes then were combined.

Sadly the generated mipmaps are bad, the mipmap change is easily noticeable: first the shade of green changes, then it fully becomes dirt colored.


texts: Alternative to Rotation degrees or clock facing to describe cards angle

texts:
I'm working on some ideas for a system and hit a minor roadblock.

I would like to identify the angle of a card placed on a playing field. Besides a clock facing identification (3:00 would be a landscape position) or degrees (90 degrees would be a landscape position) are there any other terms that can be used to describe this angle?

I would like to find a different terminology for telling players (in the rules) to turn their cards to a landscape position, or portrait, etc. This may be unanswerable, but I could swear I have heard someone refer to an angle in an engineering environment that wasn't degrees or clock facings.


texts: Flash saves in Windows, not in Linux, FileReference.save()

texts:
The code below compiles fine on the Flex 4 SDK on Fedora 15.  Mouse-click opens the dialog box, I click okay, and a file is saved, but the file is empty.  I run the same SWF file (that was compiled on the Linux machine) on a Windows machine, and the created file contains the expected data.

Then I broke the FileReference declaration out of the function into the class level, hoping to avoid a known bug and to keep a reference to the file alive outside the function.  However, the same problem persists.

Hoping to set up a workaround, I added the debug Flash player to my path and ran the file from Flash without the benefit of the browser, and it works.  So now a Flex problem has become a Firefox problem, maybe owing to a shady procedure I used to install the plugin without really understanding what was happening.  I am running Firefox 5.0.

In essence my workflow is fixed, but perhaps people who performed the above will not be able to use projects with FileReference.save()?  Should I be worried about this edge case?

/*
WriteTheFile.as
Original code by Brian Hodge
Test to see if ActionScript/Flash can write files
*/
package{
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.MouseEvent;
    import flash.utils.ByteArray;
    import flash.net.FileReference;

    public class WriteTheFile extends Sprite
    {
        private var _xml:String;
        private var fr:FileReference;

        public function WriteTheFile():void
        {
            if (stage) init();
            else addEventListener(Event.ADDED_TO_STAGE, init);
        }

        private function init(e:Event = null):void
        {
            removeEventListener(Event.ADDED_TO_STAGE, init);
            //Calling the save method requires user interaction and Flash Player 10
            stage.addEventListener(MouseEvent.MOUSE_DOWN, _onMouseDown);
        }
        private function _onMouseDown(e:MouseEvent):void
        {
            fr = new FileReference()
            fr.save("<xml><test>data</test></xml>", "filename.txt");
        }
    }
}

EDIT: addressed answer in code above, but the same problem exists.

EDIT: This works on the same system when the standalone player is invoked.  Therefore this is a browser (FF 5.0) plugin problem.


texts: Unity - Copy another object's Y location?

texts:
I'm creating a Pong clone inside of Unity and was trying to figure how to copy another object (In this case being the Y co-od of the Ball Object) How would i go about doing this? I'm using vectors as my method of paddle movement and I want to create a public int AISpeed so that the AI paddle is a little slower in comparison

In my mind I assumed it was along the lines of:
rightPaddle.location.y = pongBall.location.y

How would I create this?


texts: Is there something like a "real-action-to-3D" filter?

texts:
I recently watched the cutscenes of Call of Duty WWII and was very impressed with the graphics, especially the facial expressions and the creases in the clothing. This is, of course, pre-rendered material and not actual ingame footage.
After doing some research I found that they used real actors for the scenes (Josh Duhamel, Jonathan Tucker, ...) and filmed the scenes like it was a real-action movie.

This got my wondering if there is some kind of "filter", the turns real-action footage into something that looks like it is entirely computer generated?

So basically instead of going bottom-up and trying to make the 3D model look as realistic as possible, going top-down and alter real-action footage in a way that it looks like a 3D model.

Is this done?

Clarification: I am not referring to motion capture, at least I think I am not. I am not talking about filming facial expressions and applying the mechanics to 3D models, but rather taking the whole film and just put a filter on it to make it look 3D.


texts: How does CharacterMovementComponent::PerformMovement work?

texts:
I'm developing an adventure platformer. As such, the manipulation etc. of the CharacterMovementComponent is going to be crucial to the game.

I have seen the more top level explanations of the MovementComponent however none of them provide any insight into how PerformMovement is coded.

I'm trying to work through it and understand it myself, however as i'm not completely familiar with the component, it's a little hard for me to understand.

So I was wondering if anyone on here knew anything about this MovementComponent, could tell me how the function really works, or could point me in the right direction for the development of our movement systems.


texts:
I am trying to compare two strings in C# but even though I print the strings and they are the same, the check always fails.
Only one is stored in a variable and the other is hardcoded.
I tried using the ==operator and the equals operator.
Also tried with using the IgnoreCase StringComparisonoption but still nothing. I also checked the length of the string in case there are leading or following spaces or something but it's the same. IF it is any help the string is coming from GlovePIE

What could be going wrong?


texts: High Frequency Polling And Handling Fuzzy Inputs

texts: I'm developing a FPS game and I'm considering polling at a high frequency on a separate thread. This decouples the game loop and reading input. I get sub-frame samples and can process those samples from a queue. My question is about determinism. I want to drive input handling with a variation of a state machine or DPDA. These things are not known for "fuzzy-friendliness" so I need to filter dequeued inputs (in the signal processing sense). How do real games implement high frequency input handling?


texts:
I want to give the value of a camber to the wheel collider my game. When the car stops, there is no problem visually, but as the wheel rotates, the wheel makes odd rotational movements together with the value of camber.
foreach (var axle in axles){
    Vector3 pos;
    Quaternion rot;
    axle.wheel.GetWorldPose(out pos, out rot);
    axle.tire.position = pos;
    axle.tire.Rotate(axle.wheel.rpm / 60 * 360 * Time.deltaTime, 0, (camperValue * camperFactor));
    axle.tire.localEulerAngles = new Vector3(
         axle.tire.localEulerAngles.x,
         axle.wheel.steerAngle - axle.tire.localEulerAngles.z,
         axle.tire.localEulerAngles.z);

    axle.wheel.motorTorque = 300 * Input.GetAxis("Vertical");
    if (axle.index < 2)
        axle.wheel.steerAngle = 30 * Input.GetAxis("Horizontal");

    axle.wheel.brakeTorque = 1000 * (Input.GetKey(KeyCode.Space) ? 1 : 0);
}


texts: Ways to track login/loading progress dynamic?

texts:
Lets say we want to add a dynamic "loading bar" to our server-client game... the player presses on "login", a bar appears and shows the percentage of loaded assets and configurations from the server.

The only way i found... is very laborious and hardcoded :

// We received our environment
barPercentage += 10f; // Increasing the bar.
updateBar();

// We received our player settings
barPercentage += 5f; // Increasing the bar again
updateBar();

As you can see this progress tracking from received server data is very bad and needs to be adjusted everytime you change some important part of the game structure itself.

What are good ways to implement such a percentage tracker client side ? How do we actually track the loading progress (client & server related) without hardcoding it like i did in the code sample ? Are there any good patterns or data structures ?


texts: Which algorithm for controlling cars on a race track?

texts:
I think A* is a good place to start, but since cars cannot move in all directions (they move like cars do, trying to move forward and steer), I was wondering if someone could point me at other approaches they've used.

Also, I was wondering about the "Racing Line". Should one just precompute the optimal paths, and then use the A* to select the path that isn't blocked by other cars ?

EDIT: My question is different from Driver AI in racing game because that question is about approaches.

I am interested in learning about specific tried and trusted algorithms like A*.


texts:
I want to build a quest system in PHP. My idea so far was to create quests based on a class and write two functions for every quest: One is checking if its activated, the other will check the progress.

Since I have to do this on every page reload, this might be bad performance-wise. Is it possibleto build some kind of an event/push system with PHP? How would you do it? Yes, when something happens like the users buys something, a function gets called with for example "CAR_BOUGHT_BY_PLAYER".

My problem is, I don't know how to go on from there.
Any advice?

Thanks!


texts:
the simple way to explain it is an image

I want to have a black background and to show only a small area around player. Which way I have to look? I have no clue where to start searching :)

Thanks.


texts: Im making a project proposal for a game whose gameplay involves endless road where player just has to dodge obstacles but it also has time limit. Its as if temple run but can only be played for certain time limit and you have to make as high score as possible within that time. Temple run can be called as "endless runner" game but if it had time what would it be called. I want to know how would you describe this game type in one or two words? As in "first-person-shooter" or "Racing" etc??


texts: What are some cool examples of procedural pixel shader effects?

texts:
What are some good examples of procedural or screen-space pixel shader effects? No code is necessary; I'm just looking for inspiration.

In particular, I'm looking for effects that are not dependent on geometry or the rest of the scene (so they would look okay rendered alone on a quad) and are not based on image processing (they don't require a "base image," though they can incorporate textures). Multi-pass or single-pass is fine. Screenshots or videos would be ideal, but ideas work too.

Here are a few examples of what I'm looking for (all from the RenderMonkey samples):
alt text http://public.blu.livefilestore.com/y1pXcNg_0EPZVzwu1T84a4Yek373x8062rhrNCA7UcftTjCkeiY-5uAuJiBYY29x2E53p5MO-uMA8FmEquvxsPCkA/effect1.jpg?psid=1alt text http://public.blu.livefilestore.com/y1p_5Lx7BdjFyFRBkbcc0WakAT7Q-99fVcFOxmTXBbG4VtoFzC0UfAj51eSnE7ZOD84EYL2Y51HhMS2nWsohhn1mQ/effect2.jpg?psid=1
alt text http://public.blu.livefilestore.com/y1p_5Lx7BdjFyE3KhYtHe-Cdg7XuXcJ9Ou-GKzED-kZnzACyB5ypA6NSCfsYfuKa0h3ztoDRwwq9qBddX2OfG0fhg/effect3.jpg?psid=1alt text http://nv3wrg.blu.livefilestore.com/y1p1iHFwf-wytDo8HlTJca8RfckA-iTKgvLiJm0t9iz3S35YgeEnt99NMjKDgotxa3Bv90wAhOYLabzx2Sd3LoEH2Hs76WR1vFM/effect5.jpg?psid=1

I'm aware of this question; I'm not asking for a source of actual shader implementations but instead for some inspirational ideas -- and the ones at the NVIDIA Shader Library mostly require a scene or are image processing effects.


texts:
I'm curious what are the best practices in game development industry to render 3d universe?

To be more specific:

The data points are given and static. Each point has position, color and size;
The entire data set is much larger than available memory;
User should be able to "zoom out" to see bigger picture at once;

The most naive approach would be to split universe into cubes and render only what's visible. I'm not sure how in this scenario should I implement the "zoom out". Should I precompute cubes for each possible zoom level? Or maybe there are better approaches?

I'm looking for technology agnostic solution.


texts: How to make an irregular shape that displays how far a unit can move through the map?

texts:
I'm still new to programming, and I was wondering if there is a way to make an irregular shape that displays how far a unit can move through the map taking in account pathing around obstacles. For example, as shown in the overworld of Total War:

I do not want to brute force it by checking every pixel that is in range as that's probably too slow to do in the game maker engine.

The pathing uses the mp_grid of game maker which I heard is A* (but I don't really know what that means or how it affects what I want to accomplish).

Is there a way to get a similar thing in a 2D space, but not necessarily as precise?


texts: How would I create classes for each map tile instead of using a tmx? LibGdx

texts:
I am making a top down style game using LibGdx that I want to be randomly generated each new game load.

I already have the algorithm to generate the array for what tile should be what.

But i'm stuck on how I should handle the tile classes.

I have this class called Tile

import com.badlogic.gdx.graphics.g2d.Sprite;

public class Tile extends Sprite{ // Should I use sprite??? Seems wrong..

public byte id;

public static Tile[] tiles = new Tile[256];

public static Tile grass = new GrassTile(0);

public Tile(int id) {
    this.id = (byte) id;
    if (tiles[id] != null)
        throw new RuntimeException("Tile Already Exists....");
    tiles[id] = this;
}

}

And I want to have multiple classes that exened this class for each tile. For example this is grass.

import com.badlogic.gdx.graphics.g2d.Sprite;

public class Tile extends Sprite{

public byte id;

public static Tile[] tiles = new Tile[256];

public static Tile grass = new GrassTile(0);

public Tile(int id) {
    this.id = (byte) id;
    if (tiles[id] != null)
        throw new RuntimeException("Tile Already Exists....");
    tiles[id] = this;
}

}

Should these classes be extended off of a sprite? Or some other class from libgdx?

Also These tiles are going to be 16 x 16 that are made up of 4 smaller 8x8 sprites.


texts:
I'm looking for a faster solution that will allow me to load objects faster with
OpenGL and currently when trying to load, parse and pass the data on my main thread it takes a while... Would multi-threading be a reasonable solution to this and if so, how would I go about it?

Would I make a second thread with the same context and save the data once it has loaded or...

Would I create a second thread to load and parse the data, then pass it back to the first thread to save to the GPU?

This is the limit of my knowledge of this subject at the minute, if anyone has any better solutions please drop me a comment.


texts: C++ - what is the best library that I can use to create GUI if a textview already exists

texts:
I have a 2D char array in the textView.Basically,I need to map each char to a texture and render the whole view. Given a limited time, what is the possible best library that I can use?

The header for the text view is

    class TextView {
    char **theMap;
    std::string race;
    int gold;
    int flr;
    int hp;
    int atk;
    int def;
    std::string action;
    std::string pendingAction;
public:
    TextView();
    void update(int x, int y, char c);

    // for the rest of the methods, notice that it takes
    // the NEW VALUE rather than the CHANGE as its parameter
    void updateGold(int newValue);
    void updateHp(int newValue);
    void updateAtk(int newValue);
    void updateDef(int newValue);
    void updateFlr(int newValue);
    void updateRace(std::string newValue);
    void updateAction(std::string newValue);

    void print(); // just print to cout, rather than give a reference to a ostream
    ~TextView();
};


texts: The most efficent ways for drawing lines all day long with OpenGL

texts:
I'd like to put a computer screen that is running an OpenGL programs in a room. It has to run all day long (not in the night).

I'd like to draw lines that are slowly fading in the background. The setting is simple: a uniform color background (say, black) and colored lines (say, white) that are slowly fading out.

With slowly I mean.. hours. Say that the first line I draw is with alpha 255 (fully visible), after one hours is 240. After 10 hours is 105.

One line could have 250 points and there will be like 300 line in one day.

For now I have done a prototype with very rudimentary method like:

glBegin( GL_LINE_STRIP );
iterator = point_list.begin();
for (++iterator, end = point_list.end(); iterator != end; ++iterator) {
    const Vec3D &v = *iterator;
    glVertex2f(v.x(), v.y());
}
glEnd();

More efficient method?


texts:
I've been wondering how you would go about labeling an area on a 2D tile map. What I'd like to do is associate tiles with an area i.e Forest Area, Desert Area, etc.

Keep in mind this is an idea, so far I've been thinking that one way to go about this is to have each area store tile positions as the pivot points and you need at least four of these pivot points before it is a valid area. This way would allow for some of the granularity I would like as my first idea was to just associate every tile with an area id, which is pretty inefficient time-wise, though the task would have been alleviated somewhat with a map editor that I am going to build (i.e. just paint a tile with an area color/number).

What are your ideas on this?

Also, the map, areas, and etc will be stored in an sql database FYI.


texts: Get component that has specified method by Reflection API

texts:
Let's say that I have a component like this:

public class MyComponent: MonoBehaviour {
    public void MyMethod(int param1, int param2) {
        Debug.Log(param1 + " " + param2);
    }
}

And I have a string variable that has method name from that class.

string methodName = "MyMethod";

I need to invoke MyComponent.MyMethod with reflection api, however I don't know how to distinguish component that has "MyMethod".

MonoBehaviour[] scripts = target.GetComponents<MonoBehaviour>();

// Find the component that has method
for(int j = 0; j < scripts.Length; j++) {
    ... ??? ...
}

methodInfo.Invoke(target.gameObject, parameters);
hasFound = true;

If I just invoke with gameObject, of course it fails. So I have to get the component to use Invoke. In this case, how do I get the component that has specified method by Reflection?


texts: Why do all my matrices end up with the same values in this code?

texts:
My programme reads a binary file. For that I made a Dictionary<int, float[]> where int is order number (ID) and float[] is an array of important values.
Here's my code how I read the binary file to my dictionary:

        inv_bind_mats = new Dictionary<int, float[]>();
        float[] Farr = new float[16];

        string path2 = Application.StartupPath + "\\skeletons\\" + skeletonName + ".bone_inv_trans_mats";
        using (BinaryReader inv_trans_mats = new BinaryReader(File.Open(path2, FileMode.Open, FileAccess.Read, FileShare.Read), Encoding.ASCII))
        {
            inv_trans_mats.BaseStream.Seek(4, SeekOrigin.Begin);
            bonesCount = inv_trans_mats.ReadUInt32();
            for (int i = 0; i < bonesCount; i++)
            {
                for (int j = 0; j < 16; j++)
                {
                    if (j < 12)
                    {
                        Farr[j] = inv_trans_mats.ReadSingle();
                    }
                    else if (j >= 12)
                    {
                        Farr[j] = 0.0f;
                    }
                }
                inv_bind_mats.Add(i, Farr);
            }
        }

It doesn't matter which ID I choose all float[] values are same for each.
This binary file is an inverse matrix of skeleton bones.
Each bone has 12 float values when I need to get 16 so I just add 4 more '0' values to what I get from file.

But the problem is all float values from inv_bind_mats[i][0-16] to inv_bind_mats[i][0-16] are equal.

How I want it to work: each bone has it's own matrix (float array) instead of one matrix for all bones.


texts: Networking Client Server Packet logic (How they communicate)

texts:
I want to know what is the logic behind server client communication through packets for a real time game.
for example the server sends x packets then the client receives x packets and processes them..

Basically what is the process to keep the client and server in sync and able to receive and send packets.

more in depth example of what I want to know:

client

step 1 wait for a packet

step 2 read x packets

step 3 process x packets

step 4 send x packets

and so on...

I need to know the very basic outline of the communication.

Big questions are:

1) do I send and read packets all at one time? i.e for loop though the incoming packets array list and read them all or one every server loop or what...

2) what order should I do things i.e first receive then read then process then send etc..

3) what I asked above a step by step of what the server / client should do..

Thanks!


texts: Given a grid system where some coordinates are marked as impassable, how to find natural-looking car driving path between two locations?

texts:
I can compute an A* path, but I get only cardinal directions from that.   A 45˚ path would look like "up 1 left 1 up 1 left 1 up 1 left 1..."

My specific question is, given a grid with a pathing solution involving non-90˚ paths, how do you figure out those paths?

I have curves working as described here: https://gamedev.stackexchange.com/a/121016/66189

but I just don't know how to combine it with areas that block the path.  I've seen a little bit about "pulling the string", but very little detail.

Another issue I have is that A* will suggest that I immediately go "backwards" for the facing of my car or take way too sharp of a turn.

edit:  How do I make sure I get the blue line, not the red line, which is unusable, even though A* loves it:

The issue I'm seeing here is that a block that isn't usable on the red path is usable for the blue path -- but A* would mark it as unusable or as having a very bad score when checking the red path.


texts:
I have been dabling in game development since I started programming, but never very seriously. I work as a business app developer, but I'm working on some games in my spare time.

In the business world (on the Microsft web-dev stack) ASP.NET MVC is becoming really popular, because of its ease of unit-testing the way the interface works.

I'm wondering what design patterns (MVC, MVP, MVVM, etc) one could use to write a game in which all of the game logic is easily unit-testable. Is this possible or feasible? Am I wasting my time, is it better to do full builds and then run "integration" type tests instead of unit-tests?

Sample code would be great, but a writeup is also useful.

(I tried to add a unit-testing tag, but don't have the rep required...)


texts: How can I use graph traversal to generate a round region?

texts:
I was playing a tile-based game and noticed it used what appeared to be a circular shape for the light sources.

How can I generate something similar?

My understanding of cellular automata is that each cell's value is generated based on its neighbours. I had always assumed that every node had to have the exact same behavior, but it looks like the 4's have different behavior.


texts:
My Players experience crashes on older computers when they enter a scene with a lots of 3d models.

Is there anything I can do to avoid this, except deleting those models from the scene?


texts:
I know there are some questions to this topic, but i didnt find a
satisfying answer for my problem yet.

I'm learning to use libgdx right now, and I'm not sure about handling different screen resolutions. I can use Viewports and a Camera of course, to fit the content
to the screen. But - how do i achieve, that my game doesnt appear kind of stretched if a device has a different resolution?

For example: Do you know the game Clash Royale? It feels like this game looks the same on all devices with every different resolution and screen size.
How do they do this?

Thank you.


texts: Create a custom shape from a basic shape

texts:
Is it possible to create a custom shape by modifying one of the regular 3D objects in Unity3D 5.1?

For an example:
Make a cone from cylinder.


texts: So I applied  the baked texture (on the right side of screen shot) but it shows in this manner. What is the problem? I made the model in Blender and also the baked image. The house consists of multiple separate objects.


texts: Should I rotate the Camera using the View or World?

texts: I have an issue with roll/rotation. I have a Camera defined to move along X and Y axis at a given Z for zoom. The camera is always pointed straight down the Z axis so there is not any yaw or pitch. I do however need to roll or rotate. The problem I have is that when I roll/rotate left or right I am modifying up in the view. So, when the mouse or keyboard are moved up toward the top, the target actually moves toward the new up. If I rotate 90 right degrees when I move mouse up or arrow up it moves right. I fully understand why it is behaving this way. I need to find a way to make it not behave that way. I need to roll/rotate independent of x, y. My first thought is to use the view when moving camera along x and y. Then rotate the target (1-9 quads) in the world space. Any thoughts on this? Any Examples would help and would be greatly appreciated.


texts:
I.e. can I do this:

XMMATRIX dxMat;
Matrix myMat;
std::memcpy(&myMat, &dxMat, sizeof(XMMATRIX));
std::memcpy(&dxMat, &myMat, sizeof(XMMATRIX));

Matrix is my own class which contains 16 contiguous float variables (only). Also can I do the same with my vector class (4 floats) and XMVECTOR?

In other words, is XMMATRIX a POD?


texts:
I started a directX 12 universal app project on visual studios and started coding some stuff to create a physics engine. I was currently working on implmenting Assimp into the engine too load whatever 3d models I want. I believe I set the Assimp up incorrectly somehow. The code for loading the models worked on my last project with dx11 (non universal app). I will add the code anyways.

Mesh mesh;
// Create assimp importer to load the file
Assimp::Importer importer;
const aiScene* aiscene = importer.ReadFile(contentDirPath + filePath, aiProcess_OptimizeMeshes
    | aiProcess_PreTransformVertices
    | aiProcess_Triangulate
    | aiProcess_GenSmoothNormals
    | aiProcess_FlipUVs
    | aiProcess_OptimizeGraph
    | aiProcess_LimitBoneWeights);

// Append filePath to use file name as mesh name
mesh.name = filePath.substr(0, filePath.size());
mesh.name = mesh.name.substr(0, mesh.name.size() - 4);

for (UINT i = 0; i < aiscene->mNumMeshes; i++)
{
    // Set the size of indices and vertices
    mesh.vertices.resize(aiscene->mMeshes[i][0].mNumVertices);
    mesh.indices.resize(aiscene->mMeshes[i][0].mNumVertices);

    // Iterate through vertices
    for (UINT j = 0; j < aiscene->mMeshes[i][0].mNumVertices; j++)
    {
        if (aiscene->mMeshes[i][0].HasPositions())
            mesh.vertices[j].pos = XMFLOAT3(aiscene->mMeshes[i][0].mVertices[j].x, aiscene->mMeshes[i][0].mVertices[j].y, aiscene->mMeshes[i][0].mVertices[j].z);

        mesh.indices[j] = j;
    }
}

Now I think it has something to do with setting up the project. I went to Project->Properties->VC++Directories and in Executable, Include, & Library I added Assimp\bin, Assimp\include, and Assimp\lib respectively. Then in Project->Properties->Linker->Input->Additional Dependencies I added assimp.lib. I then included these into my project where needed. This is what I did for my non universal dx11 project and it worked fine.

#include <assimp\scene.h>
#include <assimp\Importer.hpp>
#include <assimp\postprocess.h>

Now when I run the program. I get this,

  "Unable to activate Windows Store app 'App name here' The 'exe name
  here' process started, but the activation request failed with error
  'The app didn't start'."

So I looked at the output and it says,

  'A dependent dll was not found'

I checked to see if there was even a dll for assimp in the bin I added, there was. I also tried moving it to where the exe was located, that didn't work either. Am I doing something wrong? Does assimp not work in universl apps? If I comment out my assimp code and rebuild it runs fine so I figured the dll it said was not found was the assimp.dll


texts:
I've just switched over to MonoGame from XNA. Since MonoGame is supposed to have the same API (implying that any copied code should work as usual), I've run into a strange issue- input doesn't seem to be handled through MonoGame.

When I tried to fix any missing "using" directives in that class, it automatically added using Microsoft.Xna.Framework.Input which implies that there's no MonoGame equivalent.

Googling the issue had no success- all the tutorials I found for MonoGame said to use XNA's input.

Is there a MonoGame equivalent for handling input, or do I just need to use XNA for that?


texts: Serialization/Deserialization Solutions for Loading & Playing Audio Files

texts:
I'm creating a music game in unity, and the first issue I encountered was that I had no way to load music into the game from a file. I tried using a WWW to load the mp3 files, but in my research I came across multiple sources that told me that this method would not work, and I was unable to get it to work in my own practice.
So, I found the Naudio library, which allowed me to convert the MP3 files to an array of floats which I then used AudioClip.SetData() to create an audio clip with. To avoid having to do this conversion every time I wished to load a new song, I thought to then serialize the converted audio data to a binary file which I would then deserialize to create a new audio clip when the song is requested, and that audio clip is then stored in a list for if I need it later during runtime.
This worked for a long time, but now I'm almost ready to ship my game and I'm realizing that the file sizes for these binary files are massive - upwards of 100MB in most cases of a 4 minute song. This is obviously unacceptable considering that the file size of a regular MP3 song of that length is less than a tenth of that.
So, I looked into using a DeflateStream when serializing and my research brought me to the DotNetZip library, which someone recompiled for use with Unity here. However, this did little to remedy my issue because 1) The compressed file sizes were smaller, but not small enough (still around 50MB for a 4-minute song), and 2) The time it takes to serialize the file skyrocketed from 3-5 seconds to upwards of 30 seconds.
Perhaps I'm looking at this problem the wrong way. Can anyone offer me some insight as to how I can load and play mp3 files at runtime?


texts: Animating a sprite character with Multiple Parts

texts: I'm trying to animate a 2D character with interchangable parts. Right now, I have each part nested in a general part that is in turn nested in an overall parent like so; Player->Heads->Head1. I have a Controller for each part made and I feel like I should be able to pass the parameters from the Player's animator all the way to Head1's animator as they have the same parameters. I'm not quite sure how to tackle this. Using C#


texts: In Box2dFlash my b2body gets detached from my Sprite after I use setXForm()

texts:
I have a scenario where I have red coin in a Carrom board game which should be moved outside of the visible window when it is pocketed, also if any coin either white or black is not pocketed in the next shot, the red coin should be replaced in the center of the board.

Now my problem is WHEN I apply the setXForm() method to move the b2body of the red coin outside of the visible area of my flash window.It moves,there is no problem in moving the body,but WHEN i replace the b2body and sprite after the event of no coin falling , the b2body is detached and works as a separate entity having no connection with the sprite of the red coin.

I'm not getting a clue as to what is happening, that is why I thought I'd try posting this here.


texts: In my cocos2d app I am trying to make images fall from the top of the screen and detect when they are pressed. I am having a hard time. Can anyone help me achieve this? Thanks.


texts: How can I draw lines and curves on a canvas that's not rendered?

texts:
I need to draw lines and curves on a canvas that is not rendered on the screen but just updates the array of pixels that would otherwise be rendered. I need this to separate my game engine from my renderer.

This has proven rather difficult for my case because I don't use sprites that are loaded, but I draw lines and curves on a canvas.

I have used the p5.js library to accomplish my game, but p5 doesn't let you work without a "setup()" and "draw()" function. I don't want any draw loop or something because that beats the purpose of separating my game engine from my rendering.

I want to use p5 to render after I have all my game logic separate and I can just call nextFrame() or something from my game logic inside draw() in a constant 60 fps.

In p5 it is possible to createGraphics() which works outside of the canvas and doesn't have to render but again, p5 needs a draw() loop to work.

Does anyone know how I can accomplish this?


texts:
Short Question: How do I calculate market values for different resources in the game?

Long Question:

I am building a game around the concept of resource gathering and manufacturing to gain different resources. Those resources can be traded with other players or with a "game market", meaning auto generated trades that get created on a certain time interval (undecided on the interval yet). Because it would be too complex to create different exchange rates for each pair of resources (there are currently just under 100 types of resources and plans for a few hundred in total), I have come to the conclusion that there needs to be a "game currency" (lets just call it GC for now). Each resource would have its exchange rate to GC and this exchange rate would, on a certain interval, be impacted based on what is going on in the game. How would I calculate this exchange rate or market value of a certain resource every interval? I assume different things would effect it like popularity of trading within previous interval, previous exchange rate, abundance of resource currently, etc etc. But I am not sure how to apply this methodically.

Update: Some of my concerns are around the value of a resource:

Some resources can be mined directly from the environment. Other can only be obtained from manufacturing the mined resources. Other resources may be manufactured for other manufactured resources. How do I create a stable starting point to account for these factors? Obviously manufactured resources would be worth more because they are more time consuming to create.
Should players be forced to observe the market value or place their trade requests at what ever value they desire? If the value is forced, what happens to trades after a market value changes? If the is opened ended, what stops players from gaming the market to boost or fall prices? Should I only calculate the value based on successful trades and consider that open request haven't been filled for a reason?
How do I calculate what will happen in a large multiplayer situation when the game is only in development and I only have myself and a few AI players trading? The market values could be effected differently in different situations and I don't want to be caught in a situation where I have to change game mechanics after a game in live which could potentially upset players who have figured out the predictability of the market and over night, the rules change.


texts:
I'm new to XNA and 3D game development in general.

I'm creating a puzzle game kind of similar to tetris, built with blocks. I decided to build the game in 3D since I can do some cool animations and transitions when using 3D blocks with physics etc.

However, I really do want the game to look "2D". My blocks are made up of 3D models, but I don't want that to be visible when they're not animating.

I have followed some XNA tutorials and set up my scene like this:

this.view = Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up);
            this.aspectRatio = graphics.GraphicsDevice.Viewport.AspectRatio;
            this.projection = Matrix.CreatePerspectiveFieldOfView(
                        MathHelper.ToRadians(45.0f), aspectRatio,
                        1.0f, 10000.0f);

... and it gives me a very 3D-ish look. For example, the blocks in the center of the screen looks exactly how I want them, but closer to the edges of the screen I can see the rotation and sides of them.

My guess is that I'm not after a perspective field of view, but any help on which field of view/settings to use to get a "flat" look when the blocks aren't rotated would be great!


texts: How does Minecraft compute lighting for it's non-block objects?

texts:
I was wondering how the creator of Minecraft went about lighting the objects (player and pickaxe) based on the lighting level around the player. I have implemented the ability to light the blocks around the player but I can't really think of anyway to implement with objects. Also, when I the player moves and the lighting values change will I have to rebuild it's vertexbuffers? Or is there some other way?

Any ideas?


texts: SDL and smooth transition between changed movement direction

texts:
I have an object at position (x,x). Using SDL keyboard events every time the user presses one of the arrow keys the objects is to be translated (via a glTranslatef() call for the x and y axes) by a constant factor (for example: 10).

Note: I take the top left corner of the SDL window to be my (0,0) position

Single press of left arrow key - decrease X of object by 10
Single press of right arrow key - increase X of object by 10
Single press of up arrow key - decrease Y of object by 10
Single press of down arrow key - decrease Y of object by 10

In order to allow diagonal movement I added four boolean flags (one per arrow key) that are set to true when the SDL_KEYDOWN event for the respective key is detected. After that I do the following (width and height are the size of the texture that represents my object on the screen):

if(keyLeft) {
  if(x >= 10+width/2) x -= 10;  // Check if the object doesn't go outside the window and translate
  else x = width/2;
}
if(keyRight) {
  if(x < 640-width/2) x += 10;
  else x = 640-width/2;
}
if(keyUp) {
  if(y >= 10+height/2) y -= 10;
  else y = height/2;
}
if(keyDown) {
  if(y < 480-height/2) y += 10;
  else y = 480-height/2;
}

It's working fine. The problem is that when I change the movement direction (for example from a movement in (x++,y++) to (x++,y) direction) I have to press the second key (or key combo) again in order to execute the second movement.

Any ideas how can I fix this? I realize that doing things the way I described above still results in choppy movement due to the limited movement directions, not taking factors such as speed and acceleration into account but it will do for now (prototype stage).


texts: How do I properly center Nifty GUI elements on screen?

texts:
I am new to JME3 game engine but I know Android XML GUI layouts pretty good. I have a simple layout here and I cant figure out what is wrong. Here is my XML code:

<?xml version="1.0" encoding="UTF-8"?>
<nifty xmlns="http://nifty-gui.sourceforge.net/nifty-1.3.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://nifty-gui.sourceforge.net/nifty-1.3.xsd
                   http://nifty-gui.sourceforge.net/nifty-1.3.xsd">

<useControls filename="nifty-default-controls.xml" />
<useStyles filename="nifty-default-styles.xml" />

<screen id="start" controller="com.jasoncrosby.game.farkle.gui.MenuScreenGui">
    <layer id="layer" backgroundColor="#66CD00" childLayout="center">
        <panel id="panel" align="center" valign="center" childLayout="center" visibleToMouse="true">
            <image filename="Textures/wood_floor.png" height="95%" width="95%"/>

            <panel id="panel" align="center" valign="center" childLayout="center" visibleToMouse="true">
                <text text="test" font="Interface/Fonts/Eraser.fnt"></text>
            </panel>
        </panel>
    </layer>
</screen>

Everything works well until I get to displaying the text. I have tried different alignments and tried moving the text into different panels but no matter what I do the text is never in the center of the screen. It's always in the upper left corner, so far I can only see the lower right part of the text. How can I center the text element in the center of the screen?


texts:
I found that the vertex shaders are sometimes very useful, especially because they can generate geometries and extract and use a lot of informations from just 1 image.

The problem is that my project still isn't that big and looking to bigger project or just to commercial games, seems like the vertex shaders are rarely used.

Am I wrong or the pixel shaders are much more used than the vertex shaders?

This has something to do with performance issues and compatibility issues? What about some possible bottleneck like the memory controller/CPU ?


texts: My pool balls often jump around when there are two or more balls colliding/touching

texts:
I'm working through the book 'Introduction to Game Physics with Box2D' and I've created a little pool game with the example code. Despite the name, there is NO box 2D used in this particular exercise.

The example in the book can be seen in this video by the author which only consists of the cue ball and 8-ball. This all works well.

I've written my own version from scratch (using SDL instead of DirectX), using the code in the book as a guide. When I limit it to two balls, everything works great.

When there are more than two balls, things are sometimes problematic in a way I can't predict. Breaking can be fine on one run, or it can cause the balls to 'jump' and flicker as they move presumably looking for empty space. Generally, problems occur when there are more than two balls in a collision.

I've read around and it seems that I need to perform more 'iterations' to get closer to the correct result, but the code that I'd learned will work the same regardless of the number of times it is performed - it sets the positions of any overlapping balls so that they are barely touching. I've tried changing it so it 'pushes' the balls slightly in the direction of the collision normal, with no success.

Here's the relevant code:

bool BallManager::ballBounce(Ball& ball1, Ball& ball2)
{
    float r = static_cast<float>(ball1.diameter_ + ball2.diameter_) * 0.5f;

    // Calculate direction of relative velocity.
    Vector2 v = ball2.velocity_ - ball1.velocity_;
    Vector2 vhat = v.normalized();

    // Calculate relative displacement along normal to collision tangent.
    Vector2 c = ball2.position_ - ball1.position_;

    Vector2 n = c.normalized();

    // Relative distance along normal to tangent.
    float cdotvhat = dot(c, vhat);

    // Balls don't collide, exit early.
    float discriminant = cdotvhat * cdotvhat - c.lengthSquared() + r*r;
    if (discriminant < 0.0f)
    {
        return false;
    }

    // The distance we want to move ball2 back by.
    float dist2 = cdotvhat + sqrt(discriminant);

    float relativeVelocity = 0.0f;
    if (ball2.velocity_.length() > 0.0f)
    {
        relativeVelocity = ball1.velocity_.length() / ball2.velocity_.length();
    }

    // The distance we want to move ball1 back by.
    float dist1 = dist2 * relativeVelocity;

    // Move balls in reverse direction of velocity to point of impact.
    Vector2 v1hat = ball1.velocity_.normalized();
    Vector2 v2hat = ball2.velocity_.normalized();
    ball1.position_ -= dist1 * v1hat;
    ball2.position_ -= dist2 * v2hat;

    // Adjust ball velocities after reflection.
    Vector2 vDiff = ball1.velocity_ - ball2.velocity_;
    vDiff = dot(vDiff, n) * n;
    ball1.velocity_ -= vDiff;
    ball2.velocity_ += vDiff;

    // Finally, move balls again to where they should have bounced to.
    v1hat = ball1.velocity_.normalized();
    v2hat = ball2.velocity_.normalized();
    ball1.position_ += dist1 * v1hat;
    ball2.position_ += dist2 * v2hat;

    return true;
}

At the moment I'm mainly looking for a pointer in the right direction or suggestions since I'm new to physics programming.


texts: Euler (right-handed) to Quaternion (left-handed) conversion in Unity

texts:
I'm having trouble figuring out the proper conversions from Euler angles to Quaternions. The Eulers come from BVH files, which use a right-handed coordinate system (Y is up, Z is forward) and can have any rotation order specified. The Quaternions are in Unity, which is left-handed (Y is up, Z is back).

I'm composing the Quaternions from three AngleAxis rotations, but messing up the order somewhere. So far I can't find understandable and generalized information for doing these types of conversions.

public enum AxisOrder
{
    XYZ, XZY, YXZ, YZX, ZXY, ZYX, None
}

public Quaternion EulerToQuat(Vector3 eulerAngles, AxisOrder rotationOrder)
{
    // I've tried various combinations of axis angles here, but would
    //  like to understand what's wrong rather than brute-force
    //  every combination
    var xRot = Quaternion.AngleAxis(eulerAngles.x, Vector3.left);
    var yRot = Quaternion.AngleAxis(eulerAngles.y, Vector3.down);
    var zRot = Quaternion.AngleAxis(eulerAngles.z, Vector3.back);

    switch (rotationOrder)
    {
        case AxisOrder.XYZ: return (xRot * yRot) * zRot;
        case AxisOrder.XZY: return (xRot * zRot) * yRot;
        case AxisOrder.YXZ: return (yRot * xRot) * zRot;
        case AxisOrder.YZX: return (yRot * zRot) * xRot;
        case AxisOrder.ZXY: return (zRot * xRot) * yRot;
        case AxisOrder.ZYX: return (zRot * yRot) * xRot;
    }

    return Quaternion.identity;
}

...and converting translation data like so (I believe this is working):

public static Vector3 BvhToUnityTranslation(float xPos, float yPos, float zPos)
{
    return new Vector3(xPos, yPos, -zPos);
}

If anyone can help me better understand how to conceptualize coordinate system conversions, and where I'm going wrong, I'd greatly appreciate it.


texts:
Related to my previous question (2D Terra(ria)in generation - Accidental noise) I'm stuck on understanding how the gradient function itself works (in the Accidental library).

After help on chat (thanks Jon!) I understand that upon defining the gradient, for example, Gradient(0,0,0,1), it returns a function that upon its turn would return correct values between 0 & 1 for the arguments you provide.

So calling the this function with (0,40) would give you a value back between (0,1). However, I don't understand how it would do this without knowing the outer "range".

E.g. If you'd render the gradient image that's shown on his site:

Would you do that by defining the gradient(0,0,0,1) and then calling it for each pixel? (0,1) (0,2), (50,50),...? In that case, pixel (0,200) would have to return 1, but if you'd have an image of 400 pixels high, (0,200) would have to return 0.5

And calling it with values between (0,0) & (0,1) with predefined steps (1/200 or 1/400 for example), seems to make the gradient noise function itself rather useless.

If possible, pseudo or python code would be very welcome to illustrate how the "internals" on that gradient function would work, perhaps I'm thinking of it too complex.

Thanks in advance!


texts: Problem with calculating velocity for a car with multiple gear ratios

texts:
I hope this is the right place for this but I have a problem with calculating velocity for my car game. The higher the gear, and therefore lower the gear ratio, the lower the top speed.
Given that

Acceleration = Forward Force - Drag - Rolling Resistance

Velocity += Acceleration * dt

and

Wheel Torque = Engine torque * Gearbox ratio * Differential ratio

Forward Force = Wheel Torque/Wheel Radius

I feel like I am missing something because if we decrease the gear ratio we decrease the torque and therefore the forward force causing lower acceleration so the car cannot gain additional velocity, and actually loses it due to resistive forces.


texts:
I am using the PictureBox class to create a checkerboard, and it not really working all that well. I've created the loop:

PictureBox[,] squares = new PictureBox[10,10];
        for (int i = 0; i < 10; i++)
        {
            for (int j = 0; j < 10; j++)
            {
                squares[i, j] = new PictureBox();
                squares[i,j].Image = Chess.Properties.Resources.square;
                squares[i, j].BackColor = Color.Transparent;
            }
        }

        for (int i = 0; i < 10; i++)
        {
            for(int j = 0; j < 10; j++)
            {
                squares[i, j].Location = new Point(i * 30, j * 30);
                this.Controls.Add(squares[i, j]);
            }
        }

It's supposed to create a 10x10 grid, and I added the image into the application resources. Each square is 20x20 pixels, and I loop by column. I thought it would work, but all I get is 6 images and the size just gets smaller.

Am I missing something? Or any good alternatives in creating a checkerboard without using PictureBox? Any thing with a MouseLeave, MouseHover, MouseClick, events I can use.