texts: GLES2.0 3D Android game performance and multi threading the update?

texts:
I have profiled my mixed Java\C++ Android game and I got the following result:

As you can see, the pink think is a C++ functions that updates the game. It does things like updating the logic but it mostly it generates a "request list" for rendering.
The thing is, I generate DrawLists on C++ and then send them to Java to process and draw using GLES2.0.

Since then I was able to improve update from 9ms down to about 7ms, but I would like to ask if I would benefit from multi threading the update?

As I understand from that diagram is that the function that takes the most time is the one you see it's color on the timeline. So the pink area is taken mostly by update. The other area has MainOpenGL.Handle as it's main contributor(whch is my java function), but since it's not drawn to the top of the diagram I can conclude other things are happening at the same time that use the CPU? Or even GPU stuff that isn't shown in this diagram.

I am not sure how the GPU works on this. Does it calculate stuff in parallel to the CPU? Or is it part of the CPU usage as in SoC? I am not sure.
Anyway, in case GPU things DO happen in parallel to CPU, then I would guess that if I do this C++ Update in parallel to the thread that makes the OpenGL calls, I might make use of "dead CPU time" due to GPU stalling or maybe have the GPU calls getting processed earlier because it won't have to wait for Update to finish?

How do you suggest to improve performance based on that?


texts: balloon ligher than air with libgdx, impementation of FixtureDef.density, gravityScale, linearDamping?

texts:
I use libGdx/box2d's physic. My intention is to create a balloon filled with helium (a body, what hovers above a surface, if we apply a little force to it - it moves fast but not far, if we push against a obstacle - it collide and jump back (restitution)).
I was suggested to use linearDamping or gravityScale to achieve similar behavoir.
So far I achieved a ball behavior: it hovers, it moves (not as intended, just simple move), but no restitution. Here my code:

        mBallDef = new BodyDef();
        mBallDef.type = BodyType.DynamicBody;
        mBallDef.position.set(x, y);

        mShape = new CircleShape();
        mShape.setRadius(radius);

        mFixDef = new FixtureDef();
        mFixDef.shape = mShape;
        mFixDef.density = 0.7f;
        mFixDef.friction = .5f;
        mFixDef.restitution = .8f;

        mBall = world.createBody(mBallDef);
        mBall.setActive(true);
        mBall.setAwake(true);

        mBallFix = mBall.createFixture(mFixDef);
        mBall.setGravityScale(.2f);
        mBall.setLinearDamping(5.5f);

Touch implementation (just moves a balloon up, it's for test, nothing special)

Gdx.input.setInputProcessor(new InputHandler()
    {
        @Override
        public boolean touchDown(int screenX, int screenY, int pointer, int button)
        {
            mBall.applyLinearImpulse(0, 15.5f, mBall.getWorldCenter().x + mShape.getRadius(),mBall.getWorldCenter().y - mShape.getRadius(), true);
            mBall.setAngularVelocity(0);

            return true;
        }

    });

When I use for gravity - .2f and for linearDamping - 5.5f, a ball hovers, but I loose a restitution for my balloon. The restitution is available only for linearDamping below 1.5f. And I was told that it's not good practice to keep gravity far away from 1.
My experiment with FixtureDef.density failed, changing it to various values (grom -2 to 2) has no visible effect.
The questions are:
1) What's use of density? It doesn't provide visible affect.
2) What values I should declare to create balloon ligher than air?


texts:
I was wondering how developers can give some people (like family) their paid apps for free?
Or even give paid in app purchases for free. I'm not talking about the promo codes, i believe they only last a few months?
Do they use some kind of custom developed promo code system?

Your insights are much appreciated


texts: Breaking up a 2d shape into small triangles

texts:
I have a "piece of cloth" (2d shape) that I'm applying soft-body physics to.  This works great when the shape is a square and I can create a regular grid of vertices between which are hung the cloth's "springs."  However, now I'm trying to get this to work with non-square piece of cloth, so I'd like to be able to break the polygon down into thousands of tiny triangles.  I've seen lots of libraries to tessellate or triangulate polygons, but they all seem to minimize the number of triangles created, which is exactly the opposite of what I want.

Does anyone know of a library (optimally in JS!) that breaks up a polygon into arbitrarily small chunks?  Preferably as regular as possible (i.e., creating a grid-like layout where possible), but not required.

Alternatively, does anyone know if there's a name for this, so I can just look up the algorithm and implement it myself?


texts: How can I deal with vertex precision errors between terrain chunks?

texts:
I am using OpenGL to render the following scene, using vertex data from one of the map files of a popular MMORPG. The data is chunked and the pictured scene is made up of 256 (16x16) chunks.

However between the chunks I am seeing what I believe to be glitches due to the float precision. Yet I am not doing any large translations and rendering very close to the origin, should I be seeing this problem? The glitches very noticeable as you fly over the scene with it flickering different points along the chunk edges.

I was wondering if I was overlooking something simple or there are tricks other games use to mask this problem. I guess the source data could be the reason for this problem but I am not aware of it happening in the original game.

View screenshots in a new window to see the issue.


texts:
This sounds like an easy thing but when I considering the following

Many players
Some have played many games and some just started
Different type of statistics

On what information should the actual ranking be based on? I am planning to display the board in a UITableView so there is limited space available per player. However, I am not bound to the UITableView if there is a better solution.

This is a quiz game and the information I am currently capturing per player is:

#games played totally
#games played per game type (current version have only one game type)
#questions answered
#correct answers

Maybe I should include additional information.

I have been thinking about having a leaderboard property page where the player can decide on what basis the leaderboard should display information but would like to avoid the complexity in that. However, if that is needed I will do it.

Anyone that can give me some advice on how to design the presentation of this would be highly appreciated?


texts: Implementing a build queue in a browser based game

texts:
I need to be able to execute certain events at a given time in my game, for example, say the player "Builds a building" this building should take 15mins to process. Implementing this seems straightforward enough, simply enter the event into the database and execute the event when the time comes for it to be completed.

However, it is my understanding that i would need a script that is running permanently on the server and continually checks the event database for delayed events to execute and process them as needed. My question is, is this the right approach or should i be tackling the "event que" differently?

Some of the events that will be processed can effect many different players so they would need to happen in real time, as opposed to be lazy loaded.

You can see similar such event queues in browser games such as travian, grepolis etc.

Update - If i was to implement a purely lazy load method, are there any flaws in the following pseudo code?

    ## upon player_x pages load

## start a loop that will only exit once all needed events have been processed

## check for any events initiated by player_x that are overdue

## get event and lock it for processing

    ## does this event involve another players object?

        ## if it does, then lets check if said object also has any events that should happen before this event

            ## if it has, then lets process one of those events instead, and loop again once processed

            ## if it doesnt have any previous events, then we're free to process this event, do it

## loop till all overdue events for player_x's object are done


texts: OnCollisionEnter2D and OnCollisionStay2D not detecting anything or being called unless i turn off 'Is Trigger'

texts:
I was attempting to create a simple button prompt where when you are inside a 2d box colider it will give you the option to press the button within that range, below is the short code used to test this.

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

public class ButtonScript : MonoBehaviour
{

    private void OnCollisionEnter2D(Collision2D collision)
    {
        Debug.Log("ENTER");
    }

    private void OnCollisionStay2D(Collision2D collision)
    {
        Debug.Log("Stay");
        if (collision.gameObject.tag == "Player")
        {
            Debug.Log("PLayer Detected");
            if (Input.GetKeyDown(KeyCode.E)) {
                Debug.Log("E pressed");
            }
        }
    }
}

However this does not output any Debug Messages at all. Maybe i have a misundestanding of the Is Trigger function and colliders in general but when i have it turned off it does nothing, when i have it on it acts as a box (which i dont want) but when i push againsts the box it will send out the debug messages.


texts:
I decided to give LibGDX a try and am planning to use SVN for my code repository. I created my LibGDX project via the Gradle build as outlined in the book "Learning LibGDX Game Development". I'm not quite sure how to add the project to my repository. I have tried to upload the root folder (Project below) into svn, which does contain all the sub-project, but when I check out my workspace only contains the Project folder.

Below is the structure of the project in Eclipse after the gradle build.

Project
Project-android
Project-core
Project-desktop
Project-html
Project-ios

After checking out from svn

Project

Has anyone used SVN with LibGDX, if yes can you please guide on how to add a project to repo and checkout correctly?


texts: Getting back to game page from xaml page problem. (Windows Phone 8.1)

texts:
I have implemented a xaml page where user can submit his score. I have managed to get the user to the xaml page, after 2 hours of struggling but I do not know how can I navigate the user back to the game page, because I got nothing but black screen.

This is the code, I used to navigate to submit score xaml page:

var frame = new Frame();
frame.Navigate(typeof(SubmitScoreDialog));

Window.Current.Content = frame;
Window.Current.Activate();

I used the same code, to get the user back to game page, after he submited his score, but I get that black screen, nothing is drawn ... I do not know how can I get this working.
Here is the code from SubmitScoreDialog.xaml.cs to get the user back to game page.

var frame = new Frame();
frame.Navigate(typeof(GamePage));

Window.Current.Content = frame;
Window.Current.Activate();

If anyone can provide me the working code for this problem, I will be very thankful.


texts: AC3 FlashPunk Console doesn't show anything

texts:
I am making my project using flashpunk , I knew that it has a good console gui to give feed about states of the game , however when I tried making it appear with the FP.console.enable() method it shows its dark transparent GUI but no text appears .
I though it might be something wrong with my project so I downloaded some examples and they all failed .
Here is a pic from pink example :

As you see the console displays no text while it should give feed .


texts: Unity 5.1 audio issues (no sound in back channels)

