texts: Why has the industry switched from C to C++?

texts:
First of all i would like to have a real answer, i'm always trying to get more from various sources and articles, and when I read things like C++ is slow because it has virtual functions and because of this C is better, i really don't know what to say and think as an human being with a brain. So please avoid to reach this level in your answer/s.

My question is about a massive switch to C++ that was completed, more or less, with Doom 3.

The interesting thing for me is that before this milestone, most of the game engines and the games itself were written in C, just like it was since the Quake era. It's also interesting to note that the ID software decide to completely rewrite the codebase for the IdTech 4 in C++, a massive amount of work that honestly i can't understand without a really good list of reasons.

I'm focusing on Doom 3 because I am mainly interested in the OpenGL world and in my journey i try to stay focused on this topic, so i read a lot about this, but i think that a question like that can be render-API-agnostic without too much problems.

Why at a certain point in time the industry switched massively to C++ ? What are the reasons for the choice that ID made ?

The last thing that i would like to say is that the C language is much more simple to implement and provides a less number of features, because of this has much less chance to be "fragmented" in pieces unlike the C++ really often does. In simplest terms i have much more chances to find a really good C compiler rather than a good C++ compiler with all the features implemented in a good way.

For example the NDK for Android still doesn't have a good C++ support ( with the r8b release ) with all the latest and greatest features, and it's the native toolkit for the most popular mobile OS in the world!

If I had wrote my code in a modern C++ I would probably be in pain now because one of the most popular OS in the world would be off-limits for me. And like Android, many other compilers are not that great.

I should write C++ code referring to a C++ version that is 2-3 release old ?


texts: Using sourceRect or cropping out a Texture 2D to draw? MonoGame/XNA

texts:
I was wondering what is the best way to draw textures (for performance). Using the sourceRectange in the spriteBatch.Draw() call and just draw the whole spriteSheet, or crop out every texture on the spritesheet and store them in there own Texture2D object? Like this :

    public static Texture2D Crop(Texture2D spriteSheet, Rectangle source)
    {
        Texture2D croppedTexture2d = new Texture2D(spriteSheet.GraphicsDevice, source.Width, source.Height);
        Color[] imageData = new Color[spriteSheet.Width * spriteSheet.Height];
        Color[] croppedImageData = new Color[source.Width * source.Height];

        spriteSheet.GetData<Color> (imageData);

        int index = 0;

        for (int y = source.Y; y < source.Y + source.Height; y++)
        {
            for (int x = source.X; x < source.X + source.Width; x++)
            {
                croppedImageData [index] = imageData [y * spriteSheet.Width + x];
                index++;
            }
        }

        croppedTexture2d.SetData<Color> (croppedImageData);
        return croppedTexture2d;
    }

And just call that method in the LoadContent() method?


texts: How is persistence managed by browser games?

texts:
I was wondering,

when you play browser games you never seem to witness a page refresh, even if there is data being stored on the server. So how are databases handled by browser games.

In my opinion there are several possible scenarios:

Data is being modified during your absence. Let's say in FarmVille your plants will grow while you are not using the application. So is this data being constantly updated on the server or does the application calculate everything that might have happened in a fast forward when you launch it?
Let's say you are currently playing in the browser and you completed a mission and get a coin reward or something. Is this data-update instantly written to a database or is it somehow stored in some kind of session tracker (cookies?) and stored on the server once you leave the application?

If it is written to the server instantly how is this done without a page refresh? I mean if there is some kind of client/server communication there must be a page refresh right?

If the data is send to the server once you leave the application, how to handle a case where the user simply kills the browser process by simply closing it? Can this scenario be catched by code so the data can still be written?

I read about several options to use JavaScript for database communication but I guess this is not an option, security, right? Wikipedia says that this kind of games do rely on server-side code but how exactly is this accomplished?

In case this matters, my approach for a browser game would be a JavaScript application with a minimum of client/server communication.


texts: Can I integrate Unity 5 with the 0.6.0 runtime for Oculus DK2?

texts: I am a new user and I am trying to get the Oculus running on an old PC. I had a few issues with the latest SDK so I am currently using the 0.6.0.1-beta version. I would like to integrate Oculus with Unity. My question is whether I can use Unity 5 with the SDK 0.6.0.1-beta and which kind of integration should I use - or if I should download a previous release of Unity. Thank you!


texts: Simple way to shoot bullets from a ship at angles for shoot em up

texts: Just like the title says. I'm working on a shoot em up for a personal project, and I can't seem to get this to work. I don't have any code for it, but I do have the code to make my ship shoot, but that's pretty straight forward mumbo jumbo. I have seen people use the Math function for this, but any help would be appreciated.


texts:
For my newest project, a Pokemon fan-edition, I need to collect much information on the game mechanics. So I need to know a few things about the A.I. implemented in the games. For the sake if simplicity here are my questions:

Do today's Pokemon games (Diamond, Pearl, Platinum, HeartGold, SoulSilver, Black, White) include an A.I. or is everything more or less random?
Has anyone information or even resources on that topic so that I can reuse this to build my battle system?


texts:
Ok I have two rectangles
one is the ball and other is the paddle.

1.    if(ball.rectangle.intersects(paddle.rectangle))
          y = -Math.Abs(y);

and

2.   if(paddle.rectangle.intersects(ball.rectangle))
        y = -Math.Abs(y);
       // y is y-axis of ball

are both of them same.
I used the (1.) code and when my bouncing ball touches the paddle it reflects as I want it too but when I use the (2.) code my bouncing ball it sticks with the paddle for some milliseconds then bounces off as I want it too.
I don't understand why they aren't the same. Can anybody tell me the difference between them?


texts: Using Appendbuffers in unity for terrain generation

texts:
Like many others I figured I would try and make the most of the monster processing power of the GPU but I'm having trouble getting the basics in place.

CPU code:

using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour
{
   public ComputeShader Generator;
   public MeshTopology Topology;

   void OnEnable()
   {
      var computedMeshPoints = ComputeMesh();
      CreateMeshFrom(computedMeshPoints);
   }

   private Vector3[] ComputeMesh()
   {
      var size = (32*32) * 4; // 4 points added for each x,z pos
      var buffer = new ComputeBuffer(size, 12, ComputeBufferType.Append);
      Generator.SetBuffer(0, "vertexBuffer", buffer);
      Generator.Dispatch(0, 1, 1, 1);
      var results = new Vector3[size];
      buffer.GetData(results);
      buffer.Dispose();
      return results;
   }

   private void CreateMeshFrom(Vector3[] generatedPoints)
   {
      var filter = GetComponent<MeshFilter>();
      var renderer = GetComponent<MeshRenderer>();

      if (generatedPoints.Length > 0)
      {
         var mesh = new Mesh { vertices = generatedPoints };
         var colors = new Color[generatedPoints.Length];
         var indices = new int[generatedPoints.Length];

         //TODO: build this different based on topology of the mesh being generated
         for (int i = 0; i < indices.Length; i++)
         {
            indices[i] = i;
            colors[i] = Color.blue;
         }

         mesh.SetIndices(indices, Topology, 0);
         mesh.colors = colors;

         mesh.RecalculateNormals();
         mesh.Optimize();
         mesh.RecalculateBounds();
         filter.sharedMesh = mesh;
      }
      else
      {
         filter.sharedMesh = null;
      }
   }
}

GPU code:

#pragma kernel Generate

AppendStructuredBuffer<float3> vertexBuffer : register(u0);

void genVertsAt(uint2 xzPos)
{
   //TODO: put some height generation code here.
   //      could even run marching cubes / dual contouring code.

   float3 corner1 = float3( xzPos[0], 0, xzPos[1] );
   float3 corner2 = float3( xzPos[0] + 1, 0, xzPos[1] );
   float3 corner3 = float3( xzPos[0], 0, xzPos[1] + 1);
   float3 corner4 = float3( xzPos[0] + 1, 0, xzPos[1] + 1 );

   vertexBuffer.Append(corner1);
   vertexBuffer.Append(corner2);
   vertexBuffer.Append(corner3);
   vertexBuffer.Append(corner4);
}

[numthreads(32, 1, 32)]
void Generate (uint3 threadId : SV_GroupThreadID, uint3 groupId : SV_GroupID)
{
   uint2 currentXZ = unint2( groupId.x * 32 + threadId.x, groupId.z * 32 + threadId.z);
   genVertsAt(currentXZ);
}

Can anyone explain why when I call "buffer.GetData(results);" on the CPU after the compute dispatch call my buffer is full of Vector3(0,0,0), I'm not expecting any y values yet but I would expect a bunch of thread indexes in the x,z values for the Vector3 array.

I'm not getting any errors in any of this code which suggests it's correct syntax-wise but maybe the issue is a logical bug.

Also: Yes, I know I'm generating 4,000 Vector3's and then basically round tripping them.  However, the purpose of this code is purely to learn how round tripping works between CPU and GPU in Unity.


texts: Rotating according to ground normal on Unity 3D

texts:
I know there are already some threads about this, but my problem isn't exactly with the algorithm itself.
I was able to use RayCast and get the ground normal, using it to store the rotation necessary to align to the ground in a quaternion using:

slopeRotation = Quaternion.FromToRotation (transform.up, hit.normal);

Where hit.normal is the normal of the ground. After this, I check whether the player is moving (the user is moving the joystick axis) or standing still. If it's standing still, I align it with the ground using:

transform.rotation = Quaternion.Slerp(transform.rotation,slopeRotation * transform.rotation,10*Time.deltaTime);

When the player is moving, I rotate using:

transform.rotation = Quaternion.Slerp (transform.rotation,slopeRotation *camRotation*movementRotation , 10 * Time.deltaTime);

Where camRotation is simply the rotation of the MainCamera(a third person one) on the Y axis and movementRotation is the rotation of the joystick axis, also on the Y axis, calculated using:

movementRotation = Quaternion.LookRotation (new Vector3(Input.GetAxis ("Horizontal"), 0, Input.GetAxis ("Vertical")));
camRotation = Quaternion.Euler (0, cam.transform.rotation.eulerAngles.y, 0);

Although the code above makes sense in my head, it doesn't work as expected, as seen in the picture below:

As you can see, it works fine when you're standing still, which means that the ground normal and the slopeRotation are correctly calculated. When the player moves though, the combination of all the quaternions seems to cause some kind of problem that makes the player slightly deviate from the correct rotation.
It might be worth noting that camRotation and moveRotation also work completely fine on their own, so the player moves correctly according to both the rotation of the camera and of the joystick, both on the floor and on ramps.


texts: Unitys [SerializeField] and parallel inheritance

texts:
I have the following:

public class Item
{
    [SerializeField]ItemData _data;

