texts:
I am making a simple 2d game for WP in monogame/xna and am at a point where I want to save data. I have created a method to serialize the data (index, counter and percentage counter) to an isolated storage file in xml format. There is also a subsequent method to deserialize the file. My question is simply, what point is best to save the game, because at the moment I save when the a pause screen is loaded over the gameplay screen - However, this wont save the data if the player exits the app. I am certain I am saving in a silly place.
Hence, I am wondering what the common practice is for saving?
Any help/advice would be greatly appreciated.

Here is my save method:

    public void SaveData()
    {
        const string filename = "data.vision";
#if WINDOWS_PHONE
        IsolatedStorageFile dataFile = IsolatedStorageFile.GetUserStoreForApplication();
#else
        IsolatedStorageFile dataFile = IsolatedStorageFile.GetUserStoreForDomain();
#endif
        try
        {
            // Create an isolated storage stream and initialize it as null.
            IsolatedStorageFileStream isolatedFileStream = null;

            // Check the data file already exists.
            if (dataFile.FileExists(filename))
            {
                // Open the file using the established file stream.
                using (isolatedFileStream = dataFile.OpenFile(filename, FileMode.Open, FileAccess.ReadWrite))
                {
                    // Read the data from the file.
                    XmlSerializer serializer = new XmlSerializer(typeof(Data));
                    // Store the deserialized data object.
                    Data savedData = (Data)serializer.Deserialize(isolatedFileStream);

                    // Loop through the LevelData objects within savedData.
                    for (int i = 0; i < savedData.Levels.Count; i++)
                    {
                        // Get the LevelData object in question.
                        LevelData levelData = savedData.Levels[i];

                        // Check to see if the index of the levelData object corresponds to the active level index.
                        if (levelData.Index == mLevelIndex)
                        {
                            // Increment the stored attempts by the current attempt counter.
                            levelData.Attempts += mLevel.AttemptCounter;

                            // Check if the stored completion percentage is less that the current percentage.
                            if (levelData.PercentComplete < mLevel.PercentComplete)
                                levelData.PercentComplete = mLevel.PercentComplete;

                            //System.Diagnostics.Debug.WriteLine("new attempts  " + levelData.PercentComplete);
                        }
                        // Update the level data element within the saved date.
                        savedData.Levels[i] = levelData;
                    }
                    // Set the position to the begining of the file.
                    isolatedFileStream.Seek(0, SeekOrigin.Begin);
                    // Serialize the new data object.
                    serializer.Serialize(isolatedFileStream, savedData);
                    // Set the length of the file.
                    isolatedFileStream.SetLength(isolatedFileStream.Position);
                }
            }
    }


texts:
I'm trying to create a wraparound map for a hexagonal map, so when you exit a tile on one side of the big hexagon-shaped map, you enter a tile on the other side.

Example image from Red Blob Games article on Hexagonal Grids.

In the image, the pale tan hexagonal chunk in the center is our map. The greenish/reddish chunks around it are shifted copies of the same map. If we stand on the blue tile under the cursor and walk off the main map into the green copy to the right, that's the same as wrapping around our map to the corresponding point on the other side: here, walking from the blue tile in the lower-right-hand red copy into the bottom-right corner of the center map.

I used an approach with a lookup table first. But as soon as those maps get too big, the lookup tables get even bigger. I'm searching for a solution which works without a lookup table.


texts: In HLSL script, why does random function produce negative values?

texts:
I'm currently learning shader scripting with Unity HLSL language and this awesome resource: https://thebookofshaders.com

I created my random method and a zeroOrOne method which just return 0 or 1 according to a given and the worlposition

const static float randomMultiplier = 43758.5453123f;
const static float2 randomDotVector = float2(12.9898f,78.233f);

float random2d (float2 st) {
    return frac(sin(dot(st, randomDotVector)) * randomMultiplier);
}

float zeroOrOne (float probability, float2 pos) {
    float r = random2d(pos);
    return saturate(sign(probability-r));
}

In order to chase down little bug, I simplified my zeroOrOne method to:

float zeroOrOne (float probability, float2 pos) {
    float r = random2d(pos);
    return sign(r + 0.001f);
}

And here's what I can observe :

What I understand is: if some pixels remain black, the result of sign(r + 0.001f) is 0, or -1.
This means that r can be less or equal to 0.001. But r should be a frac of a sin, and frac is between 0 and 1!!

Is there some floating point black magic here?

Does it depends of the device architecture? (I'm on a macbook, no graphic card)

Does I miss something?

EDIT: I forced the random value to be positive only, and the strange pixels remains...

Here's the code, simplified to minimum.
https://gist.github.com/martinprot/f3071b6036ae9b72f17ef941c4734a48

EDIT: I tried on another computer, with a real CG. The bug does not occur on this machine!


texts: How to make animated 2D texture on 3D cube with XNA 4

texts:
I'm looking for how to make 3D gauge on Windows Phone 7, that's mean a 3D object (a watch for example) with a basic 2D texture (= Numbers of my watch) and a rotating 2D texture (=neddle of my watch). The shaders can't be used for this (WP7 !!).

I did not find anything on this (books or internet).

There are 2 big problems for me :
   1) load 2 textures on the same object.
   2) rotating one of this 2D texture and update it on the 3D model.

algorithmic I use for is:

In LoadContent()

1) load 3D model + Final 2Dtexture  + Basic 2Dtexture and rotating 2Dtextures
 2) Apply final 2Dtexture on 3D object
 3) Load RenderTarget2D and SpriteBatch

In Draw()

1)Use TargetRender as back buffer
 2)draw Basic 2dTexture and Rotate Rotating 2Dtexture with spritebatch
 3)put the back buffer into my Final 2DTexture
 4) free the back buffer

But that's not working at all !!!

If you have idea or interesting links, thanks for help.

JeanGil


texts: Why doesn't the Source engine clear the back buffer?

texts: In the Source engine, when the map does not have a sky box, I see that typical artifact from the back buffer not being cleared. Why does the Source engine do that? Is it a performance reason, or something like that?


texts: I'm working on a 2D pixel art Unity game. I have multiple layers of scrolling so I need to use a perspective camera, the problem is though that it seems to mess up using particles as when the screen scrolls the particles move in perspective, when I need them to stay just in the x and y. Is there way to achieve this? I don't particularly want to go through every particle in real time and zero out their Z value, but maybe that's the only way?


texts: circle - rectangle collision in 2D, most efficient way

texts:
Suppose I have a circle intersecting a rectangle, what is ideally the least cpu intensive way between the two?

method A

calculate rectangle boundaries
loop through all points of the circle and, for each of those, check if inside the rect.

method B

calculate rectangle boundaries
check where the center of the circle is, compared to the rectangle
make 9 switch/case statements for the following positions:

top, bottom, left, right
top left, top right, bottom left, bottom right
inside rectangle

check only one distance using the circle's radius depending on where the circle happens t be.

I know there are other ways that are definitely better than these two, and if could point me a link to them, would be great but, exactly between those two, which one would you consider to be better, regarding both performance and quality/precision?

Thanks in advance.


texts: spritekit sidescroller how to move hero through the level

texts:
I am trying to learn spritekit by working my way through developing a simple side scrolling game, but I cannot find a clear answer on how to move the hero through the level.

The width of my ground far exceeds the width of the view and I have always thought it was best to move the ground not the hero, but my enemies (who pace back and forth) tend to move much more quickly as the hero moves and to the wrong spot. I am guessing this is because the ground is moving and changing their destination during the move action.

Is moving the ground (not the hero) the best way to create a sidescroller without a repeating landscape. If so, how do I create enemies that move in a restricted area like mario?

Here is a portion of my code:

let enemy = SKSpriteNode(imageNamed: "enemyWalk1.png")

override func didMoveToView(view: SKView) {

    enemy.physicsBody = SKPhysicsBody(texture: SKTexture(imageNamed: "enemyWalk1.png"), size: enemy.size)
    enemy.physicsBody = SKPhysicsBody(rectangleOfSize: enemy.size)
    enemy.physicsBody!.affectedByGravity = true
    enemy.physicsBody!.allowsRotation = false
    enemy.physicsBody!.dynamic = true

    enemy.position = CGPoint(x:CGRectGetMinX(self.frame) + enemy.size.width + 800, y:CGRectGetMinY(self.frame) + ground!.frame.size.height + enemy.size.height)
    self.addChild(enemy)

    var enemyGoTo1 = enemy.position.x + 100
    var enemyGoTo2 = enemy.position.x - 100

    var enemyXScale1 = SKAction.scaleXBy(1, y: 1, duration: 0.0)
    var enemyXScale2 = SKAction.scaleXBy(-1, y: 1, duration: 0.0)

 enemy.runAction(SKAction.repeatActionForever(SKAction.animateWithTextures(enemyTextureArray, timePerFrame: 0.15)), withKey: "enemyWalk")
    enemy.runAction(SKAction.repeatActionForever(SKAction.sequence([enemyXScale1, SKAction.moveToX(enemy.position.x + 100,duration: 1.5), enemyXScale2, SKAction.moveToX(enemy.position.x - 100,duration: 1.5), enemyXScale1, enemyXScale2])))

}

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    for touch in (touches as! Set<UITouch>) {
        let location = touch.locationInNode(self)

        if nodeAtPoint(location) == rightArrow {
                rightTouched = true

            }
        }
}

override func update(currentTime: CFTimeInterval) {
        if rightTouched == true {
            childNodeWithName("ground")!.position.x = childNodeWithName("ground")!.position.x - 8
        }
}


texts: Handling strange physics behaviour while sliding between coplanar surfaces

texts:
We've got a character setup based around manually resolving collisions, and we're using bullet to do so. Our characters have a kinematic rigidbody to push things around, but their movement and positioning is done using a separate (pair caching) ghost object. Every physics tick we iterate over all contacts for that ghost and resolve collision either by depenetrating 100% when it's ground, or by depenetrating gradually/not at all with walls or other characters. We then apply our ghost's new position to the kinematic rigidbody so that can interact with other physics objects.

Unfortunately, when moving around a flat world made up of a bunch of coplanar blocks, when the characters moves from one block to another it will often do one of two things;