texts:
I've trying to bring in surround sound audio into my project. I've set my computer up to run in 5.1 and when I play a 6 channel audio through windows media player (it's a test audio that does left speaker, right speaker etc) it works fine.

However, when I run it through Unity, all I get is the front 3 channels. I've set it in the Edit -> project settings -> audio to be 5.1 in there. I even set it in code with following:

void Start()
{
 AudioSettings.speakerMode = AudioSpeakerMode.Mode5point1;
}
How ever, when I run a debug line of:

print ( AudioSettings.driverCaps);
It tells me that Unity is only playing in stereo. Is there something I'm still not doing?

I should also add I've ran 10 different tests using the 3D audio pan and spread options. I've set both to either being fully off, half way on and full. Still the same results.


texts: Received email that iOS development Certificate was revoked, what is it mean?

texts:
I'm trying to make a .ipa in Xcode from the build of my project file exported in unity3d. There was two errors in Xcode which are 1."Signing for "Unity-iPhone" requires a development team. Select a development team in the project editor.
2. Code signing is required for product type 'Application' in SDK 'ios 10.1' that I'm resolving so I tried to search in google on how to resolved it. We have already an apple developers account so I set it as the "development team" (step from the tutorial I saw) then when I'm trying to test the solution I did from Product->Archive in Xcode, I received the email and I think it prevent me from making a .ipa file.

I'm not still sure why I received that email. Based from my research, some say that it means I can not longer able to submit updates to the App Store for my application. Can somebody please help me on the reasons why.

Thanks in advance!


texts:
As you can see in the attached image below and the code, I have added a class that implements the interface ICameraControl attached to a GameObject.

When I call var controller = GetComponent<ICameraControl>();, I get nothing returned (null), as in this example:

public class KeyboardHandler : MonoBehaviour
{
    private void Start()
    {
        var controller = GetComponent<ICameraControl>();
        if (null == controller)
            print("no ICameraControl found!");
    }
}

And the output is like this in the unity console:

  no ICameraControl found! UnityEngine.MonoBehaviour:print(Object)
  Assets.Player.KeyboardHandler:Start() (at
  Assets/Player/KeyboardHandler.cs:18)

Here's the Camera Position Handler attached to my game object:

Here's the interface implementation:

public class CameraPositionHandler : MonoBehaviour, ICameraControl
{
    private GameObject mainCamera;
    private Quaternion homePosition;

    private void Start()
    {
        mainCamera = GameObject.FindGameObjectWithTag("MainCamera");
        homePosition = mainCamera.transform.rotation;
    }

    private void LateUpdate() { }
}

Any ideas what I am doing wrong?

Much appreciated :)
Matt

Edit:  The keyboard script is on my player object (at bottom of the picture of the player object).  And the Camera Position Handler is on the Camera Arm object.  The Player object and Camera Arm objects are at the same level.


texts: Gameplay-affecting LOD in a multiplayer UDK environment

texts:
There is an idea of developing a proof-of-concept multiplayer environmental exploration game that has varying levels of level of detail in terms of not just how objects are represented, but what objects are presented to each player, depending on the assigned parameters to each player present in the world governed by certain skill-sets. After the initial discussion, it was decided to to give Unreal Development Kit a try for building this concept project. We know that in all major engines LOD settings can affect meshes and textures just fine, but normally it's bound to graphics settings for the whole game.

Example of the implementation: Player A focuses on imagery and and thus sees the world in higher level of detail - there are better textures and better meshes visible, whilst player B focuses on audio clues and thus is enabled to hear more sounds that are triggered by various events.*

Is it possible to implement such a mechanism in a multiplayer Unreal Engine 3 environment?

Since I'm relatively new to both game development and UDK's capabilities, it would be greatly appreciated if I could get advice on any possible show-stoppers for this idea. Thank you.


texts:
I'm using Firebase Realtime Database and I'm trying to compare if a name is available to other user. The problem is the method finish before the Firebase's method finish its execution. Here is the code:

private bool IsNameAvailable (string nick)
{
    bool available = false;
    FirebaseDatabase.DefaultInstance.GetReference ("users").OrderByChild ("name").EqualTo (nick).GetValueAsync ().ContinueWith (task => {
        if (task.IsFaulted) {
            Debug.LogError ("A error encountered: " + task.Exception);
        } else if (task.IsCanceled) {
            Debug.LogError ("Canceled ...");
        } else if (task.IsCompleted) {
            DataSnapshot snapshot = task.Result;
            available = (snapshot.GetValue (true) == null);
        }
    });
    return available; //This line executed before the Firebase's method end.
}

What can i do??
Thanks in advance.


texts:
I am building a 3D Pong clone and want to implement a frictionless bouncing ball.

These are the steps i took:

Create a box in which the ball can bounce, consisting of standard cubic objects.
Create a ball using a spherical object
Add a Rigidbody to said ball (Mass: 1, Drag: 0, A.Drag: 0, no Gravity)
Add a bouncy Physics Material to the balls Sphere Collider (D.Friction: 0, S.Friction: 0, Bounciness: 1, Fraction Combine: min, Bounce Combine: max)
Add a script to the ball that adds force to the ball on start:

Script Snippet:

void Start() {
    this.getComponent<RigidBody>().addForce(0, 0, 100);
}

When i play the scene, the ball will fly towards the wall and then stop. If i change the added force to (0,0,101) it works as intended. If i lower the mass of the ball and use the old force (0,0,100) it also works. But it will always stop at the wall, if the added force is <= mass*100.

What am i missing?


texts:
I want my enemy to move randomly to certain points on the scene. It moves to one point and then stops! It does not continue to the other points!

Here is my script:

using UnityEngine;
using System.Collections;

public class emove: MonoBehaviour {

NavMeshAgent ePath;
public GameObject[] POINT;

void Start () {
    ePath = GetComponent<NavMeshAgent>();
}

void Update () {

    foreach (GameObject waypoint in POINT) {
        ePath.SetDestination(waypoint.transform.position);
        ePath.speed = 2;

      // I write this, if you have different idea tell me please
        if (waypoint.activeSelf == false) // waypoint had it own script, when enemy touch any point it set off
        {
            ePath.SetDestination(waypoint.transform.position); // move to any other active waypoint.
            ePath.speed = 2;
        }
    }
}

What am I doing wrong?


texts: Programmatically placing objects along Polygon Collider 2D

texts:
In my game, I have Tiled "rooms" that were imported with Tiled2Unity.  All of these rooms have walls that are defined by Polygon Collider 2D objects.  In the event of a cave or dungeon, I'd like to implement torches.  Currently, I literally randomly place torches in each room, which is pretty good for lighting, but looks ridiculous.

After the room is added, rather than randomly place torches anywhere, I'd like to have them placed along the inside of the collider.  Is there a good way to make this happen?

Edit:

One of my first attempts was to get a list of all of the points in all colliders in a given room after it's instantiation.  I was starting with something like this.

GameObject _roomGO =
   (GameObject)Instantiate(_room.gameObject, new Vector3 (-6.5f, 6.5f, 0f), Quaternion.identity);

List<PolygonCollider2D> _polyList =
   _roomGO.GetComponentsInChildren<PolygonCollider2D>().ToList();

However, this only gets the points from the first collider, whereas I need the points for all colliders in the room GameObject.  Additionally, I'm not sure how those points are stored in such a way that I could create a List or Array of lines, then evaluate those lines to determine which are inside the room (as opposed to along the outside, so nothing in the set [(x,0),(x,-13),(0,y),(13,y)].

Once I had a list of lines that weren't part of that set, I could choose a point on the line and drop in a torch.

Edit2 - images:

Edit 3:

Thank to @SP., I've used some of his code as shown here:

        if (_torches)
    {
        Transform _roomGOLayer = _roomGO.transform;
        int numTorch = rndObjects.Next(2,4);

        List<PolygonCollider2D> _polyList = _roomGO.GetComponentsInChildren<PolygonCollider2D>().ToList();

        foreach (PolygonCollider2D polCol in _polyList)
        {
            foreach (Vector2 point in polCol.GetPath(0))
            {
                Debug.Log(point.x +" : "+ point.y);//you will be using these values

                GameObject _to = Instantiate(_torch, new Vector2(point.x, point.y), Quaternion.identity) as GameObject;
                _to.transform.parent = _roomGOLayer;
                _to.transform.position = _to.transform.parent.transform.position + new Vector3 (point.x, point.y, 0f);
            }
        }
    }

The biggest problem I'm having up front is that _polyList is only getting the first collider definition.  I think if I could solve that, I'd be in good shape.


texts: How do I change the turn from a user to the next?

texts:
I was asked by a friend to develop a small web game which should support 10 players.
Very basic game-play:
There is a piñata which has x-"healthpoints". Each player can hit the piñata when it's their turn.
However, I'm having a hard time figuring out how to handle this. As of now, I have three databases:
Table: game

hasStarted
usersTurn

Table: users

id
username

TABLE: usersPlaying

id
username

So far my game works like this:
'users' holds all of the users.
When the game starts all of the online users username are copied into 'usersPlaying'.
Then a random row from 'usersPlaying' is selected and that username is copied into 'game' in the 'usersTurn' field.
From the webpage there's a AJAX-script checking for 'usersTurn' variable every second. If the username matches $_SESSION["username"] the users will know if it's their turn.
However from here, I've totally lost it. I cannot figure out how to move on to the next player, and I'm even wondering if this is the right way to go at all. It's not ment to be too fancy, it's only going to be used once or twice.
So with my hands folded - is there anyone who can point me in the right direction?


texts: Will my "Block Buster" game infringe on the Blockbuster (movie rental) trademark?

texts:
I'm developing a small puzzle game called "Block Buster" and I was wondering if there will be any collision with already existing "Blockbuster" (movie rental company) registered trademark.

Does the space or case difference in the trademark mean something? Or is there any difference in that Blockbuster is a movie renting company and I will just be selling a game?

Do I really have to change the game's name?


texts: projected textures not appear on the "back" of the mesh as well?

texts:
I want to create blood wounds on my character's bodies by using projected textures. I've watched some commentaries on games like Left 4 Dead and they say they use projected textures for the blood.
But the way projected textures work is that if you project a texture on a rigged character, say his chest, it will also appear on his back.
So what's the trick? How to get projected textures appear only on one "side" of the mesh?

I use the Panda3D game engine, if that will help.


texts: What determines the hit detection ordering for graphic elements in Unity (2d game)?

texts:
I have a bunch of overlapping buttons spread across several UI Canvases. The default mouse behaviour only registers hover/click events with one of the overlapping buttons, which is ideal for my project. The problem is the order of which button gets activated, is not tied to the Layer it is on or the Sorting Layer the item is on. I cannot seem to control which button is the top button that gets activated.

Using a RaycastAll() function returns the name of all buttons on any given point, and reflects the problem that for some reason, the buttons are arbitrarily ordered.

How do you control the order in which buttons are registered by the mouse?


texts:
I am fairly new to Unity 5, as I was browsing through some prefabs, I found one for the Main menu in which UnityEvent was used in scripts to list down the menu options.

This UnityEvent was an array UnityEvent [ ] Event, which was nowhere initialized to anything but was showing no compiler errors and also during run, it was pointing to some predefined sets which the author was mentioning in the user manual... My questions are :

Is it possible to use UnityEvent Array without mentioning the size of the array.
What happens to the UnityEvent if we don't mention any of the events, but the Invoke functionality is called during runtime.

Btw, the prefab i used from was :Main Menu with Parallax effects


texts: Random generation of interesting puzzle levels?

texts:
I'm making a Sokoban-like game i.e. there's a grid that has some crates on it you can push and you have to get the crates on crosses to win the level (although I'm going to add some extra elements to it). Are there any general algorithms or reading material I can look at for  how I could go about generating interesting (as in, not trivial to solve) levels for this style of game? I'm aware that random level generators exist for Sokoban but I'm having trouble finding the algorithm descriptions.

I'm interested in making a game where the machine can generate lots of levels for me, sorted by difficulty. I'm even willing to constrain the rules of the game to make the level generation easier (e.g. I'll probably limit the grid size to about 7x7). I suspect there are some general ways to do level generation here as I've seen e.g. Traffic Jam-like games (where you have to move blocks around the free some block) with 1000s of levels where each one has a unique solution.

One idea I had was to generate a random map in its final state (i.e. where all crates are on top of their crosses) and then the computer would pull (instead of push) these crates around to create a level. The nice property here is that we know the level is solvable. However, I'd need some heuristics to ensure the level was interesting.


texts:
Of course it depends on the situation. But when a lower lever object or system communicate with an higher level system, should callbacks or events be preferred to keeping a pointer to higher level object?

For example, we have a world class that has a member variable vector<monster> monsters. When the monster class communicates with the world, should I prefer using a callback function then or should I have a pointer to the world class inside the monster class?


texts: Game map for platformer megaman-style game

texts: I want to make platformer game that would be sort of like megaman. I'm using SFML library for it. I have a problem with creating a map. Should I hardcode every single platform, add it colliders and so on? I've heard that 2d array of segments would be better, but I would still have to manually fil an array that's like 1000x1000 segments. Is there an easier way to approach this?


texts: How do I correctly set up a Unity animation to move?

texts:
I downloaded a custom .fbx model from the asset store, imported it to my project and placed it in my scene. I then created an animator controller and added it to the object.

To get the animations (that came with the model) into the animator tab, I dragged them onto the model in the hierarchy. I then set the one animation to default and pressed play, but in the game window, the model didn't move.

What might be going on?

The only time it did something was when I set it to "play from start" but that made it go through all the animations.

I'm quite new to Unity 4. If you need any extra information, please ask.


texts:
So what I am trying to achieve is have the player shoot toward the mouse positiion and I have that working but I want the player to have to charge their shot. So if the player just presses the button it only goes a certain distance but if the player holds the button down for a bit it goes farther.

I tried to make a video that kinda explains what I am going for.

This is the code that controls the shooting

public class BowController : MonoBehaviour {

    public GameObject arrow;
    public Transform shootLoc;

    public float force;
    public Camera cam;

    public float chargeMin;
    public float chargeAmount;
    public float chargeMax;

    public bool charging;

    void Start () {

    }

    void Update () {

        Ray cameraRay = cam.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        Vector3 pointToLook;

        if (Physics.Raycast(cameraRay, out hit, 50))
        {
            pointToLook = hit.point;
            Debug.DrawLine(cameraRay.origin, pointToLook, Color.blue);

        }
        else
        {
            pointToLook = cameraRay.origin + (cameraRay.direction * 50);
        }
        transform.LookAt(pointToLook);

        if(Input.GetMouseButtonDown(0))
        {
            charging = true;

        }
        if (charging)
        {
            Charging();
        }

        if (Input.GetMouseButtonUp(0))
        {
            GameObject tempArrow;
            tempArrow = Instantiate(arrow, shootLoc.position, shootLoc.rotation) as GameObject;

            tempArrow.transform.LookAt(pointToLook);

            Rigidbody tempBody;
            tempBody = tempArrow.GetComponent<Rigidbody>();

            tempBody.AddForce(transform.forward * force, ForceMode.Impulse);

            force = 100;
            charging = false;
        }
    }

    void Charging()
    {
        force += Time.deltaTime * chargeAmount;

        if (force >= 500)
        {
            force = 500;
        }
    }
}

And this is the code that is on the arrow

  public Rigidbody rBody;
  public float speed;

    void Awake () {
        flying = true;
    }

    void Update () {
        if (flying)
        {

            //rBody.velocity = rBody.velocity.normalized * speed;
            transform.LookAt(transform.position - GetComponent<Rigidbody>().velocity);
            transform.Rotate(0, 180, 0);
        }
    }

    void FixedUpdate()
    {

        /*
        if (flying)
        {
            transform.rotation = Quaternion.LookRotation(rBody.velocity);
        }
        */
    }

    void OnCollisionEnter(Collision collision)
    {
        flying = false;
    }
}

I am still pretty new to coding so any help is appreciated. Thank you all very much in advance for the help!


texts: Diamond shaped map: converting tile number to coordinates and back

texts:
I have a diamond shaped map that is displayed as follows:
*  *  *  0  1  *  *  *
*  *  2  3  4  5  *  *
*  6  7  8  9 10 11  *
12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27
* 28 29 30 31 32 33  *
*  * 34 35 36 37  *  *
*  *  * 38 39  *  *  *

The tiles are stored as a uni-dimensional array in a file. So, I need to convert from tile number to coordinates, so I can make an array of arrays map[i][j]. I want to convert the tile number to its coordinates in the map (i, j) and back.
To do this, I have simplified it to this form (all tiles flushed to the left):
   j  0  1  2  3  4  5  6  7
i
0     0  1  *  *  *  *  *  *
1     2  3  4  5  *  *  *  *
2     6  7  8  9 10 11  *  *
3    12 13 14 15 16 17 18 19
4    20 21 22 23 24 25 26 27
5    28 29 30 31 32 33  *  *
6    34 35 36 37  *  *  *  *
7    38 39  *  *  *  *  *  *

I have managed to convert a coordinate to its tile number like so:
def get_tile_number(i, j):
    # Given a map width and height n:
    if i < (n/2):
        number = i*(i+1) + j
    else:
        number = (2*((n/2)*((n/2)+1))) - ((n-i)*(n-i+1))) + j

So:
get_tile_number(0, 0) -> 0;
get_tile_number(6, 0) -> 34;

However, I cannot figure out to go back to the coordinates from the tile numbers, because I have trouble with distilling the i parameter from the tile number.
I have tried googling with terms like "diamond shaped map tile numbers coordinates convert", but no luck.
Can someone point me in the right direction?
Solution
Based on Ed Marty's answer, the formula looks as follows:
def get_ij(tile_number):
    n_serialized_tiles = (2*((n/2)*((n/2)+1)))
    if tile_number < n_serialized_tiles/2: # If before the halfway point of the diamond
        i = math.floor(0.5 * ((math.sqrt((4 * tile_number) + 1)) - 1))
    else:
        i = math.floor(n- (0.5 * ((math.sqrt((4 * ((2 * ((n/ 2) * ((n/ 2) + 1))) - tile_number)) + 1)) - 1)))

This finds the i component, after which I can find j by imputing get_tile_number(i, j=0) in the previous formula which gets me the tile_number at the start of that row. I then subtract the real tile_number from that number to get j j = tile_number - get_tile_number(i, j = 0).


texts:
As in the title, I am trying to figure out how to use a button for multiple purposes in Unity.
In my specific case for instance, I am currently using the joystick button 0 (the A button) to perform a simple melee attack:
if (Input.GetButtonDown("Fire1") && currentState != PlayerState.attack && currentState != PlayerState.stagger)
//second clause because I do not want to indefinitely attack every frame
{
    StartCoroutine(GetComponent<Player_Melee>().FirstAttack());
}

In the conditions I make sure that I am pressing the right button and determining in which state my player is (the state is then changed in the attack coroutine).
In order to interact with a given object, I created a trigger to check that the player is within range to inspect the object:
if (Input.GetButtonDown("Interact_Alt") && playerInRange)
{
    if (dialogueBox.activeInHierarchy)
    {
        dialogueBox.SetActive(false);
    }
    else
    {
        dialogueBox.SetActive(true);
        dialText.text = dialogue;
    }
}

In the Input manager settings in unity, I set the 'Interact_Alt' button to be the same as the 'Fire1' used in the attack script. The scripts actually work, however whenever I check an object I also perform an attack. How can i make so that when I want to inspect an object I do not attack?
I was considering create a new finite state similarly to the one I use to attack e.g. 'PlayerState.interact', but then I was wondering, how would unity give the priority to which command to use?
Another alternative would be to check if I am in the range of some object when I want to attack and if within range it inspects the object instead, but it seems to me a much more convoluted solutions.
How should I solve this?


texts:
I am trying to define a simple enumeration in a header file as per the example published here. My header file consists of the following:

#pragma once

#include "CoreMinimal.h"

UENUM()
enum class MyEnum : int32
{
    MyField1,
    MyField2,
    MyField3
};

If I remove UENUM(), the compiler doesn't complain; however, when I add it, I get multiple errors.

expected a ';'
expected a '{'
identifier "MyField1" is undefined
identifier "MyField2" is undefined
identifier "MyField3" is undefined

This all seems odd considering I'm doing exactly what the article says to do and other websites suggest doing the same thing.

Here's what it looks like in my editor:

What I've tried

Changing enum class to simply enum.
Not explicitly specifying an underlying type.
Defining the enum elsewhere (for instance, in one of my classes; but when you add UENUM() there, it tells you you can't define it there).

I am new to both C++ and UE4 so it could be silly or trivial. Either way, I'm having a hard time understanding why something so simple won't compile.


texts:
Currently, I'm loading images as follows:

sampleimage= BitmapFactory.decodeResource(context.getResources(), R.drawable.sampleimage);

This automatically chooses the correct image from the drawable-hdpi, drawable-mdpi or drawable-ldpi folders.

How can I load the bitmap using the image name as the string "sampleimage.png"?


texts: Gamemaker Running Animation Flashing, showing single frame, and displaying jump and run sprites at same time

texts:
EDIT: I changed the origin of the run sprite to the center, and it is no longer hovering above the jumping sprite. It now flashes in the same location as the run sprite when moving to the side. Everything else is the same.

When I move side to side, the jump sprite moves along the ground while a single frame of the running sprite animation shows up above it and to the side. Both of the sprites flash when this happens. While moving sideways, the sprite slowly sinks into the floor. Jumping works just fine.

I'm very new to game maker and programming in general, so I'm probably making some dumb mistakes. Everything was working fine before I added the "animate" section. Here's the code I'm using:

//get player input
key_right = keyboard_check(vk_right);
key_left = -keyboard_check(vk_left);
key_jump = keyboard_check_pressed(vk_space);

//react to imput
move = key_right + key_left;

hsp = move * movespeed;

if (vsp < 10) vsp += grav;

if (place_meeting(x,y+1,obj_wall))
{
    vsp = key_jump * -jumpspeed
}

//horizontal collisions
if (place_meeting(x+hsp,y,obj_wall))
{
    while(!place_meeting(x+sign(hsp),y,obj_wall))
    {
        x += sign(hsp);
    }

    hsp = 0;
}

x += hsp;

//vertical collisions
if (place_meeting(x,y+vsp,obj_wall))
{
    while(!place_meeting(x,y+sign(vsp),obj_wall))
    {
        y += sign(vsp);
    }
    vsp = 0;
}

y += vsp;

//animate

if (move!=0) image_xscale = move;

if (place_meeting(x,y+1,obj_wall))
{
    if (move!=0) sprite_index = spr_player_run; else sprite_index = spr_player_idle;
}
//else
//{
   if (vsp < 0) sprite_index = spr_player_jump //; else sprite_index = spr_player_fall;

   if (vsp > 0) sprite_index = spr_player_jump
//}


texts:
Since it generates more triangles and vertices, the official outline script isn't a good way to do text outlining in my project.

How can I outline my text, with better performance?

TextMesh Pro may be the solution, but it'll increase the usage of memory heavily and our game is aimed at mobile platforms, so we want to minimise use of memory.


texts: Is it possible to mod a game to use a scripting language like Lua?

texts:
So my questions are:

Is it possible to mod a game to use a scripting language?
How would I go about doing so?

I really like Arma 2 but like many games it does not have much in terms of capabilities beyond using server commands in scripts. That makes it pretty limited.

Personally I would like to add the ability to use a different language than Arma 2's scripting language; possibly Lua.

How could I make Arma 2 use Lua? Is there a way?

I remember from when I just a teenager and into modding Halo PC some people had created scripting mods for that game. How did they do that? I hope this question isn't too general or difficult to answer.


texts: How can one access the depth buffer for Unreal Tournament 2004?

texts:
I'm looking for a way of getting depth buffer data for a virtual 3D sensor.

Currently the method used is raycasting (implemented in UnrealScript), but I want to use the depth buffer data instead for faster output of the sensor in FPS.

One complete frame of data takes many seconds to generate currently, which is bad for my application which must parse this 3D depth data and also control a vehicle with it.

I'd like to get the data from D3D but don't know if it's possible.


texts: Turn based game - how to deal with partial world state updates?

texts:
I'm implementing a simple "turn based" game where the player sets up a bunch of "actions" on a board and "objects" move on the board and are influences by those actions. The player is no longer involved after setting up the board and just watches the actions play out. Each "turn" of the game loop, a "move right" action will move any objects on its square one square to the right, for example.

My problem is now that each time I run the game loop, all actions are executed as follows:

for(auto& go: gameObjects) {
    go->update();
}

Each of these game objects mutates the world state in its update() method. What I'm seeing now is that when the board is updated by one object, the next one will immediately use that updated board state and perform its action "too soon".

For example: When I place three "move right" actions on the board and run the game loop, the object will be moved three spaces in one "turn" while it should actually take 3 "turns" for the object to move through all 3 of those actions.

How can I delay the board state update until all actions have had their chance to decide what to do? I'm considering two strategies:

Copy the board state for each turn and create a new board state as the result of a turn. This is complicated because all my views are tied to the objects on the board. If I copy the board, I'll have to re-create all views?
Have each action not update the world state, but only return a function which, when executed, will do the update. Once I have all the functions collected, execute them all to update the board.

Any suggestions?


texts: Drawing transparent and opaque 3D objects. How do I preventing z-fighting?

texts:
I am using a transparent weighted average algorithm to draw my transparent objects.

The transparent object is drawn with the following notable render states (the rest are default XNA values):

    CustomBlendState.Additive,
    DepthStencilState.DepthRead,
    RasterizerState.CullNone,
    SamplerState.PointClamp

The opaque object is drawn using the following states:

    BlendState.Opaque;
    DepthStencilState.Default;
    RasterizerState.CullCounterClockwise;
    SamplerState.PointClamp;

In the picture below there is what I believe is a z-fighting issue where the green block and the wooden block meet.

How can I keep the objects in the same location and stop this issue from occurring?

When changing the transparent object's DepthStencilState.DepthRead state to DepthStencilState.None the issue goes away.  While this is what led me to believe it was a z-fighting issue, the opaque object will then no longer occlude the transparent object when viewed from another angle.

EDIT:

Applying a depth bias to the situation makes no discernible difference either:

    public static RasterizerState SolidNoCullBias = new RasterizerState()
    {
        CullMode = CullMode.None,
        FillMode = FillMode.Solid,
        DepthBias = 1f,
        SlopeScaleDepthBias = 1f,
    };

EDIT 2:

Culling the triangles will cause the object to look incorrect as a transparent object should show both the inside and outside faces.

EDIT 3:

Depth Stencil State is as follows with 'LessEqual' compare function (doesn't solve the issue)


texts: How do I get the Oculus Rift's position and rotation?

texts:
I'm looking for the functions to get the position and rotation data of the rift headset itself in Unity.

I have the Oculus integration SDK installed and want to avoid using any pre-fabs.


texts: So I’ve been messing around in unity lately, and I got a vr headset to mess around as as well(google cardboard). I also want to make my own controller to use with this. To achieve this, I want to use a HID complient chip with a arduino. Basicly, this sends usb keyboard input. I was wondering, will Input.getkey(keycode.whateverkey) work with this? I’m not sure if that will even register on ios, because iOS keyboard is usually separate from the app because it covers the screen.


texts: How does the stateTimer parameter is initialized in this method getKeyFrame(stateTimer)?

texts:
I have been following the tutorial https://www.youtube.com/watch?v=1fJrhgc0RRw&list=PLZm85UZQLd2SXQzsF-a0-pPF6IWDDdrXt&index=11

I an not able to understand what is stateTimer in getframe method and how is that initialized?


texts: How can I play user-provided music stored on the phone inside my game?

texts:
I am creating a car game. Is any way to play the music stored on the phone inside the game? I'd like the player to choose files that are already on their device and hear them played in the game.

For example, in GTA Vice City game there was a folder named Music, and if we placed songs in there they would play on the car radio while we're driving around inside the game. If we want to switch the songs around, we can do so. how can I do the same in Android and iOS?

I am using unity 5.2, C#.


texts: Animated examples of different interpolations formulas: any link?

texts:
I remember having spotted a link to a huge page with different equations to non linear interpolation curves, for example if you want to stop a car smoothly, etc.

Those can sometime be useful to emulate some real-world acceleration/velocity behaviors without the help of a physics engine, which can really simplify the code.

Any idea where this page is ? I can't manage to give google the right keywords...

EDIT:
I just searched on my previous laptop bookmarks, and I found it: http://sol.gfxile.net/interpolation/


texts:
I know that you can just write a code like this in the render method:

 public void render(float delta) {
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    myStage.act(delta);
    myStage.draw();

    if(myTouchpad.isTouched()){
         //do stuff
     }else{
         //do different stuff
     }
}

But I don't think it's a good way to solve this, is there a way to handle this using listeners or something like that?


texts: How to create post-processing effects in Slick2D?

texts:
As I get closer and closer to the end of the feature development for my game and the beginning of the graphical overhaul, I keep thinking of ideas for graphical effects that would make my game even better, but Slick2D is so limited in terms of graphical capabilities. The LWJGL layer is exposed, and thus, basic OpenGL functions, but I don't know anything about the various blending functions and other functions available to me.

A couple of the most basic things I need to be able to do are to be able to properly blend images and primitive shapes together, and to be able to create a proper lighting system. As of right now, I simply have a black and white "stencil" for my flashlight that I blend with a flat black layer that's drawn over everything and set its opacity so it sort of looks like a flashlight. However, I'd like it to look better and to be able to have other light sources in the scene.

Also, I'd really like to be able to have "glow" effects, such as electricity or fire that brighten up the scene and don't just look like flat pixels. Is it as simple as additively drawing these images/shapes to the scene? Or is there more to it?

I know Slick2D is horribly outdated and no longer supported and I never should have used it, but it's definitely the last time I'll be using it. I only went to it because Java has limited game libraries available and LibGDX was giving me a lot of trouble getting started.

I'd appreciate any articles and examples.

EDIT: As an example of the "glow" effect, here's a neat explosion effect created in Unity that I found on /r/gamedev. It would be great if I could get something like this in my game.

https://www.reddit.com/r/gamedev/comments/8wurqc/stylized_explosion_shader_breakdown/


texts: Geometry System of Populous: The Beginning

texts:
I want to to develop a game like Populous: The Beginning with my friend. But we could not find out what type of geometry they have used for the world.

We know that
- all tiles have the same size
- all tiles are squares

So.. It cannot be a Icosahedron, because there are triangles, nor cant it be a standard sphere geometry, because not all tiles have the same size.

Can someone help me?


texts: Player field of view, Physics.overlap, onTrigger performance

texts:
I would like to ask you what is the best way to accomplish my problem.
I have a player who can detect ennemy with raycast in a zone, or in a certain angle, like in this picture:

As you see I want to get only green one.

I'm in topDown view. I was thinking about using Physics.OverlapSphere first, and then try Angle between player and target. But: In the picture I don't want to get the Purple one.

Also: what is the best way to do that with the best performance ?


texts: How do I deal with the problems of a fast side-scroller?

texts:
I'm making a side scrolling airplane game and when I begin going very fast I begin to experience some problems as a player:

Elements are not distinguishable, like power-ups from bullets, etc
I start to feel dizzy and uncomfortable
There isn't enough time to see what's coming

How can I sort this out? Do I use less details in all the grahpics?

Tiny Wings has the same horizontal movement speed as in my game but it doesn't suffer from these problems. Are there any other really fast side-scrollers I could take as a reference?


texts: Unity3d - Do I need to destroy gameobject AND script?

texts:
From proper leak protection do I need to delete both of these or will getting rid of one take care of both?

Currently I am destroying the script AND the gameobject

private void OnDestroy() {
    Destroy(this.gameObject);
    Destroy(this);
}


texts: Error when using GetComponent (Object reference not set to an instance of an object)

texts:
I'm using a textmesh to check variables in real time. Thing is if I use AddComponent within Update(), it obviously starts spamming and slows the game. If I try with GetComponent the error is the following:

NullReferenceException: Object reference not set to an instance of an object
DebugCombo.Update() (at Assets/DebugCombo.js:9)

which points to the text.text assignment.
This is the script from DebugCombo.js, from which I call the Combo class (from Combo.js)
#pragma strict

public class DebugCombo extends MonoBehaviour{

    function Update () {
        var text = gameObject.GetComponent(TextMesh);
        var combo = gameObject.GetComponent(Combo);

        text.text = "Current: "+ Time.time +" | Limit: " + combo.comboTime;
    }

}

How do I get rid of this error?


texts: Calculate Relative Mouse Movements Regardless of position

texts:
Context

I'm working on making a variant of the atari game Breakaway IV and I'm trying to improve my mouse input handling.

I use the input of a mouse's motion left and right to move the bumper.

public void mouseLocationChanged(Point mouseLocation) {
    if (lastMouseLocation == null) {
        lastMouseLocation = mouseLocation;
        return;
    }
    bumperStep = (int) ((mouseLocation.x - lastMouseLocation.x) * SENSITIVITY_MULTIPLIER);
    lastMouseLocation = mouseLocation;
}

Then in the update method of my game I check if there is a bumper movement queued up.

 public void update() {
    if (inputHandler.isBumperMove()) {
        submitBumperMove(inputHandler.getBumperMove());
    }
    ...
}

If there is, I move the bumper with the below code.

public void submitBumperMove(int move) {
    if (move < -1 * BUMPER_SPEED_LIMIT) {
        move = -1 * BUMPER_SPEED_LIMIT;
    } else if (move > BUMPER_SPEED_LIMIT) {
        move = BUMPER_SPEED_LIMIT;
    }

    testPoint.x = bumper.x + move;
    testPoint.y = bumper.y;

    while (testPoint.x != bumper.x) {
        if (!willCollideWithWall(bumper, testPoint)) {
            bumper.x = bumper.x + move;
            if (bumper.hasBall){
                ball.x = ball.x + move;
            }
        } else {
            move = shrinkStep(move);
            testPoint.x = bumper.x + move;
        }
    }
}

Observed bugs

I don't reset bumperStep with the call to getBumperMove() so the cursor drifts if there isn't a different input to set bumperStep to 0. This mainly happens when the mouse exits the window.
When resetting bumperStep to 0 with getBumperMove() (making it consumeBumperMove()) the mouse can run out of the window before the bumper reaches the edge of the game and the bumper can't be moved to the edge.

Proposed Solution

I was considering resetting the mouse cursor in the center of my window (with the cursor invisible) while the game is in "play" mode with each game update. This would prevent the problem of the mouse leaving the screen and not working while still allowing me to consume the movements which will stop the drifting bumper I'm observing.

Questions(finally ;-) )

Is there a better approach to getting mouse left and right movements from any position in java, or should I stick with just keeping the cursor where I want it?
If locking the cursor is the way to go, how can I pragmatically set the mouse position in Java? I've heard about a Robot class that is supposed to help, but it looked like an application needs special signing/permission to use that.


texts: How to implement Microwave Signals in Unity?

texts:
I need to implement microwave signals for object detection in Unity.

I know there are raycast sensors in Unity, but can microwave signals be simulated or can a proxy of microwave signals be created in Unity using the raycast sensors?


texts: Unity 2D: Smooth ease-out movement on grid

texts:
I'm trying to create a grid movement in Unity, as where the player will ease-out on a tile when stopping, but I can't seem to get it right. I need a little nudge in the right direction for how to implement something like this:

I used a coroutine to execute the movement when input is requested and use an ease-out curve to make the player stop smoothly. But, when walking multiple tiles it is jittery because the ease-out is applied. Also, the smoother I want the ease-out to be, the slower the player moves.

My full code.

public float moveDuration = .5F;
public AnimationCurve moveCurve = AnimationCurve.Linear(0F, 0F, 1F, 1F);

private Rigidbody2D rigidBody;
private BoxCollider2D boxCollider;
private bool isMoving;

void Start() {
    rigidBody = GetComponent<Rigidbody2D>();
    boxCollider = GetComponent<BoxCollider2D>();
}

void Reset() {
    moveSpeed = 8F;
    moveDuration = .5F;
    moveCurve = AnimationCurve.Linear(0F, 0F, 1F, 1F);
    isMoving = false;
}

void Update() {
    if (!isMoving) {
        int x = 0;
    int y = 0;

    x = (int)(Input.GetAxisRaw("Horizontal"));
    y = (int)(Input.GetAxisRaw("Vertical"));
    if (x != 0) y = 0;
    if (x != 0 || y != 0) {
            AttemptMove(x, y);
        }
    }
}

private void AttemptMove(int x, int y) {
    Debug.Log("Attempt move: "+x+","+y);

    Vector2 startPosition = transform.position;
    Vector2 endPosition = startPosition + new Vector2(x, y);

    StartCoroutine(SmoothMovement(endPosition, moveDuration));
}

protected IEnumerator SmoothMovement(Vector3 endPosition, float duration) {
    float elapsed = 0F;
    Vector3 startPosition = transform.position;

    isMoving = true;

    while (elapsed < duration) {
        Vector3 newPosition = Vector3.Lerp(startPosition, endPosition, moveCurve.Evaluate((elapsed/duration)));

        rigidBody.MovePosition(newPosition);
        elapsed += Time.deltaTime;
        yield return null;
    }

    isMoving = false;

}


texts:
I have this class in java, I'm using Jersey.

 @Path("/bandas")
 public class BandaResource {

static private Map<Integer, Banda> bandasMap=someSource();

@GET
@Produces({ "application/json" })
public List<Banda> getBandas()
 {
    return new ArrayList<Banda>(bandasMap.values());
 }

@POST
@Consumes("text/xml")
@Produces("text/plain")
          public String adicionaBanda(Banda banda) {
           banda.setId(bandasMap.size() + 1);
           bandasMap.put(banda.getId(), banda);
           return banda.getNome() + " adicionado.";
    }
}

In Unity when I request all the information I get an answer from server:

 URL url = new URL ( "http://localhost:8080/restful-exemplo/rest/bandas" );
 WWW www = new WWW(url);

Debug.Log (www.data) returns:

{"banda":[{"anoDeFormacao":"1968","id":"1","nome":"Led Zeppelin"},{"anoDeFormacao":"1973","id":"2","nome":"AC/DC"}]}

But I want to send, I don't have any idea how but I tried:

 string JSON=" {\"nome\":\"Teste\", \"anoDeFormacao\":\"1988\",\"id\":\"4\"}";

    Hashtable postHeader = new Hashtable();
    postHeader.Add("Content-Type", "text/json");

    UTF8Encoding encoding = new System.Text.UTF8Encoding();
    WWW request = new WWW(url, encoding.GetBytes(JSON.ToCharArray()), HashtableToDictionary<string, string>(postHeader));

Well, it returns a error (WWW Error: 415 Unsupported Media Type
), is the idea correct?


texts: How to create an Editor class for a generic class

texts:
For all my MonoBehaviour scripts, instead of them inheriting from MonoBehaviour they inherit from a generic class like so:

public abstract class MonoBase<T> : MonoBehaviour where T : MonoBase<T> { }

public class Example : MonoBase<Example> { }

Now, I would like to make an editor script for all those MonoBase classes, and the closest I have gotten to a solution that will compile is :

[CustomEditor(typeof(MonoBase<>))]
public class MonoBaseEditor<T> : Editor where T : MonoBase<T>
{
    public override void OnInspectorGUI() {
        this.DrawDefaultInspector();

        MonoBase<T> myScript = (MonoBase<T>)this.target;
        if (GUILayout.Button("Build Object")) {
        }
    }
}

But of course it doesn't really work.

Am I missing something or is there really no way to make a generic editor class like it's mentioned in an answer here.


texts: Building a visual scripting component (like Kismet)

texts:
I'd like to know how can one get started building a visual scripting component (or what is the more accurate term for this type of component?) such as UDK's and Unreal Engine's Kismet.

For those who are not familiar, the system allows connecting various pieces of logic visually, creating a possibly complex component out of smaller building blocks.

While the underlying data model may be (perhaps) something i can figure out for myself, it is the visual part that i am not sure of how to work out.

Are there any libraries that facilitate writing something like this? Where can i get started on thsi ?


texts:
Have three groups, A, B and C.

Let B and C be children of A.

Now set

B.setZIndex(3)
C.setZIndex(2)

Why is C drawn over B, if B has a greater Z index?

If you do this:

C.setZIndex(2)
B.setZIndex(3)

It works. However, I want to set B's index before I set C's. So, what's up?

(I know that C is drawn over B because each group contains an image)


texts: pygame - avoiding sprite 'jitters' on rotating the image

texts:
Is there a common trick for getting around sprites that are changing directions 'too quickly' and causing their sprite to display erratically?

In this project, the player moves in 8 directions by determining the abs() distance between the mouse's X and Y coordinates and its own obj.rect.center. If the absolute value is less than obj.speed, it simply moves to that point. If it is greater, it moves the distance its speed allows it to move in that direction. When it's time to draw the sprite, PyGame rotates it in accordance to obj.direction by using a dict called SPINNER with stored default values to pass to pygame.transform.rotate.

def draw(obj):
    drawImg = pygame.rotate.transform(obj.img, SPINNER[obj.direction])
    drawCtr = drawImg.get_rect(center=obj.rect.center)
    DISPLAYSURF.blit(drawImg, drawCtr)

This is fine for the foolish AI characters which typically make very few course corrections - however, small movements of the mouse can cause the player's obj.direction to update very quickly, which looks chaotic.

Is there a simple way to curb this behavior? My first guess is to bog down the player object with values that retain its previous state and then determine the amount of rotation to apply, but I have a feeling the better solution is to assign that responsibility to the 'view' and not the 'model'. I'm not sticking to any hard and fast rules regarding MVC, but I am trying to engage in enough separation of concerns that 'view-like methods' don't make 'controller-like' changes to 'model-like' objects, if that makes sense.


texts: How do I get pygame to work on intel processor?

texts:
I downloaded Python 3.4 64 bit IDE and pygame but whenever I tried installing pygame it would say "Not supported on Intel".
So are there version of pygame available for Intel processor or are there any other ways to install pygame on an Intel processor?????


texts:
Currently I am using a Ray class that I built myself. The following is for brevity.

public class Ray : GameObject
{
    public GameObject Shooter;
    public List<GameObject> Objects;
    public float Speed = 250f;
    public bool Collided = false;

    public void Update(){
        if (Collided) return;
        Position.X += Speed * gameTime;
        Position.Y += Speed * gameTime;

        foreach(var obj in Objects){
            if (this.Intersects(obj) {
                 obj.OnCollide(this);
                 Collided = true;
            }
        }
    }

This works, but only if I control the amount of rays, cause if I create too many rays, the game becomes laggy OR the ray/bullet get past through walls (idk why). I am trying to find out which objects that player can see and only draw the visible things, so I need to let out alot of rays. Is there a more efficient way to achieve this objective.


texts: How is the render() method called in libGDX?

texts:
I know that the project generator in libGDX finds the render(deltatime) method in my Game project and make it into a game loop so that it repeats itself on an average of 60 times per second. But I want to know how exactly the project generator finds the render() method.

Let me give you an example:

In my game, in the Main class, I declared a SecondClass with its own render() method using its constructor in the create() of the Main class. Then, I didn't have any render() method in the MainClass. When I did this, the render() in the SecondClass worked. However, when I created the render() method in the MainClass, the render() from the MainClass worked but not the render() method in the SecondClass. Does that mean that the project generator access the first render() it can see as the GameLoop?


texts: Set a variable inside a GLSL fragment shader that persists for the render

texts:
Is it possible to set a varying variable inside a fragment shader and have it persist? I'd like to use the depth component of the first fragment and use it on all the others, making the fragments all flat to the camera.

Secondary question: Is it the whole frag shader that runs per-fragment, or just the stuff inside main()? Is everything redeclared each time?


texts: What kind of databases are usually used in an MMORPG?

texts: Do people write their own DB for some reason?


texts: TCG - how to program cards as separate entities

texts:
So I'm planning to try making a card game (in Java) but I'm not sure what the best way to design it is. I understand the engine stuff but not how the cards should be coded an how they should interact with the engine. The scope is like so:

We have an engine that understands the flow of the game. It knows you draw at the start, play cards at some point, have a combat step, and end the turn (switching players). This much is fine, but the concern is the cards themselves.

I want to have cards be their own entities. I'm not sure if it would be better to:

a) Have each card be their own class
b) Have each card be programmed as an external script (say in Python)

I want the game engine to know as little as possible about a card. When you play a card, I want the game engine to go:

You're playing a card. Do you have resources? Ask the card how much it takes, then confirm you have it. When a card has an interaction, I want it to do as much as it can. For example, if the card says draw a card, I want it to forceably tell the engine to draw a card, or better yet, hook into the game, draw a card, and then force the engine to update itself.

Extreme cases would probably provide a better description, so if there was a card that said "players do not draw at the beginning of their turn", the engine would normally automatically draw, so we'd have to stop that. I could reasonably program something where the engine would check if anything special happens before each interaction and it would see "skip draw". Even still, how would I program that? Would I write a method in the engine to skip draw and then have the card add it as a special trigger? Would I actually have the card (perhaps programmed in Python) hook into the engine and end the draw method?

What would be the best way to go about this?


texts:
I am currently creating a flappyBird-like HTML5 game using Proccessing.js

You can see current work here: http://files.tips4design.com/flappySlothRelease/

The problem is that even though the FPS is 60+ (or constant) there is an obvious shuttering in rendering.

I have read a lot of game-loop articles to solve this issue, but neither with Processing.js draw loop, browser's requestAnimFrame nor constant delta-time the problem was solved.

Now I use the variable deltaTime approach and Processing.js default draw() loop.

delta = now - lastTime;
...
position = position + velocity * delta

I have been stuck for two days with this problem, and ca not really figure out how to fix the shuttering.

Any help would be greatly appreciated!

Thank you!


texts: I am looking to create realistic car movement using vectors

texts:
I have goggled how to do this and found this http://www.helixsoft.nl/articles/circle/sincos.htm I have had a go at it but most of the functions that were showed didn't work I just got errors because they didn't exist. I have looked at the cos and sin functions but don't understand how to use them or how to get the car movement working correctly using vectors. I have no code because I am not sure what to do sorry.

Any help is appreciated.

EDIT:

I have restrictions that I must use the TL engine for my game, I am not allowed to add any sort of physics engine. It must be programmed in c++. Here is a sample of what i got from trying to follow what was done in the link I provided.

if(myEngine->KeyHeld(Key_W))
    {
        length += carSpeedIncrement;
    }
    if(myEngine->KeyHeld(Key_S))
    {
        length -= carSpeedIncrement;
    }
    if(myEngine->KeyHeld(Key_A))
    {
        angle -= carSpeedIncrement;
    }
    if(myEngine->KeyHeld(Key_D))
    {
        angle += carSpeedIncrement;
    }

    carVolocityX = cos(angle);
    carVolocityZ = cos(angle);

    car->MoveX(carVolocityX * frameTime);
    car->MoveZ(carVolocityZ * frameTime);


texts: How to use camera transformation without depending on (1,-1) scale during spriteBatch.draw()

texts:
I am creating a 2D platformer type game in XNA.

I currently have a camera object, with a position/rotation/zoomlevel that I use to generate a transformation matrix to pass to SpriteBatch.Begin(). This allows me to draw at in game coordinates instead of screen coordinates.

The relevant bit of the Camera code:

public Matrix GetViewMatrix() {
            cameraMatrix = Matrix.CreateScale(new Vector3(1f, -1f, 1f))
                   * Matrix.CreateTranslation(position.X, position.Y, 0f)
                   * Matrix.CreateScale(new Vector3(zoom,zoom,1f))
                   * Matrix.CreateRotationZ(rotation)
                   * Matrix.CreateTranslation(new Vector3(screenWidth*0.5f,screenHeight*0.5f,0));
            return cameraMatrix;
}

Which is used like so:

spriteBatch.Begin(SpriteSortMode.BackToFront, null, null, null,
                  null, null, camera.GetViewMatrix());
//Draw Stuff
spriteBatch.End();

The problem is, that in order to get anything to actually draw, I have to scale by (1,-1) when I call spriteBatch.Draw(), otherwise I believe the textures get depth culled.

spriteBatch.Draw(content.Load<Texture2D>("whiteSquare"), Vector2.Zero, null,
                 Color.White, 0f, Vector2.Zero,
                 new Vector2(1f, -1f),
                 SpriteEffects.None,0f);

Notice the Vector scaling argument in the 3rd line of the last sample. My question is twofold:

How do I avoid having to pass this scaling argument/calling the
longest form of spriteBatch.Draw() (kind of a violation of DRY,
though I could wrap it I suppose).
Am I doing something wrong (not
"it doesnt work wrong" but "thats the wrong way to approach that
problem" wrong)? I have seen mentions of viewport.Update() functions and Matrix.CreateOrthagonal etc, but I'm not quite sure if using them is simpler/better than a simple custom camera sort of deal.

Thank you very much.

EDIT: After re-reading my post, and the first answers/comments, I think I have been thinking about this problem wrong.

I dont actually want to draw in game coordinates. What I want, is to be able to specify and work with game coordinates in such a way that positive y-axis is up, and that 1 unit of game distance equates to 1 meter equates to however many screen pixels it takes to make sure that you always view (for example) 10 meters of game distance from the left border to the right border of the viewport.

Preliminary experimenting led me to believe that passing in a world transform matrix to the spriteBatch.begin() method was the way to go about this, but now I think it may be a little more complicated. Does anyone have any advice for achieving the above goal? I have seen example code where every drawable entity implements a drawable interface that comes with a world translation matrix based on current entity position/etc, but where would I use such a matrix? Do I seperate spriteBatch.Begin()/End() calls for every drawable entity?

Sorry if this is a poorly formed question, trying to even wrap my head around the concept of the goal is proving difficult.


texts: How do I include a blend tree in my controller?

texts:
I want my player to aim up and down with a pistol.
I have stored an "aim up" pose in one anim file, and I have stored an "aim down" pose in another anim file.
I want to blend between these 2 poses according to the mouse pointer on the screen:

If the mouse pointer is at the bottom of the screen, the blend tree should only play the "aim down" pose
If the mouse pointer is at the top of the screen, the blend tree should only play the "aim up" pose
If the mouse pointer is at the middle of the screen, the blend tree should play a 50/50 mix of the  "aim down" and of the "aim up" pose

To do that, I have added a 1D blend tree to my animator.
It looks like this:

I have tested the blend tree. When I scrub through the "timeline" using the red line, it works as expected:

Now I wanted to test it out in my game, but I don't see how to set the blend weight of this 1D blend tree.
The docs say that the blend tree is controlled by the animation parameters.
As far as I can see, Unity automatically created one for me when I added the blend tree. The name seems to be "Blend", as can be seen in the screenshot:

The following however has no visual effect for me:
_animator.SetFloat("Blend", 1f);

To check if this parameter even exists, I have changed its value to 0.3 in the animator.
Then in my code, I check the value like this, and it does return 0.3:
float fCur = _animator.GetFloat("Blend");

So this is proof that the parameter does exist.
However, when I set a new value like...
_animator.SetFloat("Blend", 0.56f);

... then this value is accepted, but it doesn't have any visual effect, and it doesn't show in the animator's paramters.
Can anybody tell me how I could achieve what I want?
Edit:
I have tested it in a new, stripped-down project. In this new project, I have the blend tree as the default state in the animator, and everything works.
So the fact that my blend tree is NOT the default state in the other project seems to be the problem. This is what it looks like:

I will first try to investigate more on this.


texts: Can Event Triggers be used on Non-UI objects?

texts:
Is there any way to use UI-Based event triggers on Non-UI objects?

Example : on any UI object, you add an EventTrigger component, set the event, and then set the actions for the event. Its easy, and clean, to make UI do various actions on things like mouse enter / exit, drag, etc.

For non UI objects (a cube, for example) these kind of things are mostly done through scripts with raycast code. Its not impossible, but I find it messier, harder to organize, and less flexible then the EventTrigger approach.

I'm working on a turn based strategy type game. Much of the game mechanics is based around mouse movement and clicking. I tried just adding an on-click event to a cube, but it didn't do anything.

Is this scenario just plain not supported?


texts:
In a prototype I am doing, there is a minigame similar to bejeweled. Using a grid that is a 2d array (int[,]) how can I go about know when the user formed a match? I only care about horizontally and vertically.

Off the top of my head I was thinking I would just look each direction. Something like:

int item = grid[x,y];
if(grid[x-1,y]==item)
{
    int step=x;
    int matches =2;
    while(grid[step-1,y]==item)
    {
        step++;
        matches++
    }
    if(matches>2)
        //remove all matching items
}
else if(grid[x+1,y]==item
    //....
else if(grid[x,y-1==item)
    //...
else if(grid[x,y+1]==item)
    //...

It seems like there should be a better way. Is there?


texts: Handle two different touch gestures at same time without overlapping

texts:
I'm trying to create a Character touch controls for 2d platform.

In my script Im using one horizontal swipe and hold touch gesture and one vertical swipe gesture without hold.Both are different methods called in void Update ().

And here is my script :

void Update ()
    {

        HorizontalSwipe();
        VerticalSwipe ();

    }

    void HorizontalSwipe()
    {
        foreach (Touch FingerTouchx in Input.touches)
        {
            if(FingerTouchx.fingerId<1)//         FINGERID

            {
                //if(FingerTouchx.position.x < Screen.width/2)

                if(FingerTouchx.phase == TouchPhase.Began)
                {
                    FingerInitialPositionx=FingerTouchx.position.x;

                }

                else if(FingerTouchx.phase == TouchPhase.Moved)
                {
                    FingerMovedPositionx=FingerTouchx.position.x;

                    if(FingerMovedPositionx>FingerInitialPositionx)
                    {
                        charcter.transform.Translate(Vector2.right * speed * Time.deltaTime);
                    }

                    else if(FingerMovedPositionx<FingerInitialPositionx)
                    {
                        charcter.transform.Translate(-Vector2.right * speed * Time.deltaTime);
                    }

                }

                else if(FingerTouchx.phase == TouchPhase.Ended)
                {
                    FingerInitialPositionx=0f;
                    FingerMovedPositionx=0f;

                }

                else
                {

                    FingerMovedPositionx=FingerTouchx.position.x;

                    if(FingerMovedPositionx>FingerInitialPositionx)
                    {
                        charcter.transform.Translate(Vector2.right * speed * Time.deltaTime);
                    }

                    else if(FingerMovedPositionx<FingerInitialPositionx)
                    {
                        charcter.transform.Translate(-Vector2.right * speed * Time.deltaTime);

                    }

                }

            }

        }
    }

    void VerticalSwipe()
    {
        foreach (Touch FingerTouchy in Input.touches)
        {

            if(FingerTouchy.fingerId<1)      //         FINGERID

            {
                //if(FingerTouchy.position.y > Screen.width/2)

                if(FingerTouchy.phase == TouchPhase.Began)
                {
                    FingerInitialPositiony=FingerTouchy.position.y;

                }
                if(FingerTouchy.phase == TouchPhase.Moved)
                {
                    FingerMovedPositiony=FingerTouchy.position.y;

                }
                if(FingerTouchy.phase == TouchPhase.Ended)
                {
                    if(FingerMovedPositiony>FingerInitialPositiony)
                    {
                        charcter.transform.Translate(Vector2.up * speed * Time.deltaTime);
                    }
                    if(FingerMovedPositiony<FingerInitialPositiony)
                    {
                        charcter.transform.Translate(-Vector2.up * speed * Time.deltaTime);
                    }
                    FingerInitialPositiony=0f;
                    FingerMovedPositiony=0f;

                }

                else
                {}

            }
        }
    }

Problem:

1:When i swipe and hold horizontally the character moves fine but when i take my finger back it triggers the vertical swipe method.

2:When i try to swipe only vertically the horizontal swipe is also triggered.

3: The two swipe gestures are overlapping and triggered at same time on a Single touch.

Solution(Guess):Dividing the touch screen equally half and forcing horizontal touch gestures strictly on left side of touch screen and vertical touch gestures on right side.

But I'm beginner(You can see my coding style) and would like to know how to do it programatically.
Im still learning.


texts: How to tell whether the joystick axis is released (not pushed) in SDL2 or in general?

texts: I'd like to implement an event listener that triggers character movement (left/right/up/down or stay) according to the direction of pushed axis on the joystick. Due to jittering, the approach I found is to set area near (0, 0) as dead zone. However, by this approach, I can't tell when the axis is no longer pushed and goes back to the center. It's a very typical usage of joystick axis but I couldn't find helpful info elsewhere. Thanks in advance.


texts: J2ME character animation with multiple sprite sheets

texts:
I'm working on a J2ME game and I want to have walking animations.

Each direction of walking has a separate sprite sheet (i.e. one for walking up, one for walking right etc), I also have a static idle image for each direction held together in a single file. I've tried to hold an array of sprites in my player class and then just drawing the sprite corresponding to the current direction, but this doesn't seem to work.

I'm aware that if I combine all the animations into one sprite sheet I could set up different animation sequences, but I want to be able to do it with separate images for each animation.

Is there a way that anyone knows of to achieve this? And ideally without too much extra code (as opposed to combining the sprites into one sheet)


texts:
My brother has taken an interest in making games on the DS (via PALIB). I'm worried that since its a homebrew game and homebrew development on the DS is not officially supported, his programming would go to waste.

Is there any significant differences in programming via PALIB over Nintendo's official DS SDK?


texts:
My game runs at several hundred frames per second. I want to limit it to 60. So I used

    Application.targetFrameRate = 60;

This works on the iPhone. But in the editor it only reduced the frame rate to around 80-90. Am I missing yet another setting?

Mac OSX Mavericks.


texts: Collision detection between a sprite and rectangle in canvas

texts:
I'm building a Javascript + canvas game which is essentially a platformer. I have the player all set up and he's running, jumping and falling, but I'm having trouble with the collision detection between the player and blocks (the blocks will essentially be the platforms that the player moves on).

The blocks are stored in an array like this:

var blockList = [[50, 400, 100, 100]];

And drawn to the canvas using this:

this.draw = function() {
    c.fillRect(blockList[0][0], blockList[0][1], 100, 100);
}

I'm checking for collisions using something along these lines in the player object:

this.update = function() {
    // Check for collitions with blocks
    for(var i = 0; i < blockList.length; i++) {
        if((player.xpos + 34) > blockList[i][0] && player.ypos > blockList[i][1]) {
            player.xpos = blockList[i][0] - 28;
            return false;
        }
    }

    // Other code to move the player based on keyboard input etc
}

The idea is if the player will collide with a block in the next game update (the game uses a main loop running at 60Htz), the function will return false and exit, thus meaning the player won't move.

Unfortunately, that only works when the player hits the left side of the block, and I can't work out how to make it so the player stops if it hits any side of the block. I have the properties player.xpos and player.ypos to help here.


texts:
How can one achieve a dynamic glow effect in Java Slick2d? I want an image to be surrounded by a glow when I move my mouse over it for example.

Example:

No glow

Glow

Is it possible to make this programmatically?


texts: How to make gameObjects in Unity move in predefined patterns easily

texts:
I am trying to make a bullet hell game. I want my 2D enemies to move in predefined, curving patterns. How should I do this?

The difficulty I have is being able to quickly produce enemy movements that are

(A) predefined, not random

(B) curved

(C) easy to make, with little coding

(D) visually able to see what is going on, maybe in the inspector?

Perhaps a 3rd party tool may be warranted?


texts: How to keep track of (count) vertices processed so far in GL ES SL 2.0 vertex shader?

texts:
I'm trying to learn how to use GLSL ES 2.0.

In OpenGL ES 2.0, there is no gl_VertexID keyword to obtain the number of vertices processed so far. So I was wondering if there's a way to make my own counter. I know the vertex shader is executed "per vertex," so if I can increase a counter which persists between executions then that will meet my case.

Now I know I can't use a uniform because by definition they cannot be altered.

So I thought about using an attribute, assuming the value will persist between vertex shader executions, but when I write

attribute int a_vertexCounter;

in my vertex shader, the shader compiler says that an attribute cannot have the type int.

So I thought maybe if I make a_vertexCounter a vec3 for example, and increment the first component of that vector instead... This works, except that when I try

gl_Position = u_MVPMatrix * u_canPos[int(a_vertexCounter.x)];

the compiler says

Error compiling shader: 0:23: S0027: Cannot modify an input variable

I also tried setting my attribute variable to be of type ivec3 but the shader says that's not allowed either.

Maybe there's no way to do this without ES 3.0, where I could simply use gl_VertexID ?


texts: Swapping Y and Z causes problems with Camera

texts:
I am trying to swap the Y and Z axis in my program.  Everything worked great when Y used to be the axis coming out of the plane.  After having swapped y and x,  I have been able to draw my terrain using the X Y as the plane and Z as the height, however when converting the code for the camera I am running into trouble.

Here is the code that gives me the correct camera (so y is the axis coming out of the plane), along with an illustration.  The code is in SharpDX which is a C# wrapper for DirectX

// Setup the position of the camera in the world.
      Vector3 position = new Vector3(PositionX, PositionY, PositionZ);

      // Setup where the camera is looking  forwardby default.
      Vector3 lookAt = new Vector3(0, 0, 1.0f);

      // Set the yaw (Y axis), pitch (X axis), and roll (Z axis) rotations in radians.
      float pitch = RotationX * 0.0174532925f;
      float yaw = RotationY * 0.0174532925f;
      float roll = RotationZ * 0.0174532925f;

      //// Create the rotation matrix from the yaw, pitch, and roll values.
      Matrix rotationMatrix = Matrix.RotationYawPitchRoll(yaw, pitch, roll);

      // Transform the lookAt and up vector by the rotation matrix so the view is correctly rotated at the origin.
      lookAt = Vector3.TransformCoordinate(lookAt, rotationMatrix);
      Vector3 up = Vector3.TransformCoordinate(Vector3.UnitY, rotationMatrix);

      // Translate the rotated camera position to the location of the viewer.
      lookAt = position + lookAt;

      // Finally create the view matrix from the three updated vectors.
      ViewMatrix = Matrix.LookAtLH(position, lookAt, up);

Here is an illustration of what this produces, I am able to successfully move the camera around with the mouse by having the mouse differences affect the x and y rotation:

Now if I swap all the X and Y in my terrain, without affecting the camera, I get this:

So now the camera is facing the terrain directly, and attempts to yaw will not produce the desired view.  (the world will revolve around the camera when looking perpendicular to the terrain, and spin in place when looking at the horizon, the exact opposite of what we want.)

Now I thought that maybe if I just change the lookAt to 0, 1.0f, 0 ; swap the y and z rotations, and change the Up vector to use Vector3.UnitZ, it would solve all my problems.

// Setup the position of the camera in the world.
      Vector3 position = new Vector3(PositionX, PositionY, PositionZ);

      // Setup where the camera is looking  forwardby default.
      Vector3 lookAt = new Vector3(0, 1.0f, 0);

      // Set the yaw (Y axis), pitch (X axis), and roll (Z axis) rotations in radians.
      float pitch = RotationX * 0.0174532925f;
      float yaw = RotationZ * 0.0174532925f;
      float roll = RotationY * 0.0174532925f;

      //// Create the rotation matrix from the yaw, pitch, and roll values.
      Matrix rotationMatrix = Matrix.RotationYawPitchRoll(yaw, pitch, roll);

      // Transform the lookAt and up vector by the rotation matrix so the view is correctly rotated at the origin.
      lookAt = Vector3.TransformCoordinate(lookAt, rotationMatrix);
      Vector3 up = Vector3.TransformCoordinate(Vector3.UnitZ, rotationMatrix);

      // Translate the rotated camera position to the location of the viewer.
      lookAt = position + lookAt;

      // Finally create the view matrix from the three updated vectors.
      ViewMatrix = Matrix.LookAtLH(position, lookAt, up);

However, doing this, I get the same issue as before, the world will revolve around when looking perpendicular to the ground, but spin in place when looking parallel to the ground (so towards the horizon).  I believe the camera now looks like this:

Which doesn't make sense to me, since I thought changing the Up vector to UnitZ would make Z face up and not parallel to the ground.  Any suggestions to change the second code block is appreciated.


texts: What should I use for the event name when logging metrics with Flurry?

texts:
I'm working on a multiplayer game and I want to use Flurry to record game events.

In the game you can build, grow and train troops. In Flurry you can log an event (optionally with parameters).

It would be great to be able to track the progress of a player depending upon what kinds of things they build, grow and so on and at what experience levels they do that at, but I don't know whether it's best to just have different sets of events for different types of actions... like this:

NSDictionary *buildParams =
   [NSDictionary dictionaryWithObjectsAndKeys:
      @"Build_Type", @"Castle",
      @"EXP", @"234523", // Capture user status
      nil];

[Flurry logEvent:@"Build_Action" withParameters:buildParams];

And so on... so another for growing something, another for training, et cetera.

Or is it better to have one global type of record of an event like this:

NSDictionary *actionParams =
   [NSDictionary dictionaryWithObjectsAndKeys:
      @"Action", @"Build",
      @"Type", @"Castle",
      @"EXP", @"44234",
      nil];

[Flurry logEvent:@"Game_Action" withParameters:actionParams];

In this method all the data is stored in the one event type. I'm not sure which will give me the best result when it comes to funneling, segmentation, and all that?


texts:
Over on Code Golf Stack Exchange, competitions are run where multiple programmers compete against one another. One particular class of challenges is "King of the Hill". Here is an example of a King of the Hill challenge. The unique aspect of King of the Hill is that the players must interact until a winner emerges. Most of the other competitions are non-interactive.

When interaction is introduced into a game, collusion become an issue. In real life, collusion is often not in the best interest of the players due to social consequences. However, on the Internet, the social factors play an almost nonexistent role. Anonymity allows multiple players to collude in private, or even allow a single person to manipulate multiple players.

I really have two questions, but they both address the same problem from different angles.

How can collusion be discouraged or prevented in an online, multiplayer, interactive game?
How can collusion be caught and punished in an online, multiplayer, interactive game?

Things to keep in mind:

This is not a Kingmaking scenario. "Kingmaker" specifically describes a player who chooses to collude as a result of being doomed to lose.
One player may unintentionally help another player while trying to win. This is not collusion.
Simply prefacing every challenge with "No colluding allowed." will lead to an argument over what constitutes collusion. Can it be objectively defined, given the previous bullet point?
In case anyone is unfamiliar with the culture differences between sites, Code Golf Stack Exchange does not subscribe to the "Question and Answers" format. The format is geared towards "Challenge and Solutions".

I found some information on collusion detection from online poker sites. They detect collusion by flagging accounts who always play at the same table, and either manually or automatically take action. This solution does not translate well to the Stack Exchange format, but it seems like a step in the right direction.


texts: How do I detect a tile map collision's direction?

texts:
I'm implementing collision detection with the map for my platformer. I have a method that generates a polygon on every tile and checks if the player hits it -- that's all fine. The problem is that when ever a player touches a wall in front of him the d key which moves him to the front gets disabled so he can't walk any further that way.

This method works great for preventing him from walking into walls, but I also want him to be able to jump on the walls and there is the problem. So he falls on the tile(polygon) the game senses that and applies the same method for the d key, preventing the character from walking left or right, because the game thinks it is hitting the tile in the front but it is hitting from above.

Long story short, the game handles collision from above same as from the front or back. How do I make it recognise collisions from the side separately from above?

My code is along these lines:

if(PlayerPolygon.interesects(TiledPolygon) && dKey==1) {
         moveX = 0;
}
if(dKey==1) {
  player.x +=moveX
}


texts: MonoGame SharpDX Error 'The Parameter is Incorrect' when using graphics.DrawUserPrimitives

texts:
Below is a small section of code that is meant to draw a multicolored triangle to the middle of the screen in a MonoGame game. This uses the basic function DrawUserPrimitives to draw the triangle. This works fine in XNA, but the moment i try to use it in a MonoGame DX game (Which compiles using SharpDX) it will crash with the following error:

An unhandled exception of type 'SharpDX.SharpDXException' occurred in SharpDX.dll

Additional information: HRESULT: [0x80070057], Module: [General], ApiCode: [E_INVALIDARG/Invalid Arguments], Message: The parameter is incorrect.

Below is the code that is causing the error.

private void SetUpVertices() {
        vertices = new VertexPositionColor[3];

        vertices[0].Position = new Vector3(-0.5f, -0.5f, 0f);
        vertices[0].Color = Color.Red;
        vertices[1].Position = new Vector3(0, 0.5f, 0f);
        vertices[1].Color = Color.Green;
        vertices[2].Position = new Vector3(0.5f, -0.5f, 0f);
        vertices[2].Color = Color.Yellow;
    }

    public void Draw(GameTime gameTime) {
        gDevice.DrawUserPrimitives(PrimitiveType.TriangleList, vertices, 0, 1, VertexPositionColor.VertexDeclaration);
    }

Has anyone ever come across simillar errors using the DirectX version on MonoGame and SharpDX when dealing with primatives? And do you know of a way I can fix this issue?


texts: E_FAIL: An undetermined error occurred (-2147467259) when loading a cube texture

texts:
I'm trying to implement a skybox into my engine, and I'm having some trouble loading the image as a cube map.  Everything works (but it doesn't look right) if I don't load using an ImageLoadInformation struct in the ShaderResourceView.FromFile() method, but it breaks if I do.

I need to, of course, because I need to tell SlimDX to load it as a cubemap.  How can I fix this?

Here is my new loading code after the "fix":

public static void LoadCubeTexture(string filename)
{
    ImageLoadInformation loadInfo = new ImageLoadInformation()
    {
        BindFlags = BindFlags.ShaderResource,
        CpuAccessFlags = CpuAccessFlags.None,
        Depth = 32,
        FilterFlags = FilterFlags.None,
        FirstMipLevel = 0,
        Format = SlimDX.DXGI.Format.B8G8R8A8_UNorm,
        Height = 512,
        MipFilterFlags = FilterFlags.Linear,
        MipLevels = 1,
        OptionFlags = ResourceOptionFlags.TextureCube,
        Usage = ResourceUsage.Default,
        Width = 512
    };
    textures.Add(filename, ShaderResourceView.FromFile(Graphics.device, "Resources/" + filename, loadInfo));
}

Each of the faces of my cube texture are 512x512.


texts: I am looking for some tutorial or equation how to map texture from square to "curve" or "bend". (Example on image below) I have tried to convert coordinates of unit circle to UV, but that gives me incorrect result around corners.


texts: How to use images/text/etc. in XNA without Content Pipeline?

texts:
I'm currently writing a program in C# with the XNA framework. It is absolutely necessary for the game's images and text assets to be visible by the end user in the form of PNG files, so I can't use the content pipeline.

How would I go about using graphics and text in my XNA game without it?


texts: In what instances would you want to use path-finding algorithms other than A*?

texts: I am familiar with how the common ones technically work (BFS, DFS, Dijkstra, A*) but as far as their realistic benefits I don't quite see the need for them. Considering that, given the right heuristics, A* is more performant then why bother with any others?


texts: Determine if ray hits an edge of a model in Unity 3D

texts:
How can i determine if a ray was hitting an edge of a mesh?

The figure below shows what I want to achieve:

Any ideas?


texts:
I'm trying to make a TextMesh appear when ever an enemy prefab is hit.

I currently have this functionality working. However, the text doesn't face the direction the players camera is looking.

At the moment my OnCollisionEnter method contains the following line of code:

GameObject _go = (GameObject)Instantiate(_hitPrefab, collision.gameObject.transform.position, Camera.mainCamera.transform.rotation);

This line happily creates my TextMesh whenever my enemy is hit. I know my issue has something to do with my rotation quaterion, but I have no idea what pass in so it faces my camera. As you can see, I tried setting it Quaterion.Idenitiy thinking it'll show the same way as the enemy it's associated to, but that doesn't work either.

Each time the textmesh appears, its back to front for the player and at a slight angle.

Could someone please help me in getting it so the score always faces the players camera no matter what way he is facing?


texts: Creating 2D worldbuilding games like Terraria or Starbound in frameworks like PhaserJS or PixiJS?

texts: Frameworks like Phaser or Pixi support tilemaps, but I'm curious if that is already enough to get a map where the player can change everything that he wishes. I'm also not sure if browsers would be able to handle this in terms of performance


texts: Glow with forward rendering without two passes/MRT?

texts:
I am trying to implement controllable bloom. By controllable I mean bloom that can be requested even for non-bright pixels by adding the bloom value into a model's texture channel. To do this I need to somehow pass this value (the strength of the bloom for the current pixel) into the bloom post-processor. The most obvious choice would be storing it in the alpha channel, but I use alphablending for every model I draw so for me this is not an option. A quick and dirty solution is to use MRT, render to two textures and then recombine them into one which is a huge waste of memory and speed. Another solution could be to render the scene twice: once for the color and alpha components and second for the bloom components - that is the by-the-book method I find on every internet page. Even when rendering into a smaller RT this is still an overkill.

Another thing I thought about was using YCbCr encoding and then simply increasing Y to order bloom, but I always get a green-ish image after decoding (even if I encode-decode in the very same shader, line after line). Here is the encode-decode operations I did:

inline float3 RGBtoYCbCr(float3 color)
{
    float3 YCbCr;
    YCbCr.r = color.r*0.299f + color.g*0.587f + color.b*0.114f;
    YCbCr.g = 0.5f + (-color.r*0.168f - color.g*0.331f + color.b*0.5f);
    YCbCr.b = 0.5f + (color.r*0.5f - color.g*418 - color.b*0.081f);

    return YCbCr;
}

inline float3 YCbCrtoRGB(float3 color)
{
    float3 RGB;
    RGB.r = color.r+1.402*(color.b-0.5f);
    RGB.g = color.r-0.344*(color.g-0.5f)-0.714*(color.b-0.5f);
    RGB.b = color.r+1.772*(color.g-0.5f);

    return RGB;
}

float4 MainShader(...)
{
    ...
    output.COLOR.rgb = saturate(output.COLOR.rgb);

    output.COLOR.rgb = RGBtoYCbCr(output.COLOR.rgb);
    output.COLOR.rgb = YCbCrtoRGB(output.COLOR.rgb);
}

So I wanted to ask if anyone knows a way to do it in one pass without MRT and (if possible) by still rendering an HDR image?


texts: Can I create mods for a D3D game made in C#?

texts:
There is a game currently in development in C# (using Direct3D for graphics) that I want to make mods for.

Ideally, I would like to make the mods in C#, but after that I am lost. How would I (or other people) put the finished mod into their version (client) of the game? I know that for Java this is pretty simple (as shown by all the Minecraft mods in the wild) but is it harder (or even possible) for a language like C#? Is there something special the devs have to do to make sure modding is possible?