    public ItemData data { get { return _data; } }
}

public class Weapon : Item
{
    [SerializeField]WeaponData _data;

    public WeaponData data { get { return _data; } }
}

public class ItemData : ScriptableObject { }
public class WeaponData : ItemData { }

It seems like a pretty common setup to me, data is separated from logic classes - and I can use single scriptable objects to define stats for alot of items.

However, Unity gives me this error message:

  The same field name is serialized multiple times in the class or its
  parent class. This is not supported:

I understand what's going wrong, but I don't get how to work around it, I want the data objects to inherit so I don't need to keep two (or more, further into inheritance) separate data objects per weapon.

I also need the item inheritance for inventory/merchant list management.
Using hiding screws up the serialization of the baseclass, which means I can't create default items - not feasible.

The issue is the same when using public instead of [SerializeField].

Any pointers?


texts: What is the most efficient way to store world data for a 2D tile game?

texts:
I'm working on a 2D tile based survival game for my programming class and as I was working on GUIs I realized that I would need an efficient way of storing and recalling not only the tile data and location as the world expands, but the active entities, their inventories, and the item data in said inventories.

What would be the best way to do this? Is there a specific file format or data structure that would be best? I get that my question is kind of vague but I'm stuck.


texts:
I have a 2D game and I'm working on head rotation with my newbie coding skills. My Player has child sprite object called DefaultPistol (which is the whole arm and pistol attached to it) and it has a Weapon script. The arm turns 360 (centered from the shoulder) in the scene.
What I need is for my player turn his Head wherever arm turns (the Head is also another child sprite object attached to Player like DefaultPistol) but not like rotating the head, I just simply want to mirror the head to face left or right.
I tried setting the head's x scale to 1 or -1, but it didn't work and I couldn't find what is the problem. (I also checked the inspector if I didn't attach anything, but everything is in order as far as I can see)

Here is my Weapon. You can see where I tried to implement this in Flip. How can I fix this?
public class Weapon : MonoBehaviour {

    public GameObject projectile;
    public Transform shotPoint;
    public float timeBetweenShots;
    private Animator cameraAnim;

    private float shotTime;
    private bool facingRight;
    public GameObject head;

    private void Start()
    {
        cameraAnim = Camera.main.GetComponent<Animator>();
    }

    private void Update()
    {   //this code paragraph here is calculating the shotPoint player rotation
        Vector2 direction = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
        float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
        Quaternion rotation = Quaternion.AngleAxis(angle + 90, Vector3.forward);
        transform.rotation = rotation;

        if (Input.GetMouseButton(0))
        {
            if (Time.time >= shotTime)
            {
                Instantiate(projectile, shotPoint.position, transform.rotation);
                cameraAnim.SetTrigger("shake");
                shotTime = Time.time + timeBetweenShots;
            }

        }

    }

    private void Flip(float horizontal)
    {
        if (horizontal > 0 && !facingRight || horizontal < 0 && facingRight)
        {
            facingRight = !facingRight;
            Vector3 theScale = transform.localScale;
            head.transform.localScale = new Vector3();
            theScale.x *= -1;

            transform.localScale = theScale;
        }

    }

}


texts: Optimizing updating thousands of enemies? (Or break up the enemies that need updated?)

texts:
Thanks in advance for wanting to help.

I have an array of (right now) ~1000 enemies that I need to update every frame.  The issue, I believe, is mainly brute-force checks.  I've profiled my application with dotTrace, and there are no lines of code that are inherently slow (the method itself is slow, though).  This leads me to believe that it's simply the number of operations performed that's my bottleneck.

I can already picture the comments of "why do you need to update that many objects!", so I'll answer that first.

I'm using GLEED2D (amazing level editor, by the way) to create my "maze" of enemies.  This is a top-down shooter level, so these enemies are then loaded into my game, and I move them downward each frame.  Picture a giant sheet that I move downward every frame, and you have the basic idea.

Now, I have to (currently) update every enemy with it's velocity, to keep it in sync with all of the other enemies.

This takes a long time, even on the PC, eventually starting to lag.

I'm asking for some help in thinking this problem through, or in designing a solution if you're generous.  I thought I could possibly do a chunk-based solution, where I throw enemies into arrays that contain bite-sized chunks, but then I'm back to trying to update them correctly.  This would mean I'd have to move the chunk, or keep track of the chunk's offset (if it were moving) and apply them later.

I can't see that as the best solution.  Not to mention that this is a seamless level, so the chunk calculations would have to match perfectly.  However, if it sounds good, I would still require some help in figuring out how to split up and update chunks.

I've thought about this problem for days now, and nothing I've tried has worked.  Ideally, this will be a solution that can handle more than my current amount of enemies (which was why I thought the chunk-based solution might work).

Any suggestions or ideas?

Thanks!

(Additional information)

The enemies are mainly just having a velocity applied to them.  Strictly Vector2 += Vector2.


texts: Which 2D rendering algorithm is the most suited for mobile devices?

texts: Which 2d rendering algorithms are popular for mobile game engines (specifically Android) and why? Are the same ones for the desktop and/or console world as effective here?


texts:
I know that this is a difficult question and I hope I can convey my meaning. Over time I've used many different engines from XNA over Unity to Panda3d and even tried native directX once. My final impression is that an engine basically serves to do this:

implement a scene graph
offer classes like actor to add them to the scene graph
implement an asset pipeline that exports to actors or something similar
allow for custom logic scripts that hook onto the engine and are called at the right times. In Unity you can override update() in panda3d you can add methods to the taskmanager that are then called repeatedly. In Jmonkey they are called controls. It's basically the same. Additionally you can listen to physics events and the like.
then there's work done under the hood: physics, rendering and networking.

I appreciate all of these points very much and acknowledge the comfort a good engine can offer. The problem is: I'd like to create a game in a comparably young language (Google's Go) and there's no engine out there yet. Bindings for OpenGL exist and I figure I could easily hack a little engine of my own together.

The points one, two and four are not too difficult. I'd do the rendering with custom shaders anyways so that's work that has to be done in any case. For now I don't need complex physics and the standard raycast and collision check wouldn't be too hard for me. The only problem is an asset pipeline because I've got no experience in processing 3d data at all. I've only lived on the programmatical side up to now and the 3d models I've used were admittedly ugly. In the end it will probably add up to a weekend of coding and ongoing maintaining work.

The bottom-line is: I don't have to use go but then again there's no deadline for the project and I figured it might be fun to use this language. Is anyone out there still using "pure" OpenGL and can tell me about the work that lies ahead? Have you ever done this before?

Do you think that low-level OpenGL is a too complex choice for a one-man team or does the work to hack together something of my own pay off in the end ?

EDIT: You might want to read the comments below Nicol Bolas post since they explain the question a little better.


texts: SFML - How to animate two Sprites with the same Clock?

texts:
I'm making a basic Street Fighter style game in SFML, and I use Clock and Time() from SFML to time the animations. Here's the code I started with for my Idle() animation:

//frameTimer being Clock frameTimer;
void SpriteAnimator::Idle(Sprite & targetSprite, IntRect & targetRect)
{
    // changes x of target rect to proper point in sprite sheet to start animation
    if (targetRect.left < 0 || targetRect.left > 150)
        targetRect.left = 0;
    // every 0.2 seconds, change targetRect
    if (frameTimer.getElapsedTime().asSeconds() > 0.2)
    {
        if (targetRect.left == 150)
            targetRect.left = 0;
        else
            targetRect.left += 50;
        targetSprite.setTextureRect(targetRect);
        frameTimer.restart(); // set Clock back to 0
    }
}

This works for one sprite, but I have the 2nd sprite use the same methods as the first sprite. They both are objects made from PLayer.H, and they both call an instance of SpriteAnimator to animate their respective sprite sheet.

The problem is, they're both running off the same clock, so when one sprite calls frameTimer.restart(); it messes both of them up, and only one can Idle() at a time.

How can I make it so they both can loop through their spritesheet at the same time, without the clocks overlapping?

(Btw my class structure is like this:
main.cpp -->has player.cpp -->has spriteAnimator.cpp)


texts: A* heuristic for a map that can have roads

texts:
I have a 2D grid which I am performing A* pathfinding on. Nodes are connected via a value of 3 in most cases (some connections are more expensive). In some (depends on the gameplay) circumstances the node may have a road to another node though, bringing the connection cost down to 1.
The heuristic cost is determined by multiplying the heuristic value (as stated below) with the minimum connections to take (this is known).
If I use a heuristic of 0 per connection then A* will always find the shortest path, due to just performing a Dijkstra search. Not ideal.
If I use a heuristic of 1 per connection then A* will still always find the shortest path, but will not be very efficient even when the path is straightforward. This is my fallback.
If I use a heuristic of >1 per connection then A* may not always find the shortest path, but will be more efficient. I am kind of scared of this "not always the shortest path".
I'm considering using a heuristic of 1 (or just always lower the heuristic score by a set amount without letting it get below 1) for connections heuristically close to the target (and maybe close to the start too?) to have "perfect" pathfinding in the regions where it may matter most. Useful or wrong thinking?
What would be a good way to handle this setup? Any tips?
Edit: I just found http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html and wanted to mention it, quite helpful.


texts:
If I want to release an App with a Company Name do I have to have that registered before I can use it?

I have checked and the name is not taken, so is it fine to just use a made up company name?

As a side note, I have made this game just as a hobby project, not looking to make any money from it.


texts:
Hello mature game developers. Im just started with XNA, but i got solid expirence with C#.
I wonder is there any common code patterns for XNA games?

Like should i make classes wich handle draw and update separatly, like draw model and world  data model? Or should i try to put as much code as possible in Game1 ?

Im totaly lost in project structure building. Thx for any answers.


texts: Random white lines appearing while translating rendering slick 2d images

texts:
Hmm I'm getting this weird problem that i think may be a bug with slick but when ever i translate an image in slick 2d for some reason a weird white line appears on the left side of every image like this

This is the method for rendering each of the tiles, btw they are 32x32 textures