Fall through the cracks
Get bumped upward a significant distance (we're talking up to half a unit/meter with a character that is 2 units/meters tall)

Debugging this tells me sometimes these contact points are unexpected, and not something I want to resolve by depenetrating 100%. Gravity moving the character downward can result in a contact point that is closer to the side of the terrain block than the top, and it will give you a normal/distance accordingly (blue arrow). Resolving that with 100% depenetration will just push you in between the blocks, while not counteracting the gravity forces. This would explain the falling through the cracks. But I don't know why I sometimes get contact points with normals pointing straight up, but with a distance that would place the collider far above the ground (purple arrow).

I've come to the point where I feel like my only option to handle character movement like this is by not colliding with the ground at all, and just spherecast downwards at the character's position on the horizontal plane just to place it down on the ground properly.

Now obviously I want to get rid of this behaviour. And seeing how you don't see this happen in many games, I'm lead to believe others have solved this issue somehow. Has anyone here encountered similar issues, and how did you go about fixing them?


texts:
I have a 1920x1200 shadowmap which just has the depth values of my scene drawn from the point of view of the light.

I also have a 1920x1200 gbuffer that draws my scene to a fullscreen quad.

How can I sample the shadowmap from the gbuffer lighting phase? What kind of maths needs to be performed? I have access to view space normal and view space position.


texts: Error in unity : The type or namespace name RigidBody could not be found

texts:
i m new to unity and got stuck in a problem , i have searched unity forum but could not get an answer to solve my problem.
getting this error.

The type or namespace name RigidBody could not be found. Are you missing a using directive or an assembly reference?

using UnityEngine;
using System.Collections;
public class playercomponent : MonoBehaviour {

public RigidBody rb;

void start()
{
    this.rb =  GetComponent<Rigidbody>();
}
void FixedUpdate()
{

    float moveHorizontal = Input.GetAxis("Horizontal");
    Float moveVertical = Input.GetAxis("Vertical");
    Vector3 movement = new Vector3 (moveHorizontal,0.0f,moveVertical);

    rb.AddForce(movement);

}

}


texts:
I have two objects (target and player), both have Position (Vector3) and Rotation (Quaternion).  I want the target to rotate and be facing right at the player.  The target, when it shoots something should shoot right at the player.

I've seen plenty of examples of slerping to the player, but I don't want incremental rotation, well, I suppose that would be ok as long as I can make the slerp be 100%, and as long as it actually worked.

FYI - Im able to use the position and rotation to do plenty of other things and it all works great except this last piece I cant figure out.

Code samples run in the Target's class, Position = the targets position, Avatar = the player.

EDIT

Im now using Maik's c# code he has provided and it works great!


texts: Wrong pivot point of parent / wrong scale of children

texts:
I'm trying to make two objects, in is an intact glass, the other one is the glass but shattered.

So for the shattered glass, in Maya I make a Plane, cut it with the multi-cut tool, extrude the faces, select the object and then separate. So I have every single piece of the glass as a single object. After that, I select them all, Modify->Center Pivot.

Now when I import this into unity, this is where the problems arrive.

When I rotate the native parent object, which holds all the glass pieces, it looks right:

Native Parent Rotation

When I rotate all the child glass pieces, the distort some weird way, the scaling is really off on one axis and they appear very thin:

Native Child Rotation

Now, when I create a new empty GameObject on root level, and simply add all the children glass pieces to this object, they rotate just fine and have the right scaling:

New Parent - Child Rotation

But now, when I rotate the parent, the pivot point seems to be completely off:

New Parent - Parent Rotation

The rotation I make is a simple gameObject.transform.Rotate (Vector3.left);

How can I achieve the correct pivot point for the parent, and avoid the weird scaling issues on the children? I need to be precise of course, because the shattered parent object is supposed to replace the intact glass object 1:1 after a collision.


texts: What type of Collider should I add to a LineRenderer?

texts:
I am currently building a game where I need to generate some wires (as Bézier curves) using LineRenderer. After changing the width of each line

lineRenderer.SetWidth (0.15f, 0.15f);

I am attaching an EdgeCollider2D to the same game object (specifying the same points used in generating the Bézier curve). This seems to work. However, I would like to be able to know if the Mouse Pointer is at any time over the EdgeCollider2D (something similar to the popular Fruit Ninja game). I'm using Raycast as follows:

void CastRay() {
    Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
    RaycastHit2D hit = Physics2D.Raycast (ray.origin, ray.direction, Mathf.Infinity);

    if (hit) {
        Debug.Log (hit.collider.gameObject.name);
    }
}

I'm calling the CastRay method inside the Update method. Because EdgeCollider2D does not have width (as expected), the log message is never produced.

Do I need to use a different type of Collider? Do I need to call CastRay somewhere else?


texts: How can I use Drag handlers (IBeginDragHandler, IEndDragHandler, IDragHandler) with a 2D sprite renderer instead of a UI Image?

texts:
In my game, I assigned all of the blocks to be 2D sprites so that they could be easily converted into prefabs:

However, when designing the drag and drop scripts, I noticed that all of the drag and drop handlers such as IBeginDragHandler, IEndDragHandler, IDragHandler, etc. weren't working at all. I later noticed that these were intended to be used by UI Images.
Now I am left wondering what I can do to make these 2D Sprites be usable by these functions for UI Images. Do I have any other options other than to start from scratch by making new UI Images?
Here's the small amount of code needed to create a reproducible example:
Public class DragDrop : MonoBehaviour, IBeginDragHandler, IEndDragHandler, IDragHandler
{
    [SerializeField]
    private Canvas canvas;
    private CanvasGroup canvasGroup;

    private RectTransform rectTransform;

    private void Awake()
    {
        rectTransform = GetComponent<RectTransform>();
        canvasGroup = GetComponent<CanvasGroup>();
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
        canvasGroup.alpha = 0.6f;
        canvasGroup.blocksRaycasts = false;
    }

    public void OnDrag(PointerEventData eventData)
    {
        rectTransform.anchoredPosition += eventData.delta / canvas.scaleFactor;
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        canvasGroup.alpha = 1f;
        canvasGroup.blocksRaycasts = true;
    }
}


texts: Texture packer and 2d game sprite sheet creation

texts:
I am developing a game in Unity3D. I have a bunch of images which display the character animations. I decided to use texture packer to reduce the amount of individual images. I create one sprite sheet with type multiple containing all the images of my animation.

After creating the sprite sheet the animation broke up. The images start to overlap and not animate in the same speed  despite the fact that before the animation was working fine but heavy on my app.

The spritesheet was created by importing all my assets for every animation into texture packer and export it into png file with a dimension of: 4096x4096


texts: Operating Expenses of Mathmetic Operations

texts:
I understand that math operations require more resources/take longer than others when being computed. (e.g. square roots take longer than divisions which takes longer than multiplications which takes longer than additions)

Are there known times for how long specific operations take or methods with which to measure said times?
(I'm guessing no for the former based on the wide variety of hardware that exists. I'm technically looking for measurements related to Game Maker: Studio 2 if it matters)

(P.S. Sorry if the tags for this question are wrong.)


texts: Using a object as origin for a Raycast using mouse position as direction

texts:
Is there any way to cast a ray from an object using the mouse position as the direction for the ray?
I´ve been looking for a while but I can´t find something like that anywhere, so if anyone could help with this it would be great.

I´m using kind of a top view, you can see how here:

And what I want to do is set a empty game object on top of the character to act as the origin for the ray, then when I press a key the mouse is unlocked and an area appears, here´s how that looks:

And I want to use the position where the mouse clicks to be the direction of the ray.


texts: No local transform with skinned mesh with assimp?

texts:
I'm trying to add skeletal animation to my engine and I'm importing meshes with assimp, but I think I misunderstood the skinned mesh concepts (or don't understand assimp).
When I import a model, everything works fine, regardless of mesh hierarchy. I'm using collada files.
Here's how the model should look if it was imported correctly:

However, if I try to import skinned meshes, I get something really weird like this:

It happens because each mesh is imported without any local transform and everything stays in the wrong place/rotation.
But shouldn't the model stay the same as the first picture, because it should work even if it don't have a skinned mesh? Shouldn't the bone transform just be the offset matrix to convert from mesh space to bone space when using animation data to interpolate between key frames? I'm really confused.
I'm learning from Tutorial 38 - Skeletal Animation with Assimp.


texts: Shared Object Not saving the level Progress

texts:
I am making a flash game in which i have a variable levelState that describes the current level in which user has entered I am using SharedObject to save the progress
but it does not do so
first i declred a clas level variable

private var levelState:Number = 1;
private var mySaveData:SharedObject = SharedObject.getLocal("levelSave");

in the Main function i am checking if it is a first run of the game like below

if (mySaveData.data.levelsComplete == null)
    {
        mySaveData.data.levelsComplete = 1;
    }

and in a function where the winning condition is checked so that levelState could be increased i am usin this sharedobject to hold the value of levelState

if (/*winniing condition*/)
    levelState++;
    mySaveData.data.levelsComplete = levelState;
    mySaveData.flush();
    setNewLevel(levelState);
}

but when i play the game clear a level and again run the game it does not start from that level it starts from beginning.


texts: Considerations of using online portal for game testing and feedback

texts:
I am working on a fairly simple indie game. I wanted to get some live feedback before taking the game all the way to completion. I am able to release a beta version with stripped down graphics, and was thinking of putting this on an online game portal like Kongregate. If the game is popular I will carry on and make a more advanced version to release on the various app stores.

My question is, are there any pitfalls to think about regarding the above? How far along should the final game be before releasing the demo? Here are my thoughts so far:

Pro:

Good way to test and get feedback
Some revenue if portal features royalties

Con:

Possibility for game to get cloned/ripped off
Smaller audience for final game if they played the online version


texts:
I am working on building a Strategy Game (Animal Colonies fighting each other).

It is going to be simple game targeting Kids, the beta version will only support single player playing against AI opponent.

I am going to hire Algorithm programmers to build the AI algorithms of the opponent, BUT :

I am not sure what information I need to give for the programmers in order to build these algorithms.
I want to have different AI levels difficulties (easy, medium, hard), BUT if the AI opponent is too easy to defeat, the game is boring, while if it is too difficult to defeat, the game is too frustrating, and the player will quit, so I need this issue to be addressed when building AI for different levels.
I am not sure if the AI opponent should behave like a human player? I mean should the specification allow AI opponent to have access to all game resources ? or AI should behave like human player to use scouts to collect information about resources and enemy?

I need to identify these points. I want to write detailed specification so algorithm programmers can do the work as expected. All what I have at the mean time is Colonies design (characters/elements), maps with objects (grass, rocks, hills, tree .. etc).

So, what exactly do I need to give them in order to build opponent AI?


texts: Offset a camera/render without changing perspective

texts:
I need to offset a render so that the perspective / vanishing point doesn't change.  Or another way to look at it is that I need to adjust the vanishing point in my view so that instead of being at 0,0 xy it's where ever I want it to be.

Imagine a tall iPhone screen with some extruded 3d text at the top of the view.  You would see the bottom sides of the extrusion because the camera is below the object.  But now move the object to the bottom of the view.  Now you see the top sides of the extrusion because the camera is above the object.  Same if you move the camera instead of the object.  The vanishing point is at 0,0 in the window.

Now let's say I wanted to draw the 3d text as it would look at the top of the screen but I want to draw it at the bottom of the screen.  Forget about the cheat of rendering it to a texture and drawing that texture somewhere else.  How do I shift everything up or down without changing the perspective?  Is there an easy way?

In practice I only need to move the vanishing point up a little in my game.  Perspective is key to being able to play.  Basically when the ad banner is at the top of the screen the view is smaller height wise.  That moves the vanishing point down by half the size of the ad banner, and screws up the game play.

I'm using the standard camera look at matrix function and projection matrix function that is based on the fov...

lookAtMatrix(cameraPos, camLookAt, camUpVector, mView);
matrixPerspective(cameraFOV, near, far,  aspect, mProjection);

I'm assuming that I need to change my mProjection somehow.


texts:
I'm currently trying to create a game that involves the inside of a cube, which i will make in Maya. My question is what is the best way to create a model with hit detection in mind?

For example my model will be a cube that you can walk inside of, so should i make the cube as a one model or make one wall and put it together inside XNA?

The reason I ask this is because I'm sure that if I create a whole cube and then use XNA's bounding rectangle method, hit detection will always be true because the bounding rectangle will encompass the whole cube, making collision detection inside the cube non existent without the use of hard values.

Whereas separate walls would make the process easier because i will checking against separate walls instead of the whole thing.

To add to the problem, I also have doors in the walls so hit detection for the walls in that area need to be turned off.

What is the best way to do this?


texts:
I've been wondering a lot lately about how to make an optimised server structuration, and i came to the conclusion that i severely lack knowledge on the subject.

I'll be doing this with either C, C++ or C#, with a preference for the latter.

Context:

I have a server that can operate more than 3K clients at one time.

This server is a game server, hence it only receives key inputs from the clients, for security measures.

Therefore the server is doing every operation on the user's data, and send back enough information to the client in order to display a personal GUI. (The server is of course a console application, don't get me wrong.)