public void render(GameContainer gc, StateBasedGame game, Graphics g) throws SlickException {
    g.translate(-playerX, -playerY);
    //render the blocks here
    for(int x = 0; x <= ((Size.WIDTH/Size.Tile)+1); x++) {
        for(int y = 0; y <= ((Size.HEIGHT/Size.Tile)+1); y++) {
            g.drawImage(Sprites.dirt, x*Size.Tile, y*Size.Tile);
        }
    }
    g.translate(playerX, playerY);
    //render the player here, dont touch
    //no texture it was based off an old sheet
    g.drawImage(Sprites.grass, (Size.WIDTH-Size.Tile)/2, (Size.HEIGHT-Size.Tile)/2);

Sprite Getter :

public class Sprites {
    public static Image SpriteSheet;
    public static Image grass;
    public static Image dirt;
    public static void Init() throws SlickException {

        SpriteSheet = new Image("assets/images/SpriteSheets/Sprites.png");
        grass = SpriteSheet.getSubImage(0, 0, Size.Tile, Size.Tile);
        dirt = SpriteSheet.getSubImage(0, 1*32, Size.Tile, Size.Tile);
    }
}

if you want to see the rest of the code it is at MC2D.zip


texts: (Three.js) - What object3D properties are required to make rayCaster.intersectObjects() work?

texts:
FYI, i am trying to do something almost identical to the following:
Merging geometry/mesh without losing benefits

I essentially have a list of Three.object3D's. These objects are "merged" together into a single BufferGeometry (so that i can draw thousands of these objects with a single draw call).

After merging these objects I still do have references to all of the original objects (via a class which simply "has a" object3D object reference).

* Question *

I am calling raycaster.intersectObjects(myObjects) on this list of original Object3D's. Im wondering what properties are required for this intersectObjects method to work? In other words, the ray caster must be checking against each objects position and geometry. What properties (position, geometry?) are required and where do these properties exist (within the Object3D reference)?

Whew. I hope this all makes sense.


texts: Tracking small moving targets in Vuforia

texts:
I am trying to track up to two small moving objects the size of a small toy car (about 7x4x4 cm / 3x2x2”)  from a 75cm / 2ft distance. I’m aware that the distance/size ratio is about 20, which is off by factor compared to the by Vuforia recommended ratio.

I've tried frame markers and while frame markers are super fast close up, they don't work well at a distance. I'm hesitant to use expensive object recognition on moving targets. I’ve tried black and white QR codes and AR markers as image targets but Vuforia seems to have trouble recognizing them, even though the QR code has a five star rating.

I’m considering two more options:

1) an optimized 4x4cm color image target

2) add LEDs to the objects and track the LEDs, for example like this: https://www.youtube.com/watch?v=IoL0bIGk_uE

My questions:

1) Are there specific tips for creating small image targets (I have read the generic image target optimizations tips assume not all those tips apply to small targets)

2) Is there an easy way to track LEDs in Vuforia?


texts: Why does my tile palette not arrange nicely?

texts:
I made my own Hex Point Top Tile sprite sheet, ensuring it's pixel perfect and align well. Slicing in Sprite Editor has no problem too. However, when I drag the sprite sheet to a new Palette in the Tile Palette panel, the tiles show up with random spaces. See screenshot below:

What did I miss?

The sprite sheet is here, 30 x 30px offset, 24 x 24px padding, 66 x 66px tile size:

I'm using Unity 2019.3.10f1.


texts: 2D Screen Coordinates to 2D World Coordinates in LWJGL

texts:
I'm making a 2d top down game with lwjgl and am having trouble converting my 2d screen coordinates to 2d world coordinates.

Here's what I have so far

 private Vector2f toWorldCoords(Vector4f eyeCoords) {
    Matrix4f invertedView = Matrix4f.invert(MathUtil.createViewMatrix(camera), null);
    Vector4f rayWorld = Matrix4f.transform(invertedView, eyeCoords, null);
    Vector2f mouseRay = new Vector2f(rayWorld.x, rayWorld.y);
    mouseRay.normalise();
    return mouseRay;
}

public Vector2f screenToWorld(Vector2f mouseCoords) {
    Vector2f normalizedCoords = CursorHandler.getNormalisedDeviceCoordinates();
    Vector4f clipCoords = new Vector4f(normalizedCoords.x, normalizedCoords.y, -1.0f, 1.0f);
    Vector2f worldRay = toWorldCoords(clipCoords);

    return worldRay;
}

I understand it's been asked before, and I've tried following some 3d tutorials that deal with the same topic, but so far I haven't been able to use the code successfully.

Thanks


texts: ParticleEffectPool.obtain() not resetting particles

texts:
I want to use ParticleEffectPools in libGDX but I'm running into an odd issue where the effects don't seem to be reset when obtained by the pool. The code below looks for an existing ParticleEffectPool for the named effect, creates one if necessary, and then obtains a particle effect for the newly created Actor. The particle effect should be reset in the obtain function (if you look at the source it does so). What happens is the first effect works as expected but every subsequent one flashes very briefly on the screen as if its run out of duration.

public class ParticleEffectActor extends Actor {

    private static final Map<String, ParticleEffectPool> ParticlePools = new HashMap<>();
    private final PooledEffect effect;

    public ParticleEffectActor(String effectName, float rotation) {
        if(!ParticlePools.containsKey(effectName)) {
            ParticleEffect particleEffect = new ParticleEffect();
            particleEffect.load(Gdx.files.internal("resources/particles/" + effectName + ".p"), Images.Atlas);
            ParticlePools.put(effectName, new ParticleEffectPool(particleEffect, 10, 50));
        }

        this.effect = ParticlePools.get(effectName).obtain();

        rotation -= 90f;
        for(ParticleEmitter emitter : effect.getEmitters()) {
            emitter.reset();
            ParticleEmitter.ScaledNumericValue angle = emitter.getAngle();
            angle.setLow(rotation - 35, rotation + 35);
            angle.setHigh(rotation - 35, rotation + 35);
        }
    }

    @Override
    public void draw (SpriteBatch batch, float parentAlpha) {
        effect.draw(batch);
    }

    @Override
    public void act (float delta) {
        super.act(delta);
        effect.setPosition(getX(), getY());
        effect.update(delta);
    }

    @Override
    public boolean remove() {
        effect.free();
        return super.remove();
    }
}


texts:
If I have a Vector, say (1,1), how can I rotate it around the origin (0,0)?

I'm working in XNA if that helps.


texts:
I want to clamp the vertical rotation of the first person controller I was making. I want to restrict the vertical rotation of the main camera between -90 and 90 degrees. The code is as follows:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MouseY : MonoBehaviour
{
    [SerializeField]
    private float _sensitivity = 5.0f;
    private float _verticalInput;

    // Update is called once per frame
    void Update()
    {
        _verticalInput = Input.GetAxis("Mouse Y") * _sensitivity;
        Vector3 lookDirectionY = transform.localEulerAngles;
        lookDirectionY.x -= _verticalInput;
        lookDirectionY.x = Mathf.Clamp(lookDirectionY.x, -90f, 90f);
        transform.localEulerAngles = lookDirectionY;
    }
}

In the above code, Mathf.Clamp does not work for -90. On reaching 0 degrees, it reels back to the +90 degrees. What could be the reason for this and how to resolve it?


texts:
When and how should I update my collision grid?

Current implementation:

buildGrid(): add all entities with collision to the grid
handleCollision(timePerFrame, entities): handle all collisions
grid.clear(): clear grid

If I have for example 4000 stationary entities and only 20 moving entities, I remove and add 4000 entities to the grid every update for no reason.

What would be the good way to update only cells that require updating?

Only idea that I have currently is that after collision check I remove moving entities from the grid and during buildGrid() I add only moving entities to the grid.

All help is welcome.

Grid implementation

// CollisionGrid Cell
class Cell
{
    public:
        typedef std::set<Entity*> Container;

    public:
        void        setNeighbours(Cell* left, Cell* right, Cell* up, Cell* down);
        void        addEntity(Entity* entity);
        Container   getNearbyEntities() const;
        void        clear();

    private:
        void        appendEntitiesTo(Container& entities) const;

    private:
        Container   mEntities;

    protected:
        Cell*       mLeft;
        Cell*       mRight;
        Cell*       mUp;
        Cell*       mDown;
};

// CollisionGrid
class CollisionGrid
{
    public:
                            CollisionGrid(float sceneWidth, float sceneHeight, float cellSize);

        void                clear();
        void                addEntity(Entity* entity);
        Cell::Container     getNearbyEntities(Entity* entity);

    private:
        int                 getIdForPosition(const sf::Vector2f position);

    public:
        int                 mCols;
        int                 mRows;
        std::vector<Cell>   mCells;

    private:
        float               mSceneWidth;
        float               mSceneHeight;
        float               mCellSize;
};

// CollisionGrid Cell
void Cell::setNeighbours(Cell* left, Cell* right, Cell* up, Cell* down)
{
    mLeft = left;
    mRight = right;
    mUp = up;
    mDown = down;
}

void Cell::addEntity(Entity* entity)
{
    mEntities.insert(entity);
}

Cell::Container Cell::getNearbyEntities() const
{
    Container entities = mEntities;

    if (mLeft != nullptr)
        mLeft->appendEntitiesTo(entities);
    if (mRight != nullptr)
        mRight->appendEntitiesTo(entities);
    if (mUp != nullptr)
        mUp->appendEntitiesTo(entities);
    if (mDown != nullptr)
        mDown->appendEntitiesTo(entities);

    return entities;
}

void Cell::clear()
{
    mEntities.clear();
}

void Cell::appendEntitiesTo(Container& entities) const
{
    entities.insert(mEntities.begin(), mEntities.end());
}

// CollisionGrid
CollisionGrid::CollisionGrid(float sceneWidth, float sceneHeight, float cellSize)
: mSceneWidth(sceneWidth)
, mSceneHeight(sceneHeight)
, mCellSize(cellSize)
, mCols((int)floor(sceneWidth / cellSize))
, mRows((int)floor(sceneHeight / cellSize))
{
    mCells = std::vector<Cell>(mCols*mRows);

    for (int id = 0; id < mCols*mRows; ++id)
    {
        Cell* left = nullptr;
        Cell* right = nullptr;
        Cell* up = nullptr;
        Cell* down = nullptr;

        if (id % mCols > 0)
            left = &mCells[id - 1];
        if (id % mCols < mCols - 1)
            right = &mCells[id + 1];
        if (id > mCols - 1)
            up = &mCells[id - mCols];
        if (id < mCols * (mRows - 1))
            down = &mCells[id + mCols];

        mCells[id].setNeighbours(left, right, up, down);
    }
}

void CollisionGrid::clear()
{
    for (Cell& cell : mCells)
        cell.clear();
}

void CollisionGrid::addEntity(Entity* entity)
{
    mCells[getIdForPosition(entity->position)].addEntity(entity);
}

Cell::Container CollisionGrid::getNearbyEntities(Entity* entity)
{
    return mCells[getIdForPosition(entity->position)].getNearbyEntities();
}

int CollisionGrid::getIdForPosition(const sf::Vector2f position)
{
    return int(floor(position.x / mCellSize) + floor(position.y / mCellSize) * mCols);
}


texts: How to play somersault animation during jumping at top point like in Contra games in 2D game (godot, gdscript)?