Approaches:

1- 1 Client = 1 Logic Thread

(The thread does the player calculation)

Pros: every client runs his own server code, the server is more responsive to a particular client's request.

Cons: I do not have the insurance that a particular client will iterate its code 14 times while another would have iterated it 10, (so the two players, side by side, if it was for a movement operation, can become 4 squares afar, which should not be the case, as every player should move at an exact same speed)

Locking every thread to perform actions until a next logic loop happens can be quite devastating if something bad happens on any of the client, leading to severe lags in worst cases.

2- 1 Client = 1 Entry Thread, Main logic loop

(The thread receives the keys pressed by its client)

Pros: As the logic is all in the same loop, there is no desynchronization problems anymore.

Cons: Iterating ALL the game logic in one loop will most probably cause severe latency if the operations becomes advanced.

Moreover, if many clients are to catch up with all the current data being processed (sudden peak of connections), it would also cause additional latency, a partial solution would be to retrieve those datas in the Entry Thread.

3- 1 Client = 1 Entry Thread, X Logic threads, 1 Logic Thread synchronizer

(Entry thread receives keys, register the client in the concerned threads (One for each kind of action (Moving, Acquiring user data, Battle, Etc...)), Those threads gives the information whenever they can, and the Logic thread synchronizer ensures that tasks that needs to be "Ordered" in time are ordered.)

Pros: Share computation resources among all the Logic Threads, ensuring minimum latency for clients.

Cons: High vulnerability to resources concurrency, and if a particular task is done faster than another task that is to be synchronized with it, becomes as slow as the latter.

Question:

As i said earlier, i certainly lack knowledge about networking, threading, and concurrency, to efficiently order the structure of my program. Therefore, I'm asking it here:

What would be the best approach to take, and how should the global skeleton should be ordered to minimize latency, and permits a large number of synchronous users to play on the server.

Additional information

Maybe a bit of information about the idea behind this all will help.

My goal here is to create a server that will be used to run a simple RPG, which needs to have movement synchronization on the map (old school square-to-square movements), turn by turn instanciated battle (e.g. Dragon Quest, Final Fantasy, Pokemon), and exchange of user data (seeing X's profile, see how many monsters he killed, his guild, etc.)

If i'm asking for more than 3K clients at the same time, it is because i do not want to make a pile of junk that holds in place by a miracle. I want to further my knowledge on networking and its applied logic, would it be programmative logic or structuration logic.

So basically the problem is "Having a maximum of clients, on a minimally powerful server, therefore optimizing it as much as possible."


texts: How do I reverse "Cartesian->Isometric" function?

texts:
I'm working on an isometric tile rendering engine and I need to reverse a function I used to translate the Cartesian coordinates into isometric coordinates. I've already written a function for this, but I've been getting a strange logical error and I think it must be somewhere in my code for translating from isometric coordinates back into Cartesian. Anyways, here's the code for translating Cartesian->Isometric

    private Vector2 cartToIso(Vector2 init){
        Vector2 iso = new Vector2();
        iso.x = (((init.x - init.y) * TILE_WIDTH_HALF))+X_OFFSET;
        iso.y = MAP_HEIGHT-TILE_HEIGHT-((init.x + init.y) * TILE_HEIGHT_HALF);
        return iso;
    }

Any suggestions would be appreciated. Also if anyone was wondering, what I'm trying to do right now is create an algorithm for tile picking in my engine. The API(LibGDX) is a little strange in the sense that it uses a bottom-up Y coordinate system but with any of the input(ie, clicks) it uses a top-down Y coordinate system. I can post the code I have for tile picking later if anyone thinks they can help me more, but I'll save it for now since it's pretty long.

Edit:
This is the method I use to reverse it, and it seems to be giving me the incorrect results. Does this look correct?

    private Vector2 isoToCart(int x, int y){
        Vector2 cart = new Vector2();
        x = x-X_OFFSET;
        y = y-MAP_HEIGHT;
        cart.x = (x / TILE_WIDTH_HALF + (y / TILE_HEIGHT_HALF)) /2;
        cart.y = (y / TILE_HEIGHT_HALF -(x / TILE_WIDTH_HALF)) /2;
        return cart;
    }


texts:
I made a game with Unity but the size of .apk file got so large, it is about 70mb...
Is there some way that I can compress my apk file?


texts:
So i have been struggling with this for ages and I have now decided to reach out for help.

The Problem:

The game has two NPCs for reference we will call them "Ally" and "Enemy"

Ally and Enemy each have their own weapon:

Ally has a sword with a reach 0.1 - 2 meters
Enemy has a long sword that has a reach of 0.5 - 3 meters.

Now these two NPC's wish to fight each other. They need to make sure that they stay within the reach of their weapons while also making sure that they don't bump into each other.

For this I attempted the following algorithm:

bool shouldMove = false;
Vector3 lToTarget = Target.transform.position - transform.position;
lToTarget.y = 0f;

Vector3 lToTargetDirection = lToTarget.normalized;
float lToTargetDistance = lToTarget.magnitude;
float lRange = MinMeleeReach + MaxRange;
if (!shouldMove && lToTargetDistance > lRange + 1f)
{
    shouldMove = true;
}

if (shouldMove && lToTargetDistance <= Mathf.Max(lRange))
{
    shouldMove = false;
}

if (shouldMove)
{
    float lSpeed = Mathf.Min(MovementSpeed * Time.deltaTime, lToTargetDistance);
    transform.position = transform.position + (lToTargetDirection * lSpeed);
}

Now if they should not move then they would attack their target.

However as you might have guessed this has an issue:

The agent tries to keep his distance to the max of his range!

This sadly causes the agents to bug out in a way where they are never close enough to attack each other resulting in something that looks like this:

So i thought to my self how can i change this behavior.

I came up with another idea which sadly had the same problem this time using navmesh agent:

Vector3 direction =
    (transform.position - Target.position).normalized;
Vector3 finalPosition = Target.position + direction * maxRange;
navMeshAgent.SetDestination(finalPosition);

Again sort of same behavior, however, this time they just kept their distance and if the other agent came to close they would start moving backward. Which basically meant that they would move back to the end of the world.

So this is where I am at right now. I have attempted to google this issue however without much luck.

So i am really praying that you guys have an answer for me :)

if you need more information please do not hesitate to comment!


texts: What's the difference between length function and distance function in Unity Shader?

texts: I'm confused about the two functions, do they return the same thing?


texts:
The Actor's boundaries are not centered at the ButtonText but I used the setBounds() method. The higher the Y position is, the less centered is the boundary. The weird thing is that i only created and added to the Stage one button but the screen shows two. When i click the top button, the bottom one is the one highlighted.

How can i fix that?

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;

public class MyGame extends Game {
    Stage stage;
    @Override
    public void create() {
        stage=new Stage();
        FileHandle skinFile = new FileHandle("data/resources/uiskin/uiskin.json");
        Skin skin = new Skin(skinFile);
        TextButton sas=new TextButton("dd",skin);
        sas.setBounds(0, 500, 100, 100);
        stage.addActor(sas);
        Gdx.input.setInputProcessor(stage);
    }

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

@Override
public void render() {
    super.render();
    stage.act(Gdx.graphics.getDeltaTime());
    stage.draw();
}

@Override
public void resize(int width, int height) {
    super.resize(width, height);
}

@Override
public void pause() {
    super.pause();
}

@Override
public void resume() {
    super.resume();
}

}


texts: Game Maker - Shader CGA - how to swap the palette

texts:
I created a shader that get the actual color of the surface and render it to the closer of a cga palette

I have to change it to swap the palette in 4 colors but I don't know how
secondary, I have to render it dynamic (maybe using an uniform variable)
because it have to change in base of the palette

please help me, thanks

///CGA Shader
varying vec2 v_vTexcoord; //xy
varying vec4 v_vColour; //rgba

#define _ 0.0
#define o (1./3.)
#define b (2./3.)
#define B 1.0

#define check(r,g,b) color=vec4(r,g,b,0.); dist = distance(sample,color); if (dist < bestDistance) {bestDistance = dist; bestColor = color;}

void main(out vec4 v_vColour, in vec2 v_vTexcoord)
{
    float dist;
    float bestDistance = 1000.;
    vec4 color;
    vec4 bestColor;

    vec2 pixel = vec2(320,200)-floor( v_vTexcoord.xy / iResolution.xy * vec2(320,200));
    vec4 sample = texture2D(iChannel0, pixel / vec2(320,200));

    sample += (texture2D(iChannel1, pixel / iChannelResolution[1].xy)-0.5)*0.5;

    // pallete 0

    check(_,_,_);
    check(o,B,o);
    check(B,o,o);
    check(B,B,o);

    vec4 color1 = bestColor;
    bestDistance = 1000.;

    // pallete 1

    check(_,_,_);
    check(o,B,B);
    check(B,o,B);
    check(B,B,B);

    vec4 color2 = bestColor;

    float t = (clamp(sin(iGlobalTime)*4.,-1.,1.)+1.)/2.;

    v_vColour = mix(color2, color1, t);

    gl_FragColor = v_vColour * texture2D( gm_BaseTexture, v_vTexcoord );
}