texts:
Here is my jumping code:
if is_on_floor():
    if Input.is_action_just_pressed("ui_up"):
        motion.y = JUMP_HEIGHT
    if friction == true:
        motion.x = lerp(motion.x, 0, 0.2)
else:
    if motion.y < 0:
        $Sprite.play("Jump")
    else:
        $Sprite.play("Fall")
    if friction == true:
        motion.x = lerp(motion.x, 0, 0.05)

But I want also add the somersault animation at top point like in Contra games from NES. How can I detect moment where I should play and stop this animation. Should it be related to animation frames count and play speed?


texts:
I have a game that plays sounds when some events occur.

Currently, I am using AVAudioPlayer for the purpose of playing the sound. But just the bare AVAudioPlayer has a noticeable lag time before the first playback and it stops music played by other apps.

Also, it stops the ongoing playback when a new playback is ordered. Surely, I could use a list of AVAudioPlayers for each of the effects, but that feels clunky.

I want something that will play effects mixed, one on top of another; and I want them to be played on top of background music, if there is any. I do not use any sorts of frameworks, like SpriteKit or Unity. So, how do I do this?


texts: OpenGL first person camera orientation issues

texts:
I have a "camera" in my opengl program that I recently finished. However, I've noticed that whenever I rotate and then move again, the x, y, and z angles change. For example, when I press the "w" key, I move forward along the "z" axis. If I then rotate the camera 90 degrees, when I push the "W" key, I will actually be moving right, seemingly along the "x" axis. It makes sense why this happens, I'm just wondering why its happening. Here's the rotation function:

private void camera() {
    glRotatef(xrot, 1.0f, 0.0f, 0.0f);
    glRotatef(yrot, 0.0f, 1.0f, 0.0f);
}

The keyboard function:

if (Keyboard.isKeyDown(Keyboard.KEY_D)) {
        xpos -= 0.035 * delta;
    }

    if (Keyboard.isKeyDown(Keyboard.KEY_A)) {
        xpos += 0.035 * delta;
    }

    if (Keyboard.isKeyDown(Keyboard.KEY_W)) {
        zpos += 0.03f * delta;
    }

    if (Keyboard.isKeyDown(Keyboard.KEY_S)) {
        zpos -= 0.035 * delta;
    }
if (Keyboard.isKeyDown(Keyboard.KEY_UP)) {
        xrot += 0.035;
        if (xrot > 360) {
            xrot -= 360;
        }
    }

    if (Keyboard.isKeyDown(Keyboard.KEY_DOWN)) {
        xrot -= 0.035;
        if (xrot > 360) {
            xrot += 360;
        }
    }

    if (Keyboard.isKeyDown(Keyboard.KEY_RIGHT)) {
        yrot += 0.035;
        if (xrot > 360) {
            xrot -= 360;
        }
    }

    if (Keyboard.isKeyDown(Keyboard.KEY_LEFT)) {
        yrot -= 0.035;
        if (xrot > 360) {
            xrot += 360;
        }

    }

And my translate function:

        glTranslated(xpos, ypos, zpos - 30);

any ideas on how to solve this? I would be very grateful


texts: What's wrong with this camera implementation?

texts:
I'm using WebGL and glMatrix and I implemented a camera. When a move backward, no problem. But when I move to the side and particularly forward, the camera becomes all glitchy. I implemented almost exactly the same camera before in C++ and it worked perfectly. I put the whole code on jsFiddle (with glMatrix because it's not in the list and I didn't find a url, sry).

https://jsfiddle.net/ydx0Lr1v/14/

Click and move the mouse to move around.

Also, the more I decrease the speed of the camera movement, the more it works well. I put a high speed to dramatize the effect. I know I should make the speed of the camera depend on the time between each frame, but I haven't implemented an fps counter yet.

Thanks!

Edit: Hum, that's strange. In jsFiddle the camera seems to work better when moving forward.


texts:
I'm trying to rotate models independently of each other however I cannot for the life of my figure out how. I have gotten to the stage of writing this:

std::vector<int>::size_type st = Models.size();
if (!Models.empty())
{
    for (unsigned x = 0; x < st; x++)
    {
        D3DXMATRIX matRotate;

        D3DXMatrixRotationY(&matRotate, D3DXToRadian((x + 1) * 60));

        cBuffer[x].Final = matRotate * matView * matProjection;
        cBuffer[x].Rotation = matRotate;

        devcon->UpdateSubresource(pCBuffer, 0, NULL, &cBuffer[x], 0, 0);

        devcon->VSSetShader(pVS, 0, 0);
        devcon->VSSetConstantBuffers(0, 1, &pCBuffer);
        devcon->PSSetShader(pPS, 0, 0);

        Models.at(x)->Render(devcon);
    }
}
swapchain->Present(0, 0);

but this only updates for the first assignment of rotation. Why isn't it rotating and how do I make it? Thanks in advance.


texts:
As soon as I found out that Unreal Engine 4 is now free, I decided to get it in order to tinker with it.

So I clicked on the blue "Get Unreal" button, signed up, and downloaded (and installed) the MSI installer (working on Windows here).

After the installation completed, the "Epic Games Launcher" launched, asking me to log in. Once logged in, I selected the "Unreal Engine" tab and was greeted by a page with several tutorials and demo projects for download, while the left side offered an orange button saying "No engine installed" and no option to click on it to install one.

After some time, I found this Unreal documentation explaining how to install the engine. According to it, the engine should start downloading the moment I log in to the launcher, which didn't happen.

What am I doing wrong? How can I install the Unreal Engine?


texts: Algorithm to produce a 2D 'flying through space' effect like the old Windows screen saver

texts:
I am old. My high school maths is a long way in my past and I am struggling to devise an algorithm that will produce a 2D 'flying through space' effect like the old Windows screen saver.  It has—

stars generated close to the screen centre, which move outwards at increasing speed, and
on a key press, a hyperspace effect is generated with the stars turning to lines stretching to the edge of the screen.

I've figured out that I can use arctan and x,y offsets from screen centre to identify a direction, but given that the trig functions work in a 90 degree field. My old brain is struggling to pull it all together.

How can I create this effect?


texts:
I'm encountering an issue: I cannot move into my view with W, A, D, S. However UP, LEFT, RIGHT, DOWN arrows work. What's wrong?

Here's my viewport navigation configuration:

Viewport navigation key binding


texts: How do I create an efficient long, pannable, sprite-animated scene in a Windows Store game?

texts:
I am creating my first Windows Store application in XAML, and I cannot seem to find a proper example for the requirements I have.

The basic idea of the app is to have a large scrollable canvas which would lazily start animating visible parts of the view as soon as user stops panning over a certain content (with some audio played also):

My original idea was to use a StackPanel to add a bunch of custom controls, each of which would then animate itself once visible (with a short delay), but I have a couple of concerns:

If the entire canvas is ~50 screen widths wide, is it feasible to load all content at the beginning, or do I need to plan doing some lazy loading during scrolling? For example, when I select a certain region in the Bing Travel app, it seems to lazily load tiles as I scroll it towards the end.
Since content is stretched 100% vertically, and these animations are vectorized to be resolution independent, I am not sure if XAML (CompositionTarget) will be able to handle this, or I have to go for DirectX (MonoGame or C++) to get rid of flicker.
Even better, is there an example for Windows 8 which uses a 100% vertically sized GridView with custom animated controls inside?


texts: How do you go about distributing resources procedurally in a game?

texts:
What I mean by resource distribution is the placement of items in the game. More specifically "minable" items in builder/resource gathering games like Factorio, Oxygen not included or/and RimWorld.

The games all place clumps of the same items around each other. For example in Factorio there will be fields of resources like coal, iron, copper, etc. which will spawn together in little clusters rather than there being single resource tiles being sprinkled around the map. See screenshot:

This is a similar behaviour in Oxygen not included, similar resources are more likely to be next to each other but depending on the rarity they can also be found alone as a single block. In the game there are also zones which denote what resources can spawn which appear to be preset locations and shapes as they are the same each game (with the types mixed up), but resources themselves are position procedurally. I grabbed a screenshot online and highlighted some of the resource types to make the distribution more obvious.

The ideal answer will show what methods would work well to reproduce "clustered resource distribution", with advantages and disadvantages of a given method. It will not necessarily have code examples but rather the rough steps/pseudocode that would have to be taken.


texts:
I am implementing SDSM and in a GLSL compute shader I need to min/max vec3 values to compute the shadow map bounds. The sample implementation (in HLSL) uses vectors in "light space" that spans from 0-1 and then casts them with touint (in GLSL uintBitsToFloat) so that it can call InterlockedMinMax (atomicMin/Max) with them.

I was wondering if it is a better idea to quantize the values to an uint using the bounding volume in light space as uints instead of moving them into the 0-1 range so integer min/max works on the float bit pattern?

On the one hand using float bits in unit throws about about 2/3 the precision, because the sign bit and exponent are ignored. On the other hand almost all algorithms I came up to quantize the values somehow go past the 0-1 float range and would probably loose the precision anyway.


texts: When does it make sense to use Index Buffers?

texts:
The concept of Index buffers is that certain vertices are shared across faces, hence can be reused to save space of duplicated verticies. A vertex is usually more than 12 bytes (depending on the number of attributes, ie. 3* 32-bit floats), while an index could be stored in as little as 1 to 4 bytes (depending on max number of vertices).

  Example: A cube consisting of 6 quad-faces without using an index buffer would
  require 6 * 4 * 12 = 288 bytes But as it only has 8 unique vertices,
  it could be stored using an index buffer with 4 * 6 indices = 8 * 12 + 4 * 6 = 120 bytes

However for non-shared vertices the space used by the Index Buffer is effectively wasted - because these vertices could've been drawn without an index buffer (if correct ordering in the vertex buffer is given). Considering only the vertex position as attribute, this trade-off would make sense for most meshes - but meshes in the real-world tend to have also other attributes like normals, texture-coordinates etc. Even if a vertex position is shared across faces, it is rare that all other attributes are also shared - hence the vertex needs to be duplicated in the vertex buffer.

  Example: A cube with normals has 8 unique vertices, but each of its 6 faces
  having a different normal vector. So 48 unique vertices are required,
  if one vertex is 24 bytes this results in = 8 * 6 * 24 = 1152 bytes
  Using an index buffer the same size is needed plus at least 48 bytes
  to store the indices = 1200 bytes

Not only would a vertex buffer without index buffer need less memory, it would probably be more cache-friendly as well (as the memory accessed is continous memory).

I try to find out in which scenarios I should use an index buffer instead of a plain vertex buffer, but I failed to find any real-world examples where it would make sense to use an index buffer at all.