texts:
I have a D3D11 application, and I want to add proper fullscreen suport.
Now I can let DXGI switch my window to fullscreen for me, and I'm under the impression that DXGI will take care of everything needed to make the swap chain flip front and backbuffer instead of blitting them.

However, letting DXGI perform the swich seems unreliable with a multi monitor setup - secondary screens stay entirely black after the switch a great deal of the time, with no apparent reason or pattern to it.

It can take a few times switching back and forth before I get the fullscreen window and the rest of the desktop being shown on the other screens.

Apparently I'm not alone with this, Battlefield 3 and WoW seem to have similar issues for a lot of people.

Now, the actual question: I guess since even those AAA game dev companies can't get this to work, my biggest hope would be to somehow perform the switch to fullscreen myself.

Is there anything I can do to elevate my window/swapchain into proper, buffer-flipping fullscreen mode?


texts: How should I design my score to visually accommodate large numbers?

texts:
I am creating a simple punching game that counts the total number of punches dealt.

Could you suggest a way for my game to visually accommodate very large numbers (>100000). Currently my wire-frame looks like this:

How should I display very large numbers here? I thought about shrinking the fonts, and creating abbreviations, but I'm not sure it's the proper way to go.


texts:
I can't really find a good answer to this anywhere, I have never worked on games in a proffessional environment and I am wondering; Do these games render their UI in the main game-loop?

That is, do they render loading-screen, menu-screen, text-dialogs with running text, ingame UI (direction arrows for example) in the main game loop? that is the same game-loop they use to update and render the actual game-play, meaning only one activity is used, and the game-loop runs from the moment the app starts until it exits.

I'm having a hard time making my menu because I want to animate the buttons, but when I have the menu in my main game-loop and I for example press the "start game"-button, the game starts right away before the buttons animation is played (supposed to shrink), is this just done adding like a timer for delay or something like that (like in example below)? Feels so ugly.

Ugly pseudo code:

if(startButton gets pressed){
start button animation;
start 1 second timer;
timer finished -> start game;
}

EDIT: I'm building my game for ios and Android using LibGdx Java, but I guess this question is universal so that might not be relevent.


texts: How do I detect if my object is grounded?

texts:
I am trying to detect when an object is grounded.
My script right now is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class playermovement : MonoBehaviour
{
    public CharacterController2D controller;
    public Rigidbody2D rb;
    float horizontalMove = 0f;
    public float runSpeed = 40f;
    Vector2 forceapplied;
    public bool isGrounded;
    public float NumberJumps = 0f;
    public float MaxJumps = 2;
    public float jumpHeight = 7f;
    public CircleCollider2D bc;

    void Start()
    {
        forceapplied = new Vector2(0.0f, 30f);
    }

    void Update()
    {
        if(bc.gameObject.name == "Grid") {
            isGrounded = true;
            NumberJumps = 0;
        }
        horizontalMove = Input.GetAxisRaw("Horizontal") * runSpeed;

        if (NumberJumps > MaxJumps - 1)
        {
            isGrounded = false;
        }
    }

    private void FixedUpdate()
    {
        if (isGrounded)
        {
            if (Input.GetButtonDown("Jump"))
            {
                rb.AddForce(Vector2.up * jumpHeight);
                NumberJumps += 1;
            }
        }
        controller.Move(horizontalMove * Time.fixedDeltaTime, false, false);
    }
}

In the inspector it always says that Isgrounded is false.
Can someone please help?


texts: Best practices for implementing collectible virtual item "packs"?

texts:
I'm in the process of building a game in which virtual items can be obtained either by in-game play (defeating enemies, gaining levels), or by purchasing "packs" via microtransactions.

Looking at an existing example like Duels.com's item packs, it looks like a lot of thought went into their implementation, including:

Setting clear player expectations as to what can be obtained in the pack
Limiting pack supply to increase demand and control inflation

Are there other considerations that should be taken into account?  For example, should the contents of the packs be pre-generated to guarantee the advertised drop rates, or is each drop rate just a random chance, and you could end up with higher or lower supply?


texts: Blending animations for more character movements

texts:
I am making a hack n slash 3rd person game, and I want the character movements to be more dynamic not like fighting games where you have a moves list.

I want to animate tons of different animations and have them "Tween" between each other.

I do not want the to use the mouse for controls, I want it to be all keyboard, that way you have up to 10 inputs (All your fingers) to blend and morph animations to create more fluid movements. In the end this will almost be similar to characters typing a phrase or string of keys rather than move forward mouse look click to melee.

My questions are:

Has anyone done this before?
How would someone go about trying to tween?

lets say one for key on the keyboard excluding Tab, Caps, R+Shift, L+Shift, Enter, R+Ctrl, L+Ctrl, L+Alt, R+Alt, Windows Key, and Menu.

So thats all the numbers, letters and punctuation keys. Thats 46 keys gives me a combination of 46P1 = 5502622159812088949850305428800254892961651752960000000000L (used Python), and with a minimum entry value of 2 keypresses shortening to half. This is not humanly possible to create so many inique animations in one lifetime. But I'm guessing there is a reason this hasn't been done already.

Or if I just used 10 basic keys. Maybe ASDF SPACE (RIGHT HAND) 456+0 (LEFT HAND KEYPAD)
it would give me 3,628,800 posible unique animations.


texts: How to design and implement turn-based system?

texts:
Possible Duplicate:
  How to implement turn-based game engine?

I am considering making a game like Master of Orion but I don't know how to start with turn-based systems. If any of you played this game they know what I mean, same system is used in Civilization.
1. You give orders to your units and production queues
2. Click End Turn.
3. Everything moves, go to 1.

I know that some form of state machine is used, but maybe you could point me into some book or manual on the matter.


texts: Where is the “Test Login Needed” in App review in Google Play?

texts:
I recently uploaded a new app in the google play console to review, then I was receive an email that say:

  Please provide login credentials to the support team before you submit
  any updated version for another review (select “Test Login Needed” and
  include the test login account and password details in the open box
  field).

I can´t find the “Test Login Needed” to select it.

Can anybody tell where is this option?


texts: What are pros & cons of naming in game currency a standard name vs a gimmick?

texts:
We're creating a store and going to add an in game currency. We did a poll and Tokens & Sheep were the top options selected by the players.
I personally think Sheep would be more fun like a barter system as well as it is an in game resource as you may know from the Settlers of Catan (my game https://colonist.io/)
I know that https://starve.io/ has Golden Bread and https://surviv.io/ has Potato as in game currency.
Are there any other such examples? What are the pros cons of such naming?
I don't know any big games which do such a thing.


texts:
I want to read some info from the GPU Visualizer widget and use it in my plugin, but I have no idea how.
I guess this code is responsible for running the ProfileGPU console command:
        // Create and display profile visualizer data
        if (RHIConfig::ShouldShowProfilerAfterProfilingGPU())
        {

        // execute on main thread
            {
                struct FDisplayProfilerVisualizer
                {
                    void Thread( TSharedPtr<FVisualizerEvent> InVisualizerData, const FText InVsyncEnabledWarningText )
                    {
                        static FName TaskGraphModule(TEXT("TaskGraph"));
                        if (FModuleManager::Get().IsModuleLoaded(TaskGraphModule))
                        {
                            IProfileVisualizerModule& ProfileVisualizer = FModuleManager::GetModuleChecked<IProfileVisualizerModule>(TaskGraphModule);
                            // Display a warning if this is a GPU profile and the GPU was profiled with v-sync enabled (otherwise InVsyncEnabledWarningText is empty)
                            ProfileVisualizer.DisplayProfileVisualizer( InVisualizerData, TEXT("GPU"), InVsyncEnabledWarningText, FLinearColor::Red );
                        }
                    }
                } DisplayProfilerVisualizer;

                TSharedPtr<FVisualizerEvent> VisualizerData = CreateVisualizerData( EventTree );

                DECLARE_CYCLE_STAT(TEXT("FSimpleDelegateGraphTask.DisplayProfilerVisualizer"),
                    STAT_FSimpleDelegateGraphTask_DisplayProfilerVisualizer,
                    STATGROUP_TaskGraphTasks);

                FSimpleDelegateGraphTask::CreateAndDispatchWhenReady(
                    FSimpleDelegateGraphTask::FDelegate::CreateRaw(&DisplayProfilerVisualizer, &FDisplayProfilerVisualizer::Thread, VisualizerData, VsyncEnabledWarningText),
                    GET_STATID(STAT_FSimpleDelegateGraphTask_DisplayProfilerVisualizer), nullptr, ENamedThreads::GameThread
                );
            }

        }

Any ideas on how to get the widget? Or maybe there is an easier way to get that info?


texts:
I can't seem to get my volume raycaster to work properly. I've been poking around changing things for days trying to get it to display my volume correctly but I seem only to get distorted mutations of it.

What I tried to do was a 1-pass renderer because the 2-pass one I made wasn't good enough for my purposes. I'm using C# XNA and the renderer wont have to handle transparency so it only has to get in and fetch the first color it bumps into.

How it should look:

How it looks:

float4 OnePassPS(OnePassVSOutput input, float2 pixelCoord : VPOS) : COLOR0 {

float3 rayDir = normalize(mul(float3(((pixelCoord / WindowSize) * 2) - 1.0, -FocalLength), ModelView));

float4 pos = float4(RayOrigin + (rayDir * (input.pos.z / input.pos.w)), 0);
float3 Step = rayDir * StepSize;

float4 color = float4(0, 0, 0, 0);
for(int i = 0; i < Iterations; i++)
{
    color = tex3Dlod(VolumeS, pos);

    if(color.a > 0)
        break;

    pos.xyz += Step;
}
return color; }


texts: In Unity, why is adding a Vector2 and a Vector3 ambiguous but assigning isn't?

texts:
Given the following two vectors:

Vector3 v3 = Vector3.one;
Vector2 v2 = Vector2.one;

This line is ambiguous:

v3 += v2; // Unity reports dimension ambiguity

whilst this assignment isn't:

v3 = v2; // Unity assigns despite different dimensions

Why is this?


texts:
I'm trying to achieve what was done in the game impossible creatures. I will have a skeleton to which I will apply different meshes to i.e. torso mesh, leg mesh, etc. I would also like these meshes to be skinned together at the joints so that it looks like an animal and not like a robot.

Any ideas as to how I go about achieving this?


texts: Why is this beat detection code failing to register some beats properly?

texts:
I made this SoundAnalyzer class to detect beats in songs:

class SoundAnalyzer
{
    public SoundBuffer soundData;
    public Sound sound;
    public List<double> beatMarkers = new List<double>();

    public SoundAnalyzer(string path)
    {
        soundData = new SoundBuffer(path);
        sound = new Sound(soundData);
    }

    // C = threshold, N = size of history buffer / 1024  B = bands
    public void PlaceBeatMarkers(float C, int N, int B)
    {
        List<double>[] instantEnergyList = new List<double>[B];
        GetEnergyList(B, ref instantEnergyList);
        for (int i = 0; i < B; i++)
        {
            PlaceMarkers(instantEnergyList[i], N, C);
        }
        beatMarkers.Sort();
    }

    private short[] getRange(int begin, int end, short[] array)
    {
        short[] result = new short[end - begin];
        for (int i = 0; i < end - begin; i++)
        {
            result[i] = array[begin + i];
        }
        return result;
    }

    // get a array of with a list of energy for each band
    private void GetEnergyList(int B, ref List<double>[] instantEnergyList)
    {
        for (int i = 0; i < B; i++)
        {
            instantEnergyList[i] = new List<double>();
        }
        short[] samples = soundData.Samples;

        float timePerSample = 1 / (float)soundData.SampleRate;
        int sampleIndex = 0;
        int nextSamples = 1024;
        int samplesPerBand = nextSamples / B;

        // for the whole song
        while (sampleIndex + nextSamples < samples.Length)
        {
            complex[] FFT = FastFourier.Calculate(getRange(sampleIndex, nextSamples + sampleIndex, samples));
            // foreach band
            for (int i = 0; i < B; i++)
            {
                double energy = 0;
                for (int j = 0; j < samplesPerBand; j++)
                    energy += FFT[i * samplesPerBand + j].GetMagnitude();

                energy /= samplesPerBand;
                instantEnergyList[i].Add(energy);

            }

            if (sampleIndex + nextSamples >= samples.Length)
                nextSamples = samples.Length - sampleIndex - 1;
            sampleIndex += nextSamples;
            samplesPerBand = nextSamples / B;
        }
    }

    // place the actual markers
    private void PlaceMarkers(List<double> instantEnergyList, int N, float C)
    {
        double timePerSample = 1 / (double)soundData.SampleRate;
        int index = N;
        int numInBuffer = index;
        double historyBuffer = 0;

        //Fill the history buffer with n * instant energy
        for (int i = 0; i < index; i++)
        {
            historyBuffer += instantEnergyList[i];
        }

        // If instantEnergy / samples in buffer < instantEnergy for the next sample then add beatmarker.
        while (index + 1 < instantEnergyList.Count)
        {
            if(instantEnergyList[index + 1] > (historyBuffer / numInBuffer) * C)
                beatMarkers.Add((index + 1) * 1024 * timePerSample);
            historyBuffer -= instantEnergyList[index - numInBuffer];
            historyBuffer += instantEnergyList[index + 1];
            index++;
        }
    }
}

For some reason it's only detecting beats from 637 sec to around 641 sec, and I have no idea why. I know the beats are being inserted from multiple bands since I am finding duplicates, and it seems that it's assigning a beat to each instant energy value in between those values.

It's modeled after this: http://www.flipcode.com/misc/BeatDetectionAlgorithms.pdf

So why won't the beats register properly?


texts: Marking up 2D polygon perimeter on an image

texts:
I'm working on a 2D game in JavaScript using the Web canvas. I plan to use AABB proximity detection and then point, line and polygon on polygon collision detection.

Which means I need to define polygon perimeters for each of my potentially colliding objects. I have to come up with a list of pivot-point-relative coordinates for each vertex on the perimeter of the object's sprite.

This is a tedious and laborious task to do manually, and it seems like it's something that lots and lots of game developers must have had to do many many times.

What is a more efficient workflow for marking up collision polygons on an image or sprite?


texts:
I have a coded a simple example for a matrix rotation. The example rotates a sphere around its center. The problem is that the rotation is not running perfectly smooth and I'm wondering why.

Here is a minimal code sample:

float totalMs = 0.0f;
int animationDuration = 5000;

void update(float deltaMs) {
    totalMs += deltaMs;
    float degrees = (totalMs % animationDuration) / animationDuration * 360.0f;
    glm::mat4 rotation = glm::rotate(glm::mat4(), radians(degrees), rotationAxis);

    //multiply modelViewMatrix by rotation matrix
    //and use the resulting matrix in shader to transform points
}

I'm programming in C++, using GLM Library for Maths, SDL2 for rendering context and OpenGL for the rendering.

Any hints what could cause the rendering to not look totally smooth?

Edit:
Ok I found out that the time needed for SDL_GL_SwapWindow() at the end of my gameLoop varies between <1ms and >30ms. What could be causing this?


texts: Good practices while working with multiple game engines, porting a game to a new engine

texts:
I have to work with multiple game engines, like

Cocos2d
Unity3d
Galaxy

While working with multiple game engines, what practices should I follow?

For instance, we made a game with Cocos2d and released it on the AppStore. Now we want to port it to other platforms using Unity.

What would be the course of actions to follow?


texts: vSync for gameplay in monitor and VR headset in Unity not being consistent?

texts:
Following my previous question, I'm building a project, my monitor refresh rate is 60Hz, and in my project I have set my vSync value into 2 so I can get 30fps.

QualitySettings.vSyncCount = 2

It worked perfectly, I built my project and I got stable 30fps. But after I plugged my VR headset (HTC Vive) to play the same project, my framerate drops and only reach around 10fps. Why is this happening ? FYI, Vive's refresh rate is 90Hz. In this case, will vSync adjust itself to my monitor or Vive's refresh rate ?


texts: Can I include a public domain book in my game?

texts:
Just for fun, I want to include a bookshelf in my game with a real book (or few) that you can actually read.

Would I run into any legal trouble if I included an out of print book in the public domain, such as Pride and Prejudice or Alice in Wonderland?


texts:
Using a 3/4th perspective, I'm trying to create a way to render cliffs where nothing is overlapped, and it creates an accurate representation of the elevation.
This is a rough mockup of how it might look in-game:

The way the tile data is organized is by layer. Each elevation has a layer class which holds all of the ground data for that specific layer, and all unoccupied space is simply null in the array.
I can't seem to come up with a way to render the data so it would look something like this. I've thought about rendering from highest to lowest elevation, the other way around, etc. All entailed a situation where something is getting overlapped that shouldn't be.

What's the best way to do this?


texts: Get Prefab Asset From Gameobject in Edit Mode

texts:
I want to get a prefab asset (that resides in Project Window) and assign it to a field like the one you get when you manually drag the prefab asset from Project Window to GameObject field:

But when I try to do the same thing in code (and in Edit Mode) with this function:

GameObject prefab_instance = PrefabUtility.GetNearestPrefabInstanceRoot(gameobj) as GameObject;

I get a prefab instance but not a prefab asset:

How do I get a reference to prefab asset from the gameobject that was created from it?


texts: What is the best online game framework for Python?

texts: I want create online game with Python. Is there any framework or library to make it easier? I would like it if the framework provided things like character attributes, such as health.


texts: How can I determine the velocity after impact of a 2D ball collision?

texts:
Consider two balls moving towards each other. Each has a given mass and velocity. Assuming the balls collide, how can you determine what direction the balls will take afterwards? (taking into consideration the mass & velocity)

I realise it's quite a big question, perhaps someone could direct me to an appropriate tutorial.


texts: What are file formats that store skeletal movements, and are there databases of them?

texts: I have a set of 3d vectors representing the positions of a character's hand, foot, shoulders and so on. Is there any kind of easy to read file I can use to animate those with walking, standing, jumping etc motions? Is there a database with some of them?


texts: Photon2 Unity2D How to send float with RPC

texts:
I have big problem in my code .. I want to spawn obstacle exactly on the same position as on the server is spawned so I made rpc Method and tried to pass random variable of float , but when i run the game obstacles are spawned on the diffrent position. I am loosing a lot of time to get it done but I still can not find solution.

Here is the code

   [PunRPC]
    void RPC_SpawnColumn(Vector3 position)
    {
        // Instantiate(prefab, position, Quaternion.identity);
        Debug.Log("THIS IS SPAWNYPOSITION" + spawnYPosition);

        Instantiate(prefab, new Vector2(9, spawnYPosition), Quaternion.identity);

    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        //print("Are we here");
        if (collision.GetComponent<ColumnsMultiplayer>() != null)
        {

            print("Or are we here");
            if (SpawnOnce)
            {
                spawnYPosition = Random.Range(-3.36f, 2.98f);

                photonView.RPC("RPC_SpawnColumn", RpcTarget.Others,new Vector3(9, spawnYPosition));  // this is

            }
                //SpawnColumn();

            SpawnOnce = false;

        }
    }

Thank you so much for reading post.

Edit: I need to send spawnYPosition  from method two to method one and spawn it with same position of spawnYPosition  in the second method.


texts: Measure the length of the platform in Unity

texts:
I created a platform in Unity. It consists of an empty parent object and child objects. Child object have attached components: Sprite renderer and Edge collider 2D.

How could I get the length and height of such a platform? By the length and height in the case I mean the respective measures in x and y axis.


texts: How to force a garbage collector swep on libgdx?

texts:
I found that you can control your memory usage on libgdx with:

int javaHeap = Gdx.app.getJavaHeap();
int nativeHeap = Gdx.app.getNativeHeap();

But, How can I force a garbage collector cleanup? I want to force in special moments, like screen change on a game.


texts: semi 3d walls, should I use sprite sheet or render them 3d?

texts:
I'm going to develop a game and this is just a prototype of it's graphics.

Knowing that my primary target platform is iPhone, I'm wondering if it's better to create a spritesheet containing all possible angles from a wall or is it better to render them with 3d boxes?

here is sample spritesheet I was going to use:


texts: Best way to do multiple choice in Unity 2D?

texts:
So I'm about to start development on a game in unity that is going to require multiple choice each choice having a some what unique function. I've thought of 2 ways of doing this but I'm unsure if there is an easier way as I've never really worked with unity.

So the first way I was thinking about doing this and I think better then the second would be to make a class for each choice with all the functions that belong to that choice in there and then just calling it when its needed. However, I don't know if this will scale very well as I will have over 100 different events with their own choices...

The second way I was thinking was to do it via JSON and then just code each function to parse that. So for example: addmoney, dothis, dothat etc... However this seems like a lot more work then it would be worth so I'm not 100% sure...

So I'm wondering what option would be better and if anyone else has any suggestions I'd love to hear!


texts: Any way to merge plugins in RPG maker XP?

texts:
So I'm trying to merge together 2 mods into one game. One is Tankentai's SBS and the other is Cocoa's UMS.

I'm trying to merge the 2 into one game that includes the battle system from SBS, but the text boxes and whatnot from UMS. Is there any easy way to do this other than combing through all the script lines and copying them one at a time? I've tried to use this but it doesn't seem to do quite what I need it to do.


texts: Given a ray-intersect position on morphed mesh, how to compute that position at each morph target?

texts:
I'm working on an annotation system that allows a user to click on a mesh to attach a pin with a label hanging off it.

It must be possible to pin an annotation on an object that's being morphed with keyframe morph targets, so that the pin will move with the surface of the mesh.

It's mainly pretty simple, where I do a ray-intersect to find the pin position on the mesh, for the shape of the mesh at the current time within the morph targets.

Then I have, for that time instance:

the 3D coordinates of the pin
the triangle (ie. the indices and vertex positions of the triangle's vertices) that the pin is within
the time instant

Now, if I had the 3D coordinates of the pin at each of the morph's targets, then I can simply tween the pin position, to animate it in synch with the morph.

However, the challenge I is to somehow compute the position of the pin at each of the morph targets, from these three pieces of information.

Intuitively, it seems to be a matter of somehow finding some sort of coefficient (or set of coefficients) that indicates the pin's position relative to the vertices of its enclosing triangle, at the instant within the morph sequence that we attach the pin.

Then, for each other target within the morph sequence, given the morphed positions of the triangle vertices, which could be anything, somehow use the coefficient(s) to find the updated pin position, relative to the triangle's current vertex positions.

Anybody got any ideas? Math pointers etc?

cheers!


texts: Networking problems when sending textures from the server

texts:
When a client connects to my game server, the server sends textures and then the world information.
The problem is that the texture information may come after the world information and so the client errors out because it has no texture to give the models.

How would I combat this?


texts: Detecting overlap with Phaser P2 physics

texts:
In a 2D platformer, I'd like to implement a ladder. I have collision working between the player and ground tiles. Now I would like to be able to detect when the player walks through a ladder tile (which can be one of three tile indices). When the player is overlapping a ladder and up is being pressed, the climbing state would be set.

Ideally, I'd like to get a callback when this happens. It seems that the overlap method from Arcade physics is not available in P2. What is there instead to implement overlap detection?


texts: First "If" Enemy Selection Function being recognized as a syntax error in Python

texts:
I have an issue with trying to under the syntax error with the line if enemy_select = 1: in this type of code:

enemy_select = random.randit(1, 11)

for enemy_select in range(1):
    if enemy_select = 1:
        enemy_type = character 1

    elif enemy_select = 2:
        enemy_type = character 2

    elif enemy_select = 3:
        enemy_type = character 3

    elif enemy_select = 4:
        enemy_type = character 4

    elif enemy_select = 5:
        enemy_type = character 5

    elif enemy_select = 6:
        enemy_type = character 6

    elif enemy_select = 7:
        enemy_type = character 7

    elif enemy_select = 8:
        enemy_type = character 8

    elif enemy_select = 10:
        enemy_type = character 9

    elif enemy_select = 10:
        enemy_type = character 10

    elif enemy_select = 11:
        enemy_type = character 11


texts: Using custom functions in HLSL shaders generates extra insructions?

texts:
We use forward rendering so our main shader is pretty big (342 instructions). Recently I tried substituting every single custom function I call in the shader with the actual code from that function and the number of instructions generated dropped down to 311.

Am I doing something wrong with my custom functions? I tried passing variables into them with various predicates (in/inout/out/[nothing]) but it did not change the number of instructions even though Microsoft claims every instruction in HLSL is inlined.

UPDATE:
Example code:

void DirectionalLight(half4 Normal,
                half3 DirectionToCamera,
                half4 Combined,
                inout half2x3 light)
{
    half3 halfVector = normalize(DirectionToCamera + SpecLightDirection);
    half3 lightParams = saturate(half3(dot(Normal.rgb, DirectLight1.Direction), //NDL
        dot(Normal.rgb, SpecLightDirection),                                    //NDL_Spec
        dot(Normal.rgb, halfVector)));                                          //NDH

    half4 litV = lit(lightParams.g, lightParams.b, Combined.b);
    light[0] += DirectLight1.Color*lightParams.r;
    light[1] += DirectLight1.Color*litV.b;
}

float4 MainPS(VSOutput input) : COLOR0
{
    ...
    DirectionalLight(Normal, input.DirectionToCamera, Combined, DirLightAccum);
    ...
}

Or this code:

half2x3 DirectionalLight(half4 Normal,
                half3 DirectionToCamera,
                half4 Combined)
{
    half2x3 light = (half2x3)0;
    half3 halfVector = normalize(DirectionToCamera + SpecLightDirection);
    half3 lightParams = saturate(half3(dot(Normal.rgb, DirectLight1.Direction), //NDL
        dot(Normal.rgb, SpecLightDirection),                                    //NDL_Spec
        dot(Normal.rgb, halfVector)));                                          //NDH

    half4 litV = lit(lightParams.g, lightParams.b, Combined.b);
    light[0] += DirectLight1.Color*lightParams.r;
    light[1] += DirectLight1.Color*litV.b;
    return light;
}

float4 MainPS(VSOutput input) : COLOR0
{
    ...
    DirLightAccum += DirectionalLight(Normal, input.DirectionToCamera, Combined, );
    ...
}

Both generates 342 instructions. But the following code:

float4 MainPS(VSOutput input) : COLOR0
{
    ...
    half3 halfVector = normalize(input.DirectionToCamera + SpecLightDirection);
    half3 lightParams = saturate(half3(dot(Normal.rgb, DirectLight1.Direction), //NDL
        dot(Normal.rgb, SpecLightDirection),                                    //NDL_Spec
        dot(Normal.rgb, halfVector)));                                          //NDH

    half4 litV = lit(lightParams.g, lightParams.b, Combined.b);
    DirLightAccum [0] += DirectLight1.Color*lightParams.r;
    DirLightAccum [1] += DirectLight1.Color*litV.b;
    ...
}

Only generates 339 instructions. Heavier functions (with more variables passed) generate more instructions. As I mentioned, when substituting ALL the functions with their actuall bodies I was able to reduce instruction count by 10%.

I tried making CastShadow a float function so that I can get rid of the "inout half shadow" argument but does not help.

I am just trying to figure out if it's a norm or I am doing something wrong?


texts: I am trying to create some parallax background in Unity in 2D mode by tweaking offset of the background material and using tiling. I used this tutorial https://www.youtube.com/watch?v=nGw_UBJQPDY as a reference, but my material doesn't tile like one in the tutorial. Any tips for creating infinite background with tiling and tweaking offset? What am I doing wrong?


texts:
I am now creating a 64 bit and 32 bit executable of my game.

How could I achieve so that the executable and dlls lie in a separate folder without changing all the path variables in the game?

To clarify I want to have a folder structure like this:

Game

Bin

exe
dll, so, etc.

Data

textures and everything else.

My current is:

Game

exes
dlls
data

So my path variables use something like: ./data/ ....

How could I move my exes so they would find all dlls and data, so I wouldn't need to replicate the data folder for each version and have them nicely separated?

I am mainly looking for answers for Windows, but I am also interested in Unix solutions.


texts: Speed needed to make a car jump from a ramp

texts:
I need to make a car jump from a ramp to another, and I need this to be done using AI so I thought it would be enough to set a fixed speed for my car when near the ramp, in order to let it jump correctly.

It works fine if I input the speed manually but I'd like my game to calculate it since the ramps will be generated by user's input.

Unfortunately my physics knowledge lacks, so I need your help.

The problem is summarized in the picture below.

Basically, what I need to compute is the speed (in m/s) that the car has to have on the highest point of the first ramp, given that all the data in red are user's input.

I had some rough ideas on using the projectile range with x=L, y=h-launchRampHeight but the results weren't as I expected them so I gave up.

Do you have any hints on this?

Please note that both ramps have the same length (50m).

EDIT:

Based on @mklingen here's the C# code that I'm using (where Distance = L)

var speed = (Mathf.Sqrt(g)*Mathf.Sqrt(Distance)*Mathf.Sqrt((1/Mathf.Sin(Theta)))* Mathf.Sqrt((1/Mathf.Cos(Theta))))/Mathf.Sqrt(2);

What happens is quite weird though.

For example, with theta = 19, L = 196, h = 46 my code returns 80.54646 which seems to work if I input it to the car. However running the expression in WolframAlpha leads to 55.8 which is wrong.

It may seem that the code is correct but with theta = 35, L = 261, h = 39 my code returns NaN while WolframAlpha shows 52.17 which made the jump happen.

So, tu summarize, I have 2 different cases in which my result is different from WolframAlpha's one and none of them is the correct one both the times.

What's going on?


texts: What tools are available for collaborative game development?

texts: Are there any tools that would let multiple people edit things like sprites or code at the same time? Perhaps something that works with services that host code.


texts: Trying to get an object to move in the mouse direction XNA C#

texts:
Right, so in my Player class where I call the object I got an if statement which gets the coordinates for the mouse

        bool PickedCoords = true;
        MouseState mouseState = Mouse.GetState();
        if (newState.LeftButton == ButtonState.Pressed && oldState.LeftButton == ButtonState.Released)
        {
            PickedCoords = true;
            int MouseX = mouseState.X;
            int MouseY = mouseState.Y;
        }
        else
        {
            PickedCoords = false;
        }
        oldState = newState; // this reassigns the old state so that it is ready for next time

Now how would I make MouseX and MouseY be used as the direction of the vector of my object moving in the specified X and Y coordinates? What I'm, almost trying to do is move the object in the direction of the mouse click and make it continue to move in that direction until it's stopped by whatever.


texts: Multiple Viewports/Windows Dear IMGUI c++

texts:
How do I use IMGUI with multiple GLFW windows? I know Dear IMGUI already has a virtual viewport system going in the viewport branch but I found that to be lacking a bit on how to use this new system.

To accomplish this would you share a single GLFWwindow context and using that for a single IMGUI context? Would there be any disadvantages to using this approach?


texts: Prevent from clicking through Sprite in 2D

texts:
I have this hierarchy (objects as sprites with colliders):

object 1 as parent
object 2 can be opened from object 1
object 3 can be opened from object 2

The thing is I have many objects like this in my project that are nested and I want to prevent users from clicking through sprites. Is there a more efficient way to do this? Any other way than manually adjusting every objects Z position in the inspector?


texts: How to make my 2D character stand normally on slope?

texts:
I've got this character in Unity3D (2D Mode)...
in a a slope which looks like this,

But I want the character to stand along the red line..Like below

How can I make it in Unity3d?

I've got this setup..

I'm using simple Addforce for movement...
If I remove the z position constraint it results in weird movement like rolling and so on....
Any help would be appreciated :)


texts: How can I record gameplay footage as a video within Unity?

texts: I am building a traffic simulator in Unity. I need to record my game as a video, so that I can use the video for machine learning purposes. I used fraps for the same but didn't find it worked for me since it's not within Unity. How can I make a video recording of the gameplay?


texts: How to isolate a child object from parent's movement? (Unity)

texts:
I currently have a very basic scene that includes a platform (ground), a capsule (player), and a camera rotator (main camera is mounted on it). The object hierarchy is the following.

This hierarchy reflects the objective of having a main camera that rotates about the player when correct command is entered.

A problem arises when the player moves. In this case, the capsule rotates about its vertical axis which causes the main camera to rotate because the camera rotator is mounted on the player. How could I isolate the camera rotator so that it remains mounted while ignoring the capsule's rotation. Thanks for considering my question.


texts:
I tried to make a collision box visible (for testing) with spriteBatch.Draw(with a blank texture) in my TileSprite class. I needed a GraphicsDevice for this so these are my variables:

Texture2D blankTexture;
GraphicsDevice GraphicsDevice;

I used this code as my LoadContent():

public void LoadContent()
{
    blankTexture = new Texture2D(GraphicsDevice, 1, 1, false, SurfaceFormat.Color);
    Color[] color = new Color[1];
    color[0] = Color.White;
    blankTexture.SetData(color);
}

I have one TileSprite constructor in my TileSprite class which looks like this (NOTE: this constructor is partially taken from another abstract class, named Sprite):

public TileSprite(GraphicsDevice gd, Texture2D textureImage, Vector2 position, Point frameSize, Point currentFrame)
    : base (gd, textureImage, position, frameSize, currentFrame)
{
    GraphicsDevice = gd;
    bCollisionRect = new Rectangle((int)position.X, (int)position.Y, frameSize.X, frameSize.Y);
}

And then I use this code in my Draw method to draw the box:

spriteBatch.Draw(blankTexture, bCollisionRect, Color.White);

And I have another line of code in the Game1 : Game class (variables like textureImage are written as variables in the beginning of the Game1 class):

tileSprite = new TileSprite(this.GraphicsDevice, textureImage, position, frameSize, currentFrame);

I tested this and I saw that my GraphicsDevice was returning null on a new TileSprite that used a GraphicsDevice from DrawableGameComponent.


texts: What are the dangers of self-teaching game development?

texts:
I am about to embark upon a journey into game development.  Following answers to my last question, I will be using C# and XNA.

However, I don't personally know any other game developers and I don't work in the industry so, as such, will be self-taught.  The exception to this is obviously the asking of questions and reading of online/printed information but I would still class this as being self-taught.

With that, I want to be prepared for issues that I may encounter through not having someone to "keep me under their wing".

As an analogy, when self-teaching myself to play guitar, I played the A major chord in such a manner that it made moving to a chord I learned later more difficult.

If you could share your lessons learned and advice on what might go wrong in my learning of game development I'd be grateful.

I am well aware that making mistakes is the biggest part of learning but, if there're mistakes I can be prepared for then I'd be happier with that.


texts: How to find an object which is added to a scene only when game starts?

texts: I'm looking for some advice how to find an object which is added to scene only when the game starts? Before start it isn't in Scene hierarchy. It's prefab.


texts: How do I represent blended tiles in a mesh/vertex array?

texts:
I recently started making a Terraria clone using the LÖVE library, which is based in OpenGL.

In Terraria, for each tile, there is a large texture with all possible combinations for merging with neighbouring tiles. They usually only  support tiles of the same type, and sometimes other materials, like dirt. As a result, they only need a single vertex array.

In Starbound, it seems to be simpler. A tutorial I found notes the use of basic 8x8 blocks, with a few edges drawn if the block is next to a block of a different type.

I want to implement a similar mechanic, but I encountered a serious issue. A single vertex array does not allow z-ordering, which I would need.

My first idea was to use one vertex array for each type of block, but that would eat a lot of memory.
My second idea was to use the fact that OpenGL vertex array draws primitives in order. I could use some complicated data structure to represent tiles, so I would always know where to place their vertices in the array. However, that would either require moving lots of vertices or lots of memory.

What is the best way to implement this?


texts:
Let me explain my question:

I have a sprite sheet with the different frames of the animations. Each animation has 8 frames.

Based on the player's input, I modify the character's coordinates, thus I also modify where the given frame of the animation should be rendered. Based on if the character is running or walking, I either speed up the animation or slow it down (since while running he should take 3 steps per second, and 2 steps per second when walking, so I play 12 frames per second when he's running, and 8 when he's walking).

However in the case of the walk cycle, I also get an unwanted side effect: the character "moonwalks". This means that while the X and Y coordinates are changing, thus the character is moving forward, his current sprite does not change at that instance. This gives the impression that the character is sliding or skating on his feet.

I'm trying to create something similar to Prince of Persia or Flashback. As I see they don't have this problem in their animation, and I wonder how could I eliminate it in mine.

I can not simply just speed up my walk cycle animation, since a fast walking looks weird. Maybe I should have more frames in my animation? Is there a simpler way of doing it? When I search for sprite sheet animation algorithm I find so little.

Update: I have added an image to demonstrate the issue. As you can see, the character does this weird sliding.


texts: Full-screen window hangs when debug break or crash (Windows/GLFW/Cocos2D)

texts:
I run into an issue if my game application becomes unresponsive when running in fullscreen on Windows. This mostly applies when I want to use breakpoints in Visual Studio, however if the application crashes, such as from a memory error, the window doesn't close.

I don't think this is strictly a WGL/GLFW/Cocos2D problem, since I have seen this problem in other Windows games, including ones that use Direct3D.

I searched around, but I can't find a definitive answer as to what causes this problem or how to fix it. From what I have read, this issue is only supposed to be caused by using HWND_TOPMOST (or maybe HWND_TOP); however, even changing all uses of that in GLFW to HWND_NOTOPMOST doesn't seem to fix the problem.

I imagine that registering a custom signal handler using std::signal might work, but I am not sure which parts of the Windows API, if any, I should call in an exit handler, that would solve this problem.


texts: Web single player 2d top-down RPG - background image, sprites, and new level loading

texts:
I'm making a web single player 2D top-down rpg using JavaScript (create js library) and have a couple questions.

For the background image, I've currently loaded a 1000x1000 bitmap to represent the background for my rpg world (per level). It's drawn in relation to the camera (aka the canvas - 500x500) so not all of it is on the screen at the same time. If it's not on the screen, is it still using resources to be drawn? I eventually want to have a much larger "world", which will require a much larger bitmap... What is the best way to load a background image?

And what about sprites? I'm assuming if I create several sprite objects with bitmaps... even if they aren't on the camera, they are still using resources? This may slow down the game.

Level loading: If I walk to another level, or go inside a building, I'd like to load that bitmap... Is there a specific way to architect level loading?

Thank you!


texts:
I'm making a game in XCode using SpriteKit. The game has a player and different types of projectiles that he has to avoid. When the player collides with the projectiles, the score changes and the projectile disappears. However, when two projectiles collide, they kind of bounce away.
I want to make that every time two projectiles collide, they act like nothing happened and they keep going in their original path. What should I do?

*Note: This is not the whole code, it's just what matters.

    import SpriteKit

    struct Physics {
        static let player : UInt32 = 1
        static let missileOne : UInt32 = 2
        static let missileTwo : UInt32 = 3
    }

class GameScene: SKScene, SKPhysicsContactDelegate {

    var player = SKSpriteNode(imageNamed: "p1.png")

    override func didMoveToView(view: SKView) {

        physicsWorld.contactDelegate = self

        player.position = CGPointMake(self.size.width/2, self.size.height/5)
        player.physicsBody = SKPhysicsBody(rectangleOfSize: player.size)
        player.physicsBody?.affectedByGravity = false
        player.physicsBody?.dynamic = false
        player.physicsBody?.categoryBitMask = Physics.player
        player.physicsBody?.collisionBitMask = Physics.missileOne
        player.physicsBody?.collisionBitMask = Physics.missileTwo

        var missileOneTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("SpawnMissileOne"), userInfo: nil, repeats: true)
        var missileTwoTimer = NSTimer.scheduledTimerWithTimeInterval(1.2, target: self, selector: Selector("SpawnMissileTwo"), userInfo: nil, repeats: true)

        self.addChild(player)
    }

    //When contact happens
func didBeginContact(contact: SKPhysicsContact) {
    var firstBody : SKPhysicsBody = contact.bodyA
    var secondBody : SKPhysicsBody = contact.bodyB

    if ((firstBody.categoryBitMask == Physics.player) && (secondBody.categoryBitMask == Physics.missileOne)) {

        CollisionWithMissileOne(firstBody.node as SKSpriteNode, missileOne: secondBody.node as SKSpriteNode)

    } else if ((firstBody.categoryBitMask == Physics.player) && (secondBody.categoryBitMask == Physics.missileTwo)){

        CollisionWithMissileTwo(firstBody.node as SKSpriteNode, missileTwo: secondBody.node as SKSpriteNode)

    } else if ((firstBody.categoryBitMask == Physics.missileOne)&&(secondBody.categoryBitMask == Physics.missileTwo)) {

        CollisionBetweenMissiles(firstBody.node as SKSpriteNode, missileTwo: secondBody.node as SKSpriteNode)

        }

    }

//For Player and MissileOne
    func CollisionWithMissileOne(player: SKSpriteNode, missileOne: SKSpriteNode) {

        missileOne.removeFromParent()
    }

//For Player and MissileTwo
    func CollisionWithMissileOne(player: SKSpriteNode, missileTwo: SKSpriteNode) {

        missileTwo.removeFromParent()
    }

//For MissileOne and MissileTwo
        func CollisionBetweenMissiles(missileOne: SKSpriteNode, missileTwo: SKSpriteNode) {

        ???WHAT SHOULD I CODE HERE???

    }

}