My question is: Are there any cases in modern graphics-programming where using an index buffer will actually bring a benefit (ie. is there any advantage which I overlooked)?


texts: Unity associated game object is null when running

texts:
I am just starting with Unity.
I have two UI Text game objects, Atext and Btext. I have associated them by drag-dropping with my PlayerController script public variables, say public Text atext and public Text btext.
Before running, the Unity editor correctly shows that Atext and Btext are correctly associated with the public variables.
When running with debug, I get a null reference exception with btext and even the Unity Editor shows the association as None (Text). After stopping, the association turns to Btext as it is supposed to be. The script is very simple and I don't set btext to null at any point.

When I create a new UI Text object by duplicating Atext, it works correctly after associating it with some new variable.
When I create a new UI Text object by Create-> UI -> Text, it doesnt work

Might be a stupid question but what am I forgetting?

Edit:
Here is the problem again with code:

Before running with debug, the editor shows

PlayerController2 (Script)
Script: PlayerController2
Speed: 7
Countboxref: Countbox(Text)
Winboxref: Winbox (Text)
Brokenboxref: Text (Text)

where Countbox, Winbox, and Text are Canvas/UI/Text objects which I have drag dropped into place. Winbox object has been created by duplicating it from Countbox, Text has been created by Create -> UI -> Text.

enter using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class PlayerController2 : MonoBehaviour {

public float speed;
public Text Countboxref;
public Text Winboxref;
public Text Brokenboxref;
private Rigidbody rb;
private int boxit;

void Start ()
{
    Countboxref.text = "count";
    Winboxref.text = "winner";
    Brokenboxref.text = "broken";
}

When the program breaks on line Brokenboxref.text = "broken”, the editor shows

Brokenboxref: None (Text)

and when the execution is stopped completely, it again returns to

Brokenboxref: Text (Text)

Note 1: In this project, every Text object created with Create->UI->Text is broken. A new Text object works only when I select Countbox or Winbox and duplicate it. Thus it is not possible that the object would be explicitly destroyed in the code. I can create as many Text objects as I wish by copying (all don't work) and as many Text objects as I wish by duplicating (all will work).

Note 2: when I create a new project from scratch, of course everything works as expected. I assume the project is somehow corrupted.

Edit 2: No prefabs or such. Just the basic roll a ball tutorial. But this was my son's project so I am not sure what he has done when following the tutorial.

Note 3: The problem went away when I deleted the Library folder and forced Unity to rebuild it. Don't know yet if I caused any other problems by doing that. I saw that somewhere as a suggestion for corrupted projects. I don't know if there is a proper way to refresh.

Also, this project was originally started with Unity 4.6 and upgraded to 5.02


texts: How to change a shape project when obstructed by object

texts:
I have a customized shape (mesh) in 3D as shown below:

Now that customized shape projection will change when there are several obstacles located in front of the customized shape.
I expect the result to look like this:

Questions:
1) How do I change the customized shape project when there are obstacles located in front? Which mathematical formula or theory can I use?

Please advise.
Thank you.


texts: 2d game view camera zoom, rotation & offset using 'Filter' / 'Shader' processing?

texts:
I wish to add the ability to zoom-in, zoom-out, rotate and move the view in a top-down view over a collection of points and lines in a large 2d map. I split the map into a grid so I only need to render the points that are 'near' the camera.
My question is, how do I render a point A(Xp,Yp) assuming the following details:

Offset of the camera pov from the origin of the map is:

Xc, Yc

Meaning the camera center is positioned on top of that point. If there's a point in Xc, Yc it is positioned in the center of the screen.

The rotation angle is:

alpha

The scale is:

S

Read my answer first. I am thinking there is more optimized solution, thanks.

My question is how to include the following improvement:

I read in the AS3 Bible book that: In regards to ShaderInput, You can use these methods to coerce Pixel Bender to crunch huge sets of data masquerading as images, without doing too much work on the ActionScript side to make them look like images.

Meaning if I am performing the same linear function on a lot of items, I can do it all at once if I use Shaders correctly and save processing time.

Does anyone know how that is accomplished?

Here is a sample of what I mean:

http://wonderfl.net/c/eFp0/


texts: Can't play animation from script in unity

texts:
I'm making a 2D sidescrolling game in Unity, and when the player shoots an obstacle, I want the obstacle animation to play and then destroy itself. I got it to destroy itself, but the animation won't play. Any suggestions?

    public class obstacleAnim : MonoBehaviour {

    protected Animation obsanim;

    // Use this for initialization
    void Start () {
        obsanim = GetComponent<Animation> ();
    }

    void OnCollisionEnter2D(Collision2D col)
    {
        if (col.gameObject.tag == "circle")
        {
            obsanim.Play ("circobs");
            Destroy (gameObject, 1.0f);
        }
    }
}

thank you for any help!


texts:
Is there pathfinding algorithm which takes car steering into account?

I have large space where user can place cars (trucks actually) and other blocker objects.
Objects can be placed vertically or horizontally oriented and have different sizes (may be 3x6 or 2x4 or other size).
User needs to be able to select new location for any car - then I need to calculate how can that car move to selected location.

I have pathfinding working, and I can find paths with different size but only for square objects.

Update:

Pathfinding need to give only path that is possible with that type of car. For example on empty map with only one car, if user selects new location right next to its current location, car can't strafe or turn in place it has to either reverse and steer or do U turn or something.
Also it must ensure that car orientation at end is what user requested.


texts: How can I implement child objects that follow the movement of a parent?

texts:
I'm looking for a way to have a character, let's call it "root," with a number of other similar characters attached to it. Let's call them children. When the root changes position the children follow and update their own position by their movement patterns.

My objective isn't for the child objects to move 1:1 like the root but to react to it's movement and follow the object loosely. So if the root moves upwards then child follows afterwards with it's own velocity.

Could someone guide me about how to achieve this kind of behavior of objects moving relative to others? About what sort of architecture would fit best for this kind of problem?


texts: Would adding delay to inbound traffic give you an advantage in online games?

texts:
Wouldn't adding a latency delay to inbound traffic and limiting your download speeds to a low but playable standard give you an advantage in online games, especially shooters?

Because wouldn't your shots be registering as normal (using upload/outbound) while anything that attempts to hit you (download/inbound) would be delayed and/or slow?


texts: How can I handle multiple force in Unity?

texts:
I'm trying to get my character to perform a "dash" where their x velocity increases rapidly and then falls over time. However, I'm also maintaining a constant x velocity so the character appears to be running at all times. The problem is trying to figure out when the dash should be considered finished. It can't be finished when the x velocity is equal to the running speed again, because other forces may be acting on the character.

It feels like all the information I need to figure this out is gone because it's all been calculated into the velocity vector, and the actual forces and where they come from are thrown out.

I've considered the following:

final = run + dash + other forces

But this means I couldn't use Unity's forces because I don't know what they're meant to act on(for example should a force pushing me down while I jump be applied to the jump velocity or the not?).

How can I determine how much force my dash should do and how much it should "undo" with the information given by Unity?


texts:
My animation is working but unity keep saying that my Animator has not been initialized error
Here my Code:

using UnityEngine;
using System.Collections;

public class Player: MonoBehaviour {

public float maxspeed = 10f;
bool facingRight = true;

Animator anim;

bool grounded = false;
public Transform groundCheck;
float groundRadius = 0.2f;
public LayerMask whatIsGround;

void Start ()
{
    anim = GetComponent<Animator> ();
}

void FixedUpdate () {
    grounded = Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround);
    anim.SetBool ("Ground", grounded);

    float move = Input.GetAxis ("Horizontal");
    anim.SetFloat ("Speed", Mathf.Abs (move));

    GetComponent<Rigidbody2D>().velocity = new Vector2(move * maxspeed, GetComponent<Rigidbody2D>().velocity.y);
    if (move > 0 && !facingRight){
        Flip ();
    } else if (move < 0 && facingRight) {
        Flip ();
    }
}

void Flip()
{
    facingRight = !facingRight;
    Vector3 theScale = transform.localScale;
    theScale.x *= -1;
    transform.localScale = theScale;
}

}


texts: How to avoid "completely" dark shadow using directional light (as Sun) ?

texts:
Look at my scene:

Sun is rising and as you can see the scene is realistic; I mean, that what is in shadow is almost completely dark. This is correct, but i would like something less "dark", like an HDR.

These are some parameters i'm using:

This is my unique Light in scene (Sun):

I'm using also a Post-Processing profile with "Eye Adaption" unflagged.

Can you suggest me what i've to change to make my object affected by shadow less.. dark ?

Thanks


texts: How should I store loaded world chunks in RAM (For my game similar to Minecraft)?

texts:
I am trying to replicate a chunk loading system, in C, for my own minecraft like game, though I don't know how. Once chunks are loaded, are they placed in an array, or are there a bunch of variables for each loaded chunk?
In my game, once I load chunks using fread, what should I use to store them? My problem for a two dimensional array for storing chunks, is that the loaded chunks might be separate and not start at zero. Are there any suggestions for storing loaded chunks?

I have a code fragment, solely so you guys will not yell at me for not including code:

    char ChunkFilePath[strlen(CurrentWorld)+32];
    sprintf(ChunkFilePath, "%s/ChunkData/%ld %ld", CurrentWorld, X, Z);
    FILE *ChunkFile;
    if ((ChunkFile = fopen(ChunkFilePath, "r"))) {
        //chunk file exists, Read Chunk file to ???
    }
    if ((ChunkFile = fopen(ChunkFilePath, "w")) == NULL) {
        fputs("Error Loading Chunk (File Not Found)", stderr);
        return;
    }
        /*Chunk does not exist, but any other errors would have been caught
        at this point, so Generate chunk, write generated results to ???*/

Note: The game I am trying to make is purely for my personal use, not for any commercial use.

  Edit:

The problem is just an array will not work. Suppose there is a player at 1000000 and another one at -1000000 They would only render 6 chunks around them, but if they shared an array, all the 2000000 blocks worth of chunks that aren't loaded would be taking up memory. I would refer to chunks like LoadedChunk[1000]. How can I handle that?


texts:
I am wondering how games generate IDs/GUIDs for their entities (along these lines), and which entities specifically get them. To narrow the scope of the question down, I am just focusing on FPS games such as Halo. This was an earlier question that helps explain how state is synced across clients in an FPS:

The state that is synced when a window is broken in a FPS game

The goal with that question was to learn what kinds of data is sent around to sync clients. The piece that is still missing for me is what entities in the game actually get an ID of some sort (either a GUID, or a scoped ID such as some incremented integer or something).

Some of the game "entities" I am considering are:

Particles of light, individual pixels, physical forces, etc. (the lowest level vectors/points for calculating light or physics stuff).
Topology (mountains, roads, etc.).
Landscape features (grass, bushes, trees, rocks, water, rain drops, etc.).
City features (cars, signs, buildings, windows, shards of glass from a broken window, etc.).
Tools / items (weapons, potions, etc.).
Other players.

It seems that some of these "entities" you can interact with (e.g. destroying a car in GTA, or the other players in the game), some you can to some degree (i.e. bushes might sway when you walk by, but you can't shoot them for example), and some you cannot (like the sun in a skybox).

I am thinking in terms of state syncing, it seems like there must be IDs somewhere in the picture so you can map a game entity from computer A to the same game entity in computer B. Even without syncing, it seems like you might want some sort of IDs on objects to allow for easier handling of events and tracking objects. But at the same time I don't really see "IDs" in simple "game engines" like these JavaScript game engines, so that is why I'm asking the question.

The question is, for large games like Halo, what the entities are that have IDs (or some of the main ones), and if the IDs are GUIDs (or generally what kind of ID they are: incremented integers, random numbers, UUIDs, etc.).

Like I'm wondering, maybe bushes have IDs. Maybe the individual leaves on the bushes have IDs. Maybe every single triangle in the graphics has an ID. That's what I'm wondering. Maybe the shards of glass have IDs because you can pick them up. Maybe only the players have IDs for some reason. Etc.

I am interested because (a) it seems like IDs are necessary in different ways (for state syncing, for tracking player behavior with different entity types to improve the game experience, etc.), and (b) there is a lot of variation in performance when it comes to using IDs. For example, I just tried generating 1 million particles like this and got these results:

crypto.getRandomValues: 5.7 seconds to generate 1 million IDs.
Math.random(): 18ms to generate 1 million IDs.
i++: 5ms to generate 1 million IDs.

In addition, there is the space constraint, so by using i++ you can use fewer bits for the ID until it gets very large, but they don't work as GUIDs so you need to do extra work to create ID "scopes" or things like that. Anyways, I would like to figure out how to deal with IDs in games, and looking to FPS as an example to demonstrate where the IDs might be used. Any help would be appreciated. Thank you.

If it is a complicated topic (I'm not sure), then just knowing roughly an outline of how it is typically done, or even a place to look for more information, would be helpful. Also, just saw how Unity is a good example of a Component/Entity system, so maybe instead of FPS a better example is how generic game engines do it. Either way, whatever helps explain how it works.


texts:
I've been looking at ways to load data into a game.  I even asked a question on stack overflow about reading binary data in a portable manner .  The gist of the answer seemed to be that you can use the int types header file to specify an particular integer byte amount, but there's nothing really useful for floats, etc.

I then thought that you could use fixed point, rather than floating point, but I wanted to see how other games did it.  Here is one example, a md2 loader: http://tfc.duke.free.fr/old/models/md2.htm .  However, it seemed to assume that the size of various types would just work, and that they would be the same on the platform that made the md2, and the one that read it.  This seemed to be fairly common in the code that I've seen so far.

So is it really common to just ignore possible different size issues, or have I just been looking at bad (or old) samples?  If it's not, could you also demonstrate a better way to do it, or at least link to one?

Thank you.


texts:
I want to ask that how to rotate body from corner?

movableBeam.getBeamBody().setTransform(movableBeam.getBeamBody().getPosition(), angle);

The above line of code rotate the beam from center that I want rotate from one of the conner. Any member please help me.

EDIT :

            float beamCenterX = movableBeam.getX() + movableBeam.getWidth()
                    / 2f;
            float beamCenterY = movableBeam.getY()
                    + movableBeam.getHeight() / 2f;

            float cornerOffsetX = movableBeam.getX() - beamCenterX;
            float cornerOffsetY = movableBeam.getY() - beamCenterY;

            float bodyAngle = (float) Math.atan2(cornerOffsetY,
                    cornerOffsetX);

            float newAngle = imageAngle + bodyAngle;
            float newCornerOffsetX = (float) Math.cos(Math
                    .toDegrees(newAngle));
            float newCornerOffsetY = (float) Math.sin(Math
                    .toDegrees(newAngle));

            cornerOffsetX = movableBeam.getX() - movableBeam.getWidth()
                    / 2f;
            cornerOffsetY = movableBeam.getY() - movableBeam.getHeight()
                    / 2f;

            Vector2 postion = new Vector2(
                    (newCornerOffsetX - cornerOffsetX + movableBeam.getX())
                            / PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT,
                    (newCornerOffsetY - cornerOffsetY + movableBeam.getY())
                            / PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT);

            movableBeam.getBeamBody().setTransform(postion, newAngle);


texts: How to make this generated terrain flat-shaded?

texts:
I'm generating a relatively low-poly terrain for my game using the code below:

for (int z = 0; z < VERTEX_COUNT; z++) {
    for (int x = 0; x < VERTEX_COUNT; x++) {
        final float posX = x / ((float) VERTEX_COUNT - 1) * SIZE;
        final float height = generateHeight(x, z);
        final float posY = height;
        final float posZ = z / ((float) VERTEX_COUNT - 1) * SIZE;
        final Vector3 nor = getNormals(x, z);
        final float norX = nor.x;
        final float norY = nor.y;
        final float norZ = nor.z;
        final float texU = x / ((float) VERTEX_COUNT - 1);
        final float texV = z / ((float) VERTEX_COUNT - 1);

        // Create vertex
    }
}

for (int z = 0; z < VERTEX_COUNT - 1; z++) {
    for (int x = 0; x < VERTEX_COUNT - 1; x++) {
        final int topLeft = (z * VERTEX_COUNT) + x;
        final int topRight = topLeft + 1;
        final int bottomLeft = ((z + 1) * VERTEX_COUNT) + x;
        final int bottomRight = bottomLeft + 1;

        //Triangle 1: topLeft - bottomLeft - topRight
        //Triangle 2: topRight - bottomLeft - mottomRight
    }
}

private Vector3 getNormals(final int x, final int z) {
    final float heightL = generateHeight(x - 1, z);
    final float heightR = generateHeight(x + 1, z);
    final float heightD = generateHeight(x, z - 1);
    final float heightU = generateHeight(x, z + 1);
    return new Vector3(heightL - heightR, 2f, heightD - heightU).nor();
}

This works perfectly fine and generates a smooth terrain mesh. The problem is I want this mesh to use flat shading; i.e. I don't want vertices to be shared between triangles. But I don't know how I would duplicate the vertices and find the appropriate indices to properly index the mesh. Any help?

Here's in image from google in case it wasn't clear (left shading is what I want, right is what I have):

P.S. I found this code for the Unity scripting language:

Vector3[] oldVerts = mesh.vertices;
int[] triangles = mesh.triangles;
Vector3[] vertices = new Vector3[triangles.Length];
for (int i = 0; i < triangles.Length; i++) {
    vertices[i] = oldVerts[triangles[i]];
    triangles[i] = i;
}
mesh.vertices = vertices;
mesh.triangles = triangles;

Perhaps this is the solution I'm looking for? If so, how can I translate this code to using float[] instead of Vector3[] array for my vertices? And what is the triangles array, the indices?


texts: Game loop architecture using WPF(MVVM) and C#

texts:
Could i get some suggestions on how to implement a game loop whilst using WPF(MVVM) and C#, I am a professional developer and understand the technology well.

The game loop usually contains a Init(), Render() and Update().

I know how to implement the Init() and Update(), but i would like ideas of how the render() fits in, using data binding the Render will happen on update(). Should forget the Render method or suppress the bindings and force them with a render?

Hope that makes sense :)


texts: I currently program a game in which the user don't need to interact with the screen. Is there any way to keep the screen awake?


texts: Odd exception when calling a method in DirectX 11

texts:
I am following the "3D game programming with directx 11" book (Frank Luna) and I am trying to render a cube. In the code there is this m_device->CreateBuffer() function which is giving me problems.
The exception I get is:

Device was 0XFFFFFFFFFFFFFFFF
DirectX11 exception in a method which is external to where the CreateDevice() method is called

So I tried to put it in the method where the device is created, and it gives no exception, so I'm wondering if I have to make the m_device something like global or I don't know.
struct Vertex {
        XMFLOAT3 Pos; XMFLOAT4 Color;
    };

 Vertex vertices[] = {
        { XMFLOAT3(-1.0f, -1.0f, -1.0f), XMFLOAT4((const float*)&Colors::White)},
        {XMFLOAT3(-1.0f, +1.0f, -1.0f),  XMFLOAT4((const float*)&Colors::Black)},
        {XMFLOAT3(+1.0f, +1.0f, -1.0f),  XMFLOAT4((const float*)&Colors::Red)},
        {XMFLOAT3(+1.0f, -1.0f, -1.0f),  XMFLOAT4((const float*)&Colors::Green)},
        {XMFLOAT3(-1.0f, -1.0f, +1.0f),  XMFLOAT4((const float*)&Colors::Blue)},
        {XMFLOAT3 (-1.0f, +1.0f, +1.0f), XMFLOAT4((const float*)&Colors::Yellow)},
        {XMFLOAT3 (+1.0f, +1.0f, +1.0f), XMFLOAT4((const float*)&Colors::Cyan)},
        {XMFLOAT3 (+1.0f, -1.0f, +1.0f), XMFLOAT4((const float*)&Colors::Magenta)}
    };
    D3D11_BUFFER_DESC vbd;
    vbd.Usage = D3D11_USAGE_IMMUTABLE;
    vbd.ByteWidth = sizeof(Vertex) * 8;
    vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    vbd.CPUAccessFlags = 0;
    vbd.MiscFlags = 0;
    vbd.StructureByteStride = 0;
    D3D11_SUBRESOURCE_DATA vinitData;
    vinitData.pSysMem = vertices;
    m_device->CreateBuffer(&vbd, &vinitData, &mBoxVB); //exception is here

I repeat the code perfectly works in the method where I called the CreateDevice() method, but doesn't here, in another method of another class.


texts: How do I go about implementing and using a custom vertex deceleration in monogame for windows phone 8. I want to be able to store a position, a colour and a normal?


texts: Vertices shaking with large camera position values

texts:
Basicly when i set the position of my camera (my character in game) to a high value, the geometries seems to be shaking, the higher the position value, the more they shake. On low position values you can't seem to notice any shaking.

I create a video to make it easyer to explain:
http://www.youtube.com/watch?v=dxg6wIl1U1Q

In the video i'm changing to chunkAmount from 100 -> 100000
this is a value i use in the following:

player.position.z = blocksize*((chunksamount/2)*blocksPerRow);
player.position.x = blocksize*((chunksamount/2)*blocksPerRow);

Which is something like 50'000 * 32 * 16 => position.x = 25600000


texts: How to pack the game files into one without using any file compressor?

texts:
Well, one example is this file of the game The Sims 2 for PS2: quickdat.arc.
The file contains this .arc extension, but it's no one an archive file and it contains some data of the game inside. How can I do this? Put so many files in one?

How to do something like this? All the game files inside one without using a file compressor?


texts: How to share image in persistentDataPath to facebook feed?

texts:
I'm trying to share an image taking from CaptureScreenshot() using FB.ShareLink(...) to Facebook.

My code is the following: (After calling FB.Init(), etc..)

 string tmpScreenshotPathname = "file:///" + currentScreenshotPathname;
 System.Uri contentUri = new System.UriBuilder(tmpScreenshotPathname).Uri;
 System.Uri imageUri = new System.UriBuilder(tmpScreenshotPathname).Uri;
 FB.ShareLink(contentUri, "Test", "Test desc", imageUri);

However,  when open the FB share, the page opens for a split second before returning me back to the game. I tried using a normal Uri such as http://........jpg and it works fine, but when I try to use a local Uri, it fails.

Is there any way to share the image to the feed without uploading it to the user's Facebook gallery using FB.API? Because there's the case where the user might decide not to share the image to the feed.. but it would have already been uploaded to his gallery from FB.API.


texts:
My game object isn't moving in correct speed calculated from deltaTime bellow. It should reach half of the screen in one second, on any device.

Devices:

tablet A7600-F - deltaTime = 0.03355443;  (res. 720x1280)
Xperia Z3 Compact - deltaTime = 0.13421772;  (res. 720x1280)

Calculation:

calc = (screenWidth / 2) * deltaTime. //I have app in landscape mode
speed = Math.round(calc);

speed on tablet - 21px per update;
speed on xperia - 86px per update;

You can see these results are very different (actualy it should be something about 8px - 20px). Game object is then extreme fast on Xperia (on tablet it's just a bit faster - speed is more than half of the screen per second).

What am I missing?


texts:
I've been trying for weeks to get AABB collision set up on my DX11 project.

So far, I have a 'condition' set up in place, so that when both cubes collide the 'light' cube will show within the scene. At this moment, the cubes pass through each other, which causes the light to show, but I can't figure out how to actually stop them from passing through each other. When cube1 hits cube2, they'll simply collide and won't be able to pass through each other.

This manages the user input

//Manage the users input via keyboard
class Vector3 {
public:
    float x;
    float y;
    float z;
};

class UserInput
{
public:
    float xPos;
    float yPos;
    float zPos;
    Vector3 vecMin;
    Vector3 vecMax;
    float rotationX;
    float rotationY;
    float rotationZ;
    bool isMoving;
    bool isMovingRight;
    bool isMovingLeft;
    bool isMovingUp;
    bool isMovingDown;
    bool isMovingCloser;
    bool isMovingFurther;
    bool isRotatingX;
    bool isRotatingY;
    bool isRotatingZ;
    UserInput()
    {
        rotationX = 0.0f;
        rotationY = 0.0f;
        rotationZ = 0.0f;
        isMovingRight = false;
        isMovingLeft = false;
        isMovingUp = false;
        isMovingDown = false;
        isMovingCloser = false;
        isMovingFurther = false;
        isRotatingX = false;
        isRotatingY = false;
        isRotatingZ = false;
    }

    void UpdatePos()
    {
        //-1 and +1 from the origin of the cube (centre)
        vecMin.x = xPos - 1.0f;
        vecMax.x = xPos + 1.0f;
        vecMin.y = yPos - 1.0f;
        vecMax.y = yPos + 1.0f;
        vecMin.z = zPos - 1.0f;
        vecMax.z = zPos + 1.0f;
    }
};

AABB Collision Function

bool AABBtoAABB(const UserInput& box1, const UserInput& box2)
{
    return!(box1.vecMin.x > box2.vecMax.x ||
        box1.vecMax.x < box2.vecMin.x ||
        box1.vecMax.y < box2.vecMin.y ||
        box1.vecMin.y > box2.vecMax.y ||
        box1.vecMin.z > box2.vecMax.z ||
        box1.vecMax.z < box2.vecMin.z);
}

Update Function

//Update each Frame
void Update()
{
    AABBtoAABB(input[0], input[1]);
    input[0].UpdatePos();
    input[1].UpdatePos();
}


texts: Animating Tile with Blitting taking up Memory

texts:
I am trying to animate a specific tile in my 2d Array, using blitting. The animation consists of three different 16x16 sprites in a tilesheet. Now that works perfect with the code below. BUT it's causing memory leakage. Every second the FlashPlayer is taking up +140 kb more in memory. What part of the following code could possibly cause the leak:

//The variable Rectangle finds where on the 2d array we should clear the pixels
//Fillrect follows up by setting alpha 0 at that spot before we copy in nxt Sprite
//Tiletype is a variable that holds what kind of tile the next tile in animation is
//(from tileSheet)
//drawTile() gets Sprite from tilesheet and copyPixels it into right position on canvas

        public function animateSprite():void{

                    tileGround.bitmapData.lock();

                    if(anmArray[0].tileType > 42){
                        anmArray[0].tileType = 40;
                        frameCount = 0;
                    }
                    var rect:Rectangle = new Rectangle(anmArray[0].xtile * ts, anmArray[0].ytile * ts, ts, ts);
                    tileGround.bitmapData.fillRect(rect, 0);

                    anmArray[0].tileType = 40 + frameCount;
                    drawTile(anmArray[0].tileType, anmArray[0].xtile, anmArray[0].ytile);

                    frameCount++;

                    tileGround.bitmapData.unlock();
                }

        public function drawTile(spriteType:int, xt:int, yt:int):void{

                    var tileSprite:Bitmap = getImageFromSheet(spriteType, ts);
                    var rec:Rectangle = new Rectangle(0, 0, ts, ts);
                    var pt:Point = new Point(xt * ts, yt * ts);
                    tileGround.bitmapData.copyPixels(tileSprite.bitmapData, rec, pt, null, null, true);

                }

                public function getImageFromSheet(spriteType:int, size:int):Bitmap{

                    var sheetColumns:int = tSheet.width/ts;
                    var col:int = spriteType % sheetColumns;
                    var row:int = Math.floor(spriteType/sheetColumns);
                    var rec:Rectangle = new Rectangle(col * ts, row * ts, size, size);
                    var pt:Point = new Point(0,0);

                    var correctTile:Bitmap = new Bitmap(new BitmapData(size, size, false, 0));
                    correctTile.bitmapData.copyPixels(tSheet, rec, pt, null, null, true);
                    return correctTile;

                }


texts: Is there a free type library kind of implementation available for XNA? I wish to use it on WP7, so it should be a managed code. I know can alternatively use spritefont, but I wish to know if other implementations exist for complex requirements.


texts: Unity: How to transition to a different animation during the blend phase?

texts:
I have a set of animations: Idle, start walking, stop walking, and walking full speed.

I have the animations all blending nicely...and the controls are fairly responsive during most of the motion...but there are odd transitions where the blends take away control--I can't transition to the walking animations when I am blending between the "stop walking" and "Idle" animations, for instance.

How do I get the animations to transfer during the blend phase??


texts: jBullet Collision/Physics not working as expected

texts:
Below is the code for one of my objects in the game I am creating (yes although this is a cube, I am not making anything remotely like MineCraft), and my issue is I while the cube will display and is does follow the physics if the cube falls, it does not interact with any other objects in the game.  If I was to have multiple cubes in screen at once they all just sit there, or shoot off in all directions never stopping.  Anyway, I am new to jBullet, and any help would be appreciated.

    // Constructor
public Cube(float pX, float pY, float pZ, float pSize)  {
    posX = pX;
    posY = pY;
    posZ = pZ;
    size = pSize;
    rotX = 0;
    rotY = 0;
    rotZ = 0;

    // physics stuff
    fallMotionState = new DefaultMotionState(new Transform(new Matrix4f(new Quat4f(0, 0, 0, 1), new Vector3f(posX, posY, posZ), 1)));
    fallRigidBodyCI = new RigidBodyConstructionInfo(mass, fallMotionState, fallShape, fallInertia);
    fallRigidBody = new RigidBody(fallRigidBodyCI);
}


texts: How to find points of a reflected 2d bezier curve about a line

texts: Pardon me if this sounds primitive. I have created a bezier curve with control points A, B, C, D, which are known (see image below). How can I find control points B1, C1, D1 for a new bezier curve reflected in AR1 and A2, B2 and C2 for a new bezier curve reflected in DR2?


texts: How to handle sounds muting in settings?

texts:
I have a easy and specific question.

Let's say that in my game I use singleton for playing/pausing/changing volume of specific sounds (SimpleAudioEngine in cocos2d-x).

What is the best way to handle mute button, which is displayed in the upper corner of the screen? Should I just volume everything down and do not care about checking the state of this setting before playing any kind of sound?

1) This is called when an object is destroyed

if (!UserDefault::getInstance()->getBoolForKey(MUTED, false))
{
    SimpleAudioEngine::getInstance()->playEffect("shouting.ogg", /* other arguments */)
}

I think that not playing a sound at all is bad practise (if muted is on - like in the above example), because when the user changes this setting while eg. his hero is getting shot, nothing will be played - even if it supposed to take 5 seconds and the option was changed after 2,5 seconds.

But if I only volume everything down - then the rest of the shout will be heard.


texts:
I understand that basic calculus is applicable to game development, particularly physics.  Problem is, I'm not entirely sure how.  So, what can I use it for?  I'm most concerned about what's on the AP tests, as I hear I won't need much more than that;

AP Calculus - AB

I'm particularly interested in hearing examples in terms of gameplay elements.


texts: Inverse Kinematics with obstacle avoidance for the manipulator (arm)

texts:
I have a basic understanding of inverse kinematics, in that there's a workspace and a configuration space, and the point is to find a solution in configuration space that satisfies a workspace goal. Multiple solutions may exist in configuration space for redundant manipulators.

That said, I'm currently struggling with a problem where the workspace is a plane with blocks (cubes) placed on it, and I need to plan a path for moving a block in the workspace while avoiding collisions with other blocks. Importantly, the arm (manipulator) moving the block must not collide with other blocks as well. The latter situation could be possible in case blocks are stacked to form a tower.

I recognize that planning a path for block to avoid other obstacles is a simpler problem that may be solved with A* and the likes. However, I'm interested in solutions that also account for obstacle avoidance for the manipulator. For my part, I have looked at the existing research (mainly robotics journals), where Rapidly Exploring Random Trees (RRTs) and their variations seem to be discussed a lot. Before I spend too much time learning and implementing those approaches, I'd like to confirm if I am on the right path, or are there any approximate solutions to this with low runtime cost that I should look at? Thanks.

Note: I've made some omissions from the question in order to keep it simple, but I'd be happy to answer any questions asking clarification.


texts: Another app has the same name as mine on the appstore!

texts: I am about to publish a game on the android playstore and the ios appstore. It is called "PairIt". I checked a while back to see if there were any other apps named PairIt on the playstore, and there were none. But I did not check on the appstore. Yesterday, when I tried publishing my app onto the appstore, it said the name was taken. After looking around on the appstore I saw someone else had an app named PairIt. So what I did was changed my app name to "PairIt!". Will this work? Could I get into any legal troubles for this?


texts:
I am building 3D solar system containing (sun > earth > moon).
I have difficult to add the part which the moon rotate around earth.
I separated between "moon" and other stars.
The problem is that the center of earth is not const like the sun.
I know that earth is in starsList[1] so I thought to translate the moon to this place but got weird result..
Someone have an idea how to do this?

mat4.identity(mvMatrix);
mat4.translate(mvMatrix, [0, 0, z]);

for (i = 0; i < starsList.length; i++) {
    mvPushMatrix();

    if (starsList[i].name == "moon"){
        /////////
        mat4.rotate(mvMatrix, degToRad(starsList[i].angle), [0, 1, 0]);
        mat4.translate(mvMatrix, starsList[1].initPlace);
        mat4.rotate(mvMatrix, degToRad(starsList[i].angle), [0, 1, 0]);
        ////////
   }
    else{
        mat4.rotate(mvMatrix, degToRad(starsList[i].angle), [0, 1, 0]);
        mat4.translate(mvMatrix, starsList[i].initPlace);
        mat4.rotate(mvMatrix, degToRad(starsList[i].angle), [0, 1, 0]);
    }
    mvPopMatrix();
}


texts: Android LibGDX game: Choosing starting activity

texts:
I am making a Android game with LibGDX (using ADT eclipse bundle). How do I choose the default activity to launch when the user opens the app. I set the project up with the LibGDX setup GUI, and I can't find the main activity.
I want a main menu to open before the game starts, is there something I should change in the manifest?
Thanks in advance.


texts: Issues using real names in a soccer player game

texts:
Is illegal to use the real player and team names in a game? When I say game could be and desktop, mobile or fantasy game.

If is illegal, is ok to change a little bit names? Instead of using Messi could I use Messsi (or something similar)?

All gambling and statistics soccer websites have permissions to use those names?

Thanks!


texts: How can I make background elements wrap around the screen?

texts:
I'm looking to make my clouds wrap around the screen in my game (like the picture).

Right now it just continues off the screen. The current movement code is:

Cloud.center = CGPointMake(Cloud.center.x +0.032, Cloud.center.y)


texts:
Is it possible to hide an environment texture as to preserve the reflections/light it provides while keeping the background transparent (as seen in picture 2)? I know this is done in Blender by removing light rays from the environment texture that directly hit the camera.
When I use the defaultEnvironment() and set scene.clearColor, this blue box is still showing up. (as seen in picture 1)
scene.createDefaultEnvironment();
scene.clearColor = new BABYLON.Color4(0,0,0,0)

Picture 1:

Picture 2:


texts:
I have experience with XNA and Unity3D. I have also built my own engine with Tao and C#. I am in last year of college and I want to make a small RTS game demo, nothing fancy I won't bother much with the art part. I will leave objects untextured, just drop some light.

It is a big decision, which one to choose XNA or Unity3D or maybe else? I definitely won't build my own engine since I will waste lot of time that way. I am looking for an engine/framework that will allow me to concentrate on higher level stuff like AI algorithms rather than do my own texture loading and stuff.

I will try to copy stuff from Starcraft2. My models and environment won't be textured though. I won't bother with sounds either, just some simple explosion and shooting sounds. The player will play against AI. I will go for the Starcraft2 mechanics/logic, not the skin. By skin I mean art stuff. At the end I would make small videos of gameplay showing the AI decision making process by printing text, so that a potential employee can see what is actually going on.


texts: Im creating a multiplayer asteroids type game for the Windows Phone 7, 2 players can challenge each other over who will get the highest score. On each players phone the opponent is displayed and both go about shooting asteroids and enemies. In an assignment I have due I would like to talk about the packet design, what would be the least amount of info that I can send over the connection? Instead of constantly having to send each players position, asteroid position, bullet position and enemy position etc. Or would all that data constantly need to be sent?


texts: How hard is it to build for other platforms using the Unreal Engine 3?

texts:
Quick question to those that have used the Unreal 3 Engine for development. (Not the UDK).

How much work would it take to take a game made on/for Windows and output a working build on another platform?

Is it as simple as "File -> Export -> PS3" (or similar) or is there much programming involved?


texts: Is sidescroller movement just offsetting the background?, MonoGame/XNA

texts: When I make a sidescroller game and what to move my character do I just offset the background, or is there another better way?


texts: timeScale=0 doesnt stop all prefabs in unity

texts:
As expected timeScale=0 can be used for stopping the game or pausing but when i make timeScale equal to 0 some prefabs still move and they can shoot bullets but addforce doesnt effect to bullets and they stop there. I know i can fix the problem on handling code of my prefabs but they are a lot. is there a good way to do the trick in my game?
thank you for helping


texts:
Ive just finished Alex Stv's Voxel tutorial on http://alexstv.com/index.php/category/voxel-tutorial, and realized it would be very handy to have a custom inspector for the TerrainGenerator variables, so that I could easily tweak and test how the world would change by using it.

The problem is, the class doesn't actually implement MonoBehaviour, as it's always used by other classes. I could extend the class to MonoBehaviour, and that would allow me to use the inspector, but since this class only really governs how the height map are going to effect the position and type of the voxels, not the creation of the world itself, it would make the inspector less useful.

I wanted to be able to have a button in the inspector to regenerate the world, check the changes in a quick and efficient way. How would I go about to have an inspector that would both allow me to regulate and change the variables in TerrainGenerator, and also allow me to regenerate and (maybe) change some world variables?

Would I need to have multiple inspectors--one to change the variables used in the simplex, and another, smaller one for the regenerative button?


texts: Can you show rng code running in real time in a game?

texts:
First off, I know almost nothing about game development/rng but I will learn. So apologies for sounding uninformed.
I want to make a sandbox ios game with several activities to do within, one of which is poker, but I want the poker to be infallibly transparent unlike online poker. They wouldn't dare.
So I want to show the rng code to be viewable by players as the hand plays out, so players will know its legit, and can verify after the hand etc if they have concerns, is this possible, can you "show" rng?


texts: Inclusive vs Exclusive voxel bounding box

texts: Let's say I have a few voxel at (1,1,1) and (2,2,2), I would like to know if would be better to consider that the smallest box that contains both voxels is either (1,1,1) to (2,2,2) or (1,1,1) to (3,3,3). That is to say is it more correct to make the box contains the lower point of the voxels or the voxels as cubes inside the box?


texts: How do I pause a single bone with spine?

texts:
I'm using spine along with SFML. I have a character that is always animated. When he shots, I set  an animation that affects only his arm. The arm goes up, but I need to stop this animation in the last frame while he keeps shooting.

I use this to make him walk

AnimationState_setAnimationByName(drawable->state, 0, "walk", true);

And this to make him shot

AnimationState_setAnimationByName(drawable->state, 1, "rshot", false);

I can't find a way in Spine c runtime to make this.

I could resolve this if I find a way to update manually tracks 0 and 1, instead of the full animation.


texts: Complicated How to create objects that fill a specific area?

texts:
How to create objects that fill a specific area? How to instantiate cubes within a random 2D form ... Trying not to leave the black lines.

@ JaamiParvez

Objetive:


texts:
Hello I’ve been working on a save/load system for my RPG inventory, and I was wondering whether there was a way to make the script use Serialization instead of PlayerPrefs, because I want the player to be able to access their save file. The main issue I run into with this code is how it mixes up the same variable in different itemHolders, causing duplication. Also, I heard that PlayerPrefs is better used for settings or preferences. Here’s my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

public class ItemInformation : MonoBehaviour
{
    // These are the assets for the item to change
    public Text nameText;
    public Text descriptionText;
    public Text regenText;
    public Text amountText;

    // This is the identifier for each item
    public string identifier;

    // These are the variables that change with the different items
    public string itemName;
    public string itemDescription;
    public float itemRegeneration;
    public int itemAmount;

    // Starts on awake
    void Awake()
    {
        // Function to change the object's information and such
        nameText.text = itemName;
        descriptionText.text = itemDescription;
        regenText.text = "HEALS " + itemRegeneration + "HP";

        // Loads game data
        LoadDataIfNeeded();
    }

    void Update()
    {
        amountText.text = "HAVE:" + itemAmount;
    }

    private void SaveData()
    {
        string jsonString = JsonUtility.ToJson(this);
        PlayerPrefs.SetString(identifier, jsonString);

        // Creates file to store variables
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Create(Application.persistentDataPath + "/InvData.dat");
        SaveData data = new SaveData();

        // Gets the player data
        data.itemSave = myItemAmount.itemAmount;

        // Writes player data to file and encrypts it
        bf.Serialize(file, data);
        file.Close();
    }

    public void LoadDataIfNeeded()
    {
        if (PlayerPrefs.HasKey(identifier))
        {
            string jsonInstance = PlayerPrefs.GetString(identifier);
            JsonUtility.FromJsonOverwrite(jsonInstance, this);

            // Extracts the data from the binary file and reads it
            BinaryFormatter bf = new BinaryFormatter();
            FileStream file = File.Open(Application.persistentDataPath + "/InvData.dat", FileMode.Open);
            SaveData data = (SaveData)bf.Deserialize(file);
            file.Close();
            myItemAmount.itemAmount = data.itemSave;
        }
        else
        {
            SaveData();
        }
    }
}

// Holds data that is to be saved
[Serializable]
class SaveData
{
    // Variables for save file
    public int itemSave;
}


texts:
Dabbling with basic MMO code because it intrigues me.

How does the server handle monsters / mobs?

I understand that generally on each game tick, the server loops through each player to send them updated positions of each other nearby player or mob.

So every player loop you're also looping through every other player but is it just standard to  loop through the entire mob list too? I mean there could be 1000+ mobs idling around the game world/zone. Would this just slow the loops down?

I thought maybe they keep a seperate list of ACTIVE mobs, ones that are either near a player or are chasing a player, but that would still require looping the idle ones to check if a moving player comes near one. Unless the aggro loop is less frequent (thinking out loud here)..

Is there some tricks or common workarounds involved? Or is that just how they work?