texts: Is it secure to use UDP socket for a game server?

texts:
I'm working on a multiplayer android game with Unity. For server side I use python. There is no login system or username. Basically, there is a matchmaking system and rooms. I send json object which contains room key , position of user and etc. from client to server. Room keys are unique and 10 digit hexadecimal numbers. I use udp socket for communication. Here is my questions.

Is it secure only using udp socket for gameplay. Clients already has source code and can change it easily. So they can change data that coming from client to server. Do I need implement an algorithm to make more secure from hack or cheat? Can anybody change apk file and ruin everything in this game?


texts: Multiple UV coordinates in Unreal Engine Procedural Mesh Component?

texts:
How can I have multiple UV coordinates per vertex in a Procedural Mesh Component? My goal is to create a UV editor.

I know it is possible to generate multiple vertices per corner, as in UKismetProceduralMeshLibrary::GenerateBoxMesh but that's 24 vertices instead of 8 for a simple box. Would this be a performance problem?

I know that FRawMesh (used when importing an FBX into a static mesh) contains multiple UVs per "wedge" (properties stored for each corner of each face). But I don't know how to set or create the equivalent in custom mesh component (except by duplicating vertices).

I know that casperjeff modified the Procedural Mesh Component plugin to add an additional UV set (as he explains here), but I don't really know how to make one UV set correspond to one face.

I am looking for an efficient solution in terms of performances.


texts: Panning with the OpenGL Camera / View Matrix

texts:
I'm gonna try this again

I've been trying to setup a simple camera class with OpenGL but I'm completely lost and I've made zero progress creating anything useful. I'm using modern OpenGL and the glm library for matrix math. To get the most basic thing I can think of down, I'd like to pan an arbitrarily positioned camera around. That means move it along its own Up and Side axes. Here's a picture of a randomly positioned camera looking at an object:

It should be clear what the Up (Green) and Side (Red) vectors on the camera are. Even though the picture shows otherwise, assume that the Model matrix is just the identity matrix. Here's what I do to try and get it to work:

Step 1:
Create my View/Camera matrix (going to refer to it as the View matrix from now on) using glm::lookAt().

Step 2:
Capture mouse X and Y positions.

Step 3:
Create a translation matrix mapping changes in the X mouse position to the camera's Side vector, and mapping changes in the Y mouse position to the camera's Up vector. I get the Side vector from the first column of the View matrix. I get the Up vector from the second column of the View matrix.

Step 4:
Apply the translation:
viewMatrix = glm::translate(viewMatrix,translationVector);

But this doesn't work. I see that the mouse movement is mapped to some kind of perpendicular axes, but they're definitely not moving as you'd expect with respect to the camera. Could someone please explain what I'm doing wrong and point me in the right direction with this camera stuff?


texts: How can I use the mouse to draw a filled arc/wedge of a disc?

texts:
Instead the mouse for testing I tried to use StartCoroutine to set the speed the circle will be drawn. The speed does change according to the seconds to wait but it also showing the radius line from the center:

And

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

[RequireComponent(typeof(LineRenderer))]
public class DrawCircle : MonoBehaviour
{
    [Range(0, 50)]
    public int segments = 50;

    public bool circle = true;
    [Range(0, 50)]
    public float xradius = 15;
    [Range(0, 50)]
    public float yradius = 15;
    LineRenderer line;

    void Start()
    {
        line = gameObject.GetComponent<LineRenderer>();

        line.positionCount = (segments + 1);
        line.useWorldSpace = false;

        StartCoroutine(CreatePoints());
    }

    private void Update()
    {
        //CreatePoints();
    }

    IEnumerator CreatePoints()
    {
        if (circle == true)
            yradius = xradius;

        float x;
        float z;

        float change = 2 * (float)Math.PI / segments;
        float angle = change;

        for (int i = 0; i < (segments + 1); i++)
        {
            x = Mathf.Sin(angle) * xradius;
            z = Mathf.Cos(angle) * yradius;

            yield return new WaitForSeconds(0.3f);
            line.SetPosition(i, new Vector3(x, 0, z));

            angle += change;
        }
    }
}

My goal is to use the mouse without dragging, only by moving, to draw a circle around the object (instead of drawing the circle automatically). So if I move the mouse only some of the way it will draw only part of the circle.

And I want to make the circle filled.

The circle will be drawn with a fixed radius around the selected object but with the mouse. The mouse movement will decide how much of the circle will be drawn. The idea is to make smooth mouse movement and drawing.

The idea is to use the mouse to draw something like the Handles.DrawSolidArc: an Arc but in the game view not the scene view.

Something like that:


texts:
I wonder if there is a simple way to use some kind om interval timing in XNA? For example call a method every 10 seconds?

I'm also wondering if there is a way to hide and unhide a sprite when it's on the screen?

Thanks!


texts:
I am working on a game in which I need an enemy ship to point towards the player.

Here is the equation I came up with:

  angle = sin-1(abs(y1 - y2)/√(x1 - x2)2-(y1 - y2)2)

This essentially takes the inverse sine of the opposite divided by the hypotenuse. Unfortunately, this algorithm does not work. Any ideas as to what I need to change? Note, the angle is a radian value.


texts:
How can we refine this path search method to make group movement more elegant? I'm trying to make a RTS-style game, using a 2d tiled gameworld. I have implemented an A* pathfinding algorithm which works well enough for single units. I've also make some functionality to make agents walk around other agents they stumble across on their way.

Here is some of my code:

def move(self, agent, clickbox, nogolist):
    impassable = []
    impassable.extend(nogolist)
    mapinfo1 = MapInfo(self.map_layout.finalsize,self.map_layout.finalsize,impassable)
    graph, self.nodes = self.make_graph(mapinfo1)
    paths = AStarGrid(graph)
    for c in self.map_layout.all_map_objects:
        if clickbox.box.collidepoint(c.checkpoint):
            path = []
            if len(agent.travel_list) > 1:
                v = agent.travel_list[1]
                start = self.nodes[v[0]][v[1]]
            elif len(agent.travel_list) == 1:
                start = self.nodes[agent.grid_pos[0]][agent.grid_pos[1]]
            end = self.nodes[c.gridnumber[0]][c.gridnumber[1]]
            path = paths.search(start, end)
            try:
                agent.target = self.convert_path(path)
                agent.travel_list = self.waypoints((agent.grid_pos[0],agent.grid_pos[1]), path)
            except:
                print 'road error'

When one or more agents are selected and the player right-clicks somewhere, self.move gets called on each agent individually, they are at this point still ignorant of other agents positions. The next part is where I try to have agents not walk over each other, or just stop if 'travel_list' only contains one more step, and another agent occupies it.

if not len(self.traveling_agents) == 0:
    for a, b in combinations(self.agent_list, 2):
                self.resolve(a, b, self.nogolist)
                self.resolve(b, a, self.nogolist)

def resolve(self, a, b, nogolist):
    try:
        if len(a.travel_list) > 1 and b.travel_list[0] == a.travel_list[-1]:
            a.travel_list = a.travel_list[:-1]
            a.target = a.target[:-1]
            if a.travel_list[1] == b.travel_list[0]:
                self.traveling_agents.remove(a)
        elif len(a.travel_list) > 1 and b.travel_list[0] == a.travel_list[1]:
            path = []
            go = a.travel_list[0]
            goal = a.travel_list[-1]
            impassable = []
            impassable.append(b.travel_list[0])
            impassable.extend(nogolist)
            mapinfo1 = MapInfo(self.map_layout.finalsize,self.map_layout.finalsize,impassable)
            graph, self.nodes = self.make_graph(mapinfo1)
            paths = AStarGrid(graph)
            start = self.nodes[go[0]][go[1]]
            end = self.nodes[goal[0]][goal[1]]
            path = paths.search(start, end)
            a.target = self.convert_path(path)
            a.travel_list = self.waypoints((go[0],go[1]), path)
            del impassable
    except: a.stop()

This works reasonably well for solo agents encountering other stationary solo agents. But when moving in a group towards a common target, this method falls way short of what would be desired. What can we do to achieve smoother group movement like what is seen in some of those old school RTS games?

For some additional insight on my code, check my previous entry on implementing the A-star search algorithm: https://stackoverflow.com/questions/14390458/how-to-structure-an-adjacency-list-for-this-a-program/


texts:
Not sure how to describe the issue I'm facing here:

Rectangles are grouped and attached to a "layer" extending Stage.
Each layer is added to a multiplexer in a Screen extension.

There are 2 layers:

Top has the 1 big rectangle & group members (smaller colored rectangles)
Bottom has the 2 big rectangles & their members

The 3 big rectangles are all the same size & color (turns yellow if it detects the mouse is over it, for debugging purposes)

When you click on it, it brings its group to the front of its layer.

The problem is that both the top layer and bottom layer are processing the input, grouping and drawing stuff works fine.

In the screenshot, only the top-most big rectangle should be yellow at the cursor's position:


texts: Why is OnCollisionEnter2D called when it's layer's collisions are being ignored?

texts:
I'm sure this is down to my lack of understanding of the unity physics system.

I'm trying to implement a simple one-way platform for a 2d game and have got stuck on creating a reliable way to let the character 'drop down' from a platform on pressing the down arrow.

While trying to debug and whittle down the code, I've found myself with this strange debug script:

using UnityEngine;
using System.Collections;

public class DebugPlatform : MonoBehaviour
{

    void OnCollisionEnter2D(Collision2D other)
    {
        if(Physics2D.GetIgnoreLayerCollision (other.collider.gameObject.layer, this.gameObject.layer))
            print ("ERROR: How does this happen?!!");
        else
            print("This is normal.");
     }
 }

When I place this on my one way platform and mess about in game, sometimes the character refuses to drop down on command, and the error message is printed.

From what I understood, GetIgnoreLayerCollision returned whether the collisions between the layers were being ignored or not.

So my questions are:

Why is OnCollisionEnter2D being called even though the layers are supposed to be ignored?
Is this ignore value just a request, not absolute? Maybe some collision optimization that I have to override?
I can't imagine this is some multi-threading issue, as the error appears regularly, after I do a normal jump on the platform.
Am I doing something completely wrong?

EDIT:
Extra info:
The one way platform is two parts, first an if else in FixedUpdate in the player script:

// Don't collide with platforms if flag is set or we are moving up:
if (ignorePlatform || transform.rigidbody2D.velocity.y > 0f)
    Physics2D.IgnoreLayerCollision (PlayerLayerID, PlatformLayerID, true);
else if(transform.rigidbody2D.velocity.y <= 0f)
    Physics2D.IgnoreLayerCollision (PlayerLayerID, PlatformLayerID, false);

The platform has an EdgeCollider2D on the top and a child with a Collider2D trigger underneath. A script then resets the player's ignorePlatform to false on exit. This is to make sure the player only falls through one platform when the down arrow is pressed.


texts:
I want to use the font Trajan Pro, but I'm not sure that it would be legal. I've read a bit on fonts and copyright, and the only thing I could get was it depends on the license and where it was copyrighted, and sometimes it isn't copyrighted at all.

So how would I tell if the font Trajan Pro, or any other font, is under copyright?


texts:
Are VBOs only for OpenGL 3.x?

I'm using immediate mode and I know it's bad, slow, and deprecated. But then I looked at display lists but they are deprecated too. I guess the VBO is the only one left so is it only for OpenGL 3.x?