texts:
I currently am creating a script that allows the player character to attack by shooting orbs at foes.

I have the current code to do that (not final code, for testing purposes):

if(Input.GetButton("Fire1"))
    {
        print("firing");
        GameObject newOrb = (GameObject) Instantiate(MagicOrb, this.transform.position, Quaternion.identity);
        BasicAttackOrb orbControl = newOrb.GetComponent<BasicAttackOrb>();
        if (MoveHandler.facingRight)
            orbControl.SetDirection(BasicAttackOrb.RIGHT);
        else if (!MoveHandler.facingRight)
            orbControl.SetDirection(BasicAttackOrb.LEFT);

    }

So I create the new orb projectile, instantiate it, and then attempt to set the direction.

In the orb script:

public class BasicAttackOrb : MonoBehaviour
{
    public const int LEFT = -1;
    public const int RIGHT = 1;

    public float orbSpeed = 15.0f;

    public int direction;

    // Use this for initialization
    void Start ()
    {
        direction = 0;

    }

    // Update is called once per frame
    void Update ()
    {
        if (direction == LEFT)
            this.transform.Translate(-1.0f * orbSpeed * Time.deltaTime, 0.0f, 0.0f);
        else if (direction == RIGHT)
            this.transform.Translate(1.0f * orbSpeed * Time.deltaTime, 0.0f, 0.0f);

    }

    public void SetDirection(int dir)
    {
        direction = dir;
    }
}

So, if the direction is RIGHT (aka 1) it flies right. If it's LEFT (aka -1) it flies left.

However, the orb direction stays at 0, and is never set. This indicates to me that the initial code above in the Input.GetButton("Fire1") block is incorrect.

Am I accessing the GameObject incorrectly? I feel like it's just a slight coding error with objects but for the life of me I can't find it.


texts: Can I create realtime textures with text?

texts:
I have a large number of items in my game, that will eventually have a texture associated with them. The problem is, for right now, I have nothing. I would really like to do something with, say, the first 2 letters of the object's name. As my main system will be pure textures, I really don't want to add a text object to the texture, I would really like to just create a texture with the object's first two letters.

Is there a way I can create a texture, realtime, with font rendered on that texture? Preferably without a camera/ render texture, unless I can create them once. I really want to create a unique default texture for each item at runtime, preferably with some kind of font. Can I do this?


texts: How can I deal with actor translations and other "noise" in third-party motion capture data?

texts:
I'm working on a game, and I've run into a problem with motion capture data. My team is using 3DS Max 2011 and trying to put free motion capture files on our models.

The problem we're having is it has become extremely hard to find motion capture data that stays in place. We've found some great motion captures of things like walking and jumping but the actors themselves move within the data, so when we attach these animations to our models and bring them into XNA, the models walk forward even when they should technically be standing still (and then there's also the problem of them resetting at the end of the animation).

How can we clean up, at runtime or asset-processing time, the animation in these motion capture files?


texts:
I just started using Box2d and libgdx. I followed this tutorial, https://github.com/libgdx/libgdx/wiki/Box2d
And a ball would bounce if I run the following code I took from the tutorial.

// ...omit the rest of code
World world = new World(new Vector2(0, -10), true);
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyType.DynamicBody;
bodyDef.position.set(100, 300);
Body body = world.createBody(bodyDef);
CircleShape circle = new CircleShape();
circle.setRadius(6f);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = circle;
fixtureDef.density = 0.5f;
fixtureDef.friction = 0.4f;
fixtureDef.restitution = 0.6f; // Make it bounce a little bit
Fixture fixture = body.createFixture(fixtureDef);
circle.dispose();
// ...omit the rest of code

I'm wondering how I can make the ball bounce like a basketball or volleyball? It's like the ball movement is in a space, move so slowly. I changed some properties such as density or friction, but it seems box2d doesn't care of air friction, so nothing changed at all. Could you tell me how I can make the ball movement to be a basketball or such stuff?


texts:
Hi I am making a java game in were you can build land. At the moment you can build but not destroy. So I want to be able to destroy. I have an array of the tiles. I think I might need to do something like remove the tile that the mouse is hovering on form he arraylist so how can I do this? I don't think you need my code to explain to me because I only want to know how to remove the Tile that the mouse is hovering over. Please help me.

EDIT** MY array is a arraylist kind of arraylist and I have an arraylist for each block.


texts: Securing HTTP requests to online game server

texts:
I'm pretty new at making online games. Right now I'm trying to make an iPhone game. Each player has a profile in my server.

I want to avoid username/password for authentication. Currently, as it stands, when my game is installed it also generates an unique key string and safeguards it in the device. When the player runs the games and needs to perform an action, the action request is sent to the server - along with the key to validate the action.

This is done with an HTTP request, and is working fine.

The thing is, I'm not sure about the security implications behind this. Suppose that a seasoned cracker manages to discover their own key string (if it is stored somewhere in the device I imagine it is always possible to crack), and also identifies the HTTP request schema. They could technically create their own program, use the key string, and send requests to my server and effectively automate several tasks.

For example, let's say that you discover that your key string is 12345, and you also realize that the HTTP requests are like this

http://www.example.com/getcoins.php?key={KEY}

Well, now you're capable of making a nice program automating

http://www.example.com/getcoins.php?key=12345

So then I considered doing something like cookies. As if, the player authenticates using the key string and then the server returns some "session ID" which is stored in the device. The session ID must be used to validate actions. But I'd imagine this would cause the same issue: the cracker just discovers the session ID and off they go.


texts: How to design a class for an object that its state varies over time

texts:
I have a soccer team with 14 players (11 active + 3 substitutes). The team is going on a tour participating in different matches across the world. I have two very different design ideas of how for the classes for such match, and I am wondering if there is a better approach here. The language is Python and the database is Mongo.

My requirements:

At any time during a match, I want to know the current status of a player. (substitutes, active, injured) as well as their penalty cards if they got any. If they are actively playing, I want to know when they started. If they got back to sitting or got injured, I want to know their most recent start time and end time.
I want to be able to retrieve the information about a past match. For any player in a past match, I only need to know their latest status (as described above)

Here is my idea about db collections:

Players collection:
- Player ID
- Player Name
- Player Tshirt Size

Teams collection:
- Team ID
- Team Player IDs []
- Team Name
- Team logo

Matches collection:
- Match ID
- Team ID
- Match Location
- Match Time

Match Participants collection:
- Player ID
- Match ID
- Latest Status
- Latest Start Time
- Latest End Time
- Latest Penalty Card
- Latest Injury Note

As you see, I tried to separate the static information about a player (Players collection) from their dynamic information in a match (Players History collection) but I not sure how to define classes?

Class Player:
- Player ID
- Player Name
- Player Tshirt Size
- Latest Status
- Latest Start time
- Latest End time
- Latest Penalty Card
- Latest Injury Note

Class Match:
- Match ID
- Player IDs []
- Match Location
- Match Start time
- Match Tshirt color

The second option would be creating another class for the dynamic part to match to my db collection:

Class Player:
- Player ID
- Player Name
- Player Tshirt Size

Class Match:
- Match ID
- Player IDs []
- Match Location
- Match Start time
- Match Tshirt color

Class Match Participant:
- Player ID
- Match ID
- Latest Status
- Latest Start time
- Latest End time
- Latest Penalty Card
- Latest Injury Note

I do not know how I should decide which approach is better. I would appreciate if you help me figure out the approaches pros and cons or even just what criteria I need to think about when deciding between the two.

Is there any design patterns that would describe any of these approaches?


texts: Add translation at each animation cycle loop in Unity

texts:
I have a running animation. It already contains root animation. At every loop, it jumps to starting position.

What is the best way to add a translation every time the animation loops?


texts:
I've got an extensive world terrain that uses vec3 for the vertex position attribute. That's good, because the terrain has endless gradations due to the use of floating point. But I'm thinking about how to reduce the amount of data uploaded to the GPU. For my terrain, which uses discrete / grid-based vertex positions in x and z, it's pretty clear that I can replace my vec3s (floats, really) with shorts, halving the per-vertex position attribute cost from 12 bytes each to 6 bytes. Considering I've got little enough other vertex data, and an enormous amount of terrain data to push into the world, it's a major gain.

Currently in my code, one unit in GLSL shaders is equal to 1m in the world. I like that scale. If I move over to using shorts, though, I won't be able to use the same scale, as I would then have a very blocky world where every step in height is an entire metre.

So I see these potential solutions to scale the positional data correctly once it arrives at the vertex shader stage:

Use 10:1 scaling, i.e. 1 short unit = 1 decimetre in CPU-side code. Do a division by 10 in the vertex shader to scale incoming decimetre values back to metres. Arbirary (non-PoT) divisions tend to be slow, however.
Use (some-power-of-two):1 scaling (eg. 8:1), which enables the use of a  bitshift (eg. val >> 3) to do the division... not sure how performant this is in shaders, though. Not as intuitive to read values, but possibly quite a bit faster than div by a non-PoT value.
Use a texture as lookup table to convert the value from decimetres to metres. I've heard that this is really fast.

Or whatever solutions others can offer to achieve the same results -- minimal vertex data with sensible scaling.


texts: Any free 2D C\C++ framework that supports iPhone?

texts:
I'm looking for a C\C++ game dev framework that supports iPhone.
It should have least Objective-C requirement to use it.

The closest one I could find is Kanji engine.
But that's not free.

Other frameworks like cocos2d need to be code in obj-c.

So do you know any C\C++ game dev framework for iPhone?

Thanks


texts: How can I apply a glow filter in Phaser?

texts:
I'm trying to get the following effect, but as far as I know, a filter is the only sensible way.

Imagine some objects and background, and a fire ball passing through. The fireball glows. All objects (not the background) become brighter in color where they are under that glow. The glow effect could be described as a glow around a missile's fire.

This should be built-in to Phaser, as pixi.js has it.


texts:
I don't want to use XMVECTOR which i currently use in my DirectX 11 C++ game code.
Because it is too much for me in memory.
I want to use XMFLOAT3 or 4, but the problem is there is no matrix/vector XNA Math function available for XMFLOAT*. It is pointless to use 6 fields or pass to the shader (XMVECTOR), if object represents only 3 or 4 (and operate with them only).
I don't want to convert types in any case just to do calculations. Can you please recommend me what to do? I really like using XNA math, but XMVECTOR is just dirty variant...


texts: Blender Video Sequencer: I try to load 76 images, but length is 48 frames, can't change

texts: In Blender 2.8, I am trying to load a sequence of already-rendered images from a previous project I did (also in 2.8, but hey, these are just .png's) into the image sequencer. I set the frame rate in the render context menu from 24fps to 30fps, which seems to have no effect on the video sequencing window, because the markers for 1 second are stuck at 24 frames. Anyway, when I try to load all 77 frames of my animation into the VS as an image sequence, I get an animation that is only 48 frames long. I can scrub through the entire sequence, but the frame count does not match the number of images in the sequence--and I can't change it. I can't even stretch the animation out. What the heck? Can somebody explain how I can make this work properly?


texts: How do you make objects be pushed away from you?

texts:
like pain from naruto, I wanna be able to press a button and be able to push objects
here's my push method
 void DoPush()
    {
        Collider[] colliders = Physics.OverlapSphere(transform.position, pushRadius);

        foreach (Collider pushedObject in colliders)
        {
            if (pushedObject.CompareTag("Enemy"))
            {
                Rigidbody pushedBody = pushedObject.GetComponent<Rigidbody>();

                pushedBody.AddForce(-transform.forward * 500, ForceMode.Force);

            }
        }

    }

the problem with this method is when I go behind the objects I push, they go towards me


texts: Multithreading in Gamedevelopment, specifically Networking

texts:
Let me quick explain my actual setup:

I use 2 Threads, one for networking and one for the main-loop (input, update, render). I have two synchronized queues, one for mainthread->networking and one for networking->mainthread. When a chunk of bytes arrives, the network-thread decodes a paket. The network-code knows, what each paket is and what it does. It now creates a functor to change the coordinates of an entity, to spawn a new one, or something else. It emplaces this functor in the queue and the main-tread executes every tick all the functors in the queue.

This kinda works for now, but i think i have to change this completely. I might split up some parts of the main-thread, input for example, and stick it in another thread. Also, i might want to add support for plugins written in lua, python or some other language, and i don't want the main-thread to get stuck when the plugin decides to run a long-running task. This would mean, eventually the main thread has to handle a decent number of queues, one for every thread plus one extra for the other direction (thread->main). Also, at the moment, the networking needs to have all the pointers to the data-structures it wants to control (For example, it has a ptr to the entitymanager stored, so it can create a functor to spawn a new entity in the entitymanager), thats kinda weird.

Are there common techniques to synchronize threads better? Especially since i have to provide a lot more control over the gamestate and still need to synchronize the other threads with the main-thread, i don't really see a better approach other then the functor-queue, so i hope for some suggestions.


texts:
I've just started writing a 3D First Person Shooter in Java, and I'm having a bit of trouble with tracking the mouse movements and moving the camera accordingly. I'm implementing typical FPS movement, in that the mouse stays at the center of the screen.

Moving the mouse left and right (horizontal movement) is fine - each time the mouse is moved, I get it's position on the screen. I then use atan2 to get the angle I need to rotate around the y axis to get to this position, and apply the rotation accordingly.

My problem is when I try to change the pitch of the view (i.e. rotating around the x axis - essentially looking up and down). I can get the y coordinate of the mouse, and the y coordinate of the center of the screen, but how do I calculate how much I need to rotate around the x axis to get to that point?

Thanks in advance!


texts: Improving first person camera and implementing third person camera

texts:
I want to improve upon my first person camera implementation and extend it to, so the user can toggle between third person/first person view.

My current setup:
draw()::

glPushMatrix();
    m_pCamera->ApplyCameraTransform();

    // Render gameObjects
glPopMatrix();

Camera is strongly coupled to the player, so much so, that it is a friend of player. This is what the Camera::ApplyCameraTransform looks like:

glm::mat4 l_TransformationMatrix;
m_pPlayer->m_pTransformation->GetTransformation(l_TransformationMatrix, false);

l_TransformationMatrix = glm::core::function::matrix::inverse(l_TransformationMatrix);
glMultMatrixf(glm::value_ptr(l_TransformationMatrix));

So, I take the player's transformation matrix and invert it to yield First person camera view.
Since, Third person camera view is just a 'translated' first person view behind the player; what would be a good way to improve upon this (keeping in mind that I will be extending it to Third person camera as well.

Thanks


texts: How to implement a configurable spring force to SpringJoint2D like SpringJoint does?

texts:
I'm working in unity 5.3.4f1.

Looking at the SpringJoint2D class I can't seem to find a similar "spring force" as in spring in SpringJoint.

Is there any other way to make a spring stronger in SpringJoint2D?

If not, the only option I see is to inherit the Joint2D parent class and build my own spring joint 2D.


texts: Sending an object from one point to another

texts:
I am working on a simple game in Java and am stuck for now with getting an object to be directed from its current position to a certain point, all at a fixed speed. My problem is that whenever I activate the movement, the object seems to shoot off into a random direction, sometimes towards my target, sometimes away, really any direction it seems, but nothing consistent.

This is what I'm working with:

    else if (key == KeyEvent.VK_SPACE)
    {
        double deltaY = 100 - p.getY();
        double deltaX = 100 - p.getX();
        double angle = Math.atan2(deltaY, deltaX) * 180 / Math.PI;
        System.out.println(angle);
        double dx = (double) (Math.cos(angle) * 3);
        double dy = (double) (Math.sin(angle) * 3);
        p.setVelX(dx);
        p.setVelY(dy);
    }

Here is my SetVel functions as well as the tick method.

public void tick()
{
    x+=velX;
    y+=velY;

    if(x <= 0)
        x = 0;
    if(x >= 640)
        x = 640;
    if(y < 0)
        y = 0;
    if(y >= 480)
        y = 480;
}

public void setVelX(double velX)
{
    this.velX = velX;
}

public void setVelY(double velY)
{
    this.velY = velY;
}

Using the system outs, and positioning my object at 90 degree angles relative to my target I am getting 90 and 180 degrees, so I don't think its a problem with that.


texts: Using timer to reverse enemy movement in Flash game made with Flixel

texts:
I am creating a 2d flash game using Flixel 2.5 in Flash Builder. I am trying to reverse enemy movement on an interval so that they will move back and forth over a set space. I felt that a timer would be best for this situation. The enemy class extends FlxSprite.
I have three class level variables to help with managing the sprite's direction:

private var _movementTimer:Timer;
private var _movementTimerEvent:TimerEvent;
private var _forward:Boolean;
public var _directionSet:int = 0;

In the constructor, I instantiate the timer like this:

//create timer for movement
_movementTimer = new Timer(3000);
//set listener for movement
_movementTimer.addEventListener(TimerEvent.TIMER,SetDirection);
//start timer
_movementTimer.start();
//set initial direction
_forward = true;

The function called on the timer interval is as follows:

/*Reverse direction of this sprite*/
        public function SetDirection():void
        {
            _directionSet++; //increment direction set for debug purposes
            FlxG.log("direction set");
            FlxG.log(_directionSet);

            if(this._forward)
            {
                this._forward = false;
                //set the direction the sprite is facing
                this._facing = RIGHT;
            }
            else
            {
                this._forward = true;
                //set the direction the sprite is facing
                this._facing = LEFT;
            }

        }

Then, the update function evaluates the _forward flag to determine direction of movement:

/*Update this sprite*/
        override public function update():void
        {
            super.update();

            if(this._forward)
            {
                this.acceleration.x = this.maxVelocity.x * .5;
            }
            else
            {
                this.acceleration.x = -this.maxVelocity.x * .5;
            }
        }

However, my sprite is not reversing direction, it just continues forward. What am I missing?

EDIT:

I added additional variables and calls to FlxG.log for debugging purposes, and it seems that SetDirection is never called, but I am not sure why.


texts: Inconsistent CapsuleCast/Collision behavior when a GameObject is selected

texts:
My gameobject has a CapsuleCollider and I use CapsuleCast to check for horizontal collisions when moving horizontally so the gameobject won't pass thru obstacles.
It works 100% of the time except when I select the gameobject in Hierarchy.

When I have the gameobject selected, whenever I try to bump a wall continuously, it shakes/jitters until it eventually goes thru the wall. But this only happens when I have the object selected in Hierarchy. If I click on the scene so that the object is not selected and do the exact same thing (bump a wall continuously), there is no shaking/jitter and it doesn't pass thru the wall no matter how long I bump it.

This passing in the wall when selected is also consistent. Hundred percent of the time it will pass thru when I have it selected (and does the shaking) and also hundred percent of the time it doesn't if I don't have the object selected. Shouldn't selecting an object don't have any effect on this? Please give me some ideas of why.


texts: Pull OVRCameraRig over RTS map via touch controller grabbing gesture

texts:
Currently developing a little prototype RTS with the Oculus VR devkit.
I want to implement camera movement via "grabbing" onto the world space with a touch controller and move the OVRCameraRig object on the X- and Z-axes. For the prototype purpose, I rather decided to go with a simpler approach, namely just pull the map around, since it's not that big, and not much is happening on it.

So far I got this script:

public class MapMover : MonoBehaviour
{
    private bool movementEnabled;

    Transform map;
    Transform leftController;
    Vector3 offset;

    public bool IsMovementEnabled { get { return movementEnabled; } }

    private void Awake()
    {
        leftController = GameObject.Find("LeftHandAnchor").transform;
    }

    public void BeginMovement()
    {
        offset = transform.position - leftController.position;
        movementEnabled = true;
    }

    public void EndMovement()
    {
        movementEnabled = false;
    }

    private void LateUpdate()
    {
        if (movementEnabled)
        {
            transform.position = new Vector3(
                (leftController.position.x * 1.1f + offset.x),
                transform.position.y,
                (leftController.position.z * 1.1f + offset.z)
            );
        }
    }
}

BeginMovement() is called when I press the Hand Trigger on the left Touch controller. My current results are unproductive: The first BeginMovement() call is sufficient, but the movement of the map is very minimal, since the controller models are tiny and their position clamps around -1.0f and 1.0f. The second call of BeginMovement() makes the map do a jump to either side before going back to the minimal movement.

My question is, what exactly am I missing? Is there a simpler approach to this?


texts: OpenGL VAO buffer rebinding vs binding switching

texts:
I'm considering two different approaches to vertex buffer management in my OpenGL game engine. The first one seems to be pretty usual, but I haven't seen the second one being proposed or used anywhere.

Buffer rebinding

This is the more obvious approach I've seen before. The vertex buffers are bound to VAO on demand, before draw calls.

// VAO creation
// Some attribute setup here

// Constant buffer-attribute bindings
glVertexArrayAttribBinding( vao, 0, 0 );
glVertexArrayAttribBinding( vao, 1, 1 );
glVertexArrayAttribBinding( vao, 2, 2 );

Then, when drawing:

for ( const auto &mesh : scene )
{
    for ( int i = 0; i < mesh.buffer_count; i++ )
        glVertexArrayVertexBuffers( vao, 0, mesh.buffer_count, mesh.buffers, mesh.offsets, mesh.strides );
    // glDrawArrays()
}

Binding switching

In this approach, each mesh binds its vertex buffers to the VAO during initialization.

// VAO creation
// Some attribute setup here

// Each mesh binds its buffers to the VAO
// with glVertexArrayVertexBuffers()
int count = 0;
for ( auto &mesh : scene )
{
    glVertexArrayVertexBuffers( vao, count, mesh.buffer_count, mesh.buffers, mesh.offsets, mesh.strides );
    mesh.first_binding = count;
    count += mesh.buffer_count;
}

Then, when drawing, only attribute bindings are altered and no buffers are bound. There are, however, many more glVertexArrayAttribBinding() calls.

for ( const auto &mesh : scene )
{
    for ( int i = 0; i < mesh.buffer_count; i++ )
        glVertexArrayAttribBinding( vao, i, mesh.first_binding + i );
    // glDrawArrays()
}

I'd seem that only changing where buffers feed their data might be more efficient than replacing buffers each frame. Is it really though? What are other advantages and disadvantages? Which way should I choose?

Also, is there any limit of buffers bound to VAO? I couldn't find any relevant GL_MAX_* argument for glGet().

Thank you


texts: How do I calculate rotational impulses in rigid body collisions?

texts:
I'm writing a simple 2D physics engine to help me understand the inner workings of physics engines. I'm following Randy Gaul's tutorial which can be found here and It's been extremely useful and interesting. I'm now on the fourth and final article in the series which covers rotation, but I've spent weeks trying to figure it out and I've hit a brick wall. I've looked all over for other tutorials or explanations, but I have yet to find any that help. No matter how I impliment it, to the point of translating the source code of the tutorial to C# I seem to get completely counter intuative behavour.

The first cause of confusion is that the tutorial states that the collision resolution impulse for two bodies according to the tutorial is the first of the equations below, but the source code accompanying the tutorials appears to be using the second. These two don't appear to be equivalent to me, but I may be wrong.

I'm using the second equation in my code, as implemented in the example source code. I alter the angular velocity as follows:

angularVelocity += ColumnVector2.crossProduct(contactVector, impulse);

Assuming neither of these are the problem, then I must be doing something fundamentally wrong. Can anyone explain, or point me to a good explanation of how to calculate the angular components of my physics engine because I am completely stuck!

Thanks in advance (and sorry for the lengthy question),
Adam


texts: Correct way to export from blender to ogre format?

texts:
When I export from blender to ogre using the blender2ogre add-on, I'm not getting anything besides a scene most of the time and when I get a mesh I never get a material. Is there something wrong with my export procedure or what else could I be doing wrong?

Update

I can export the basic cube from blender to ogre but when I download a model and try to export it I don't get the meshes.

Update 2

I tried again and selecting the model in Blender does the difference like the answer here says. I can export an alien and get the mesh and material:

I rename the files:

$ ls workspace/DungeonWorld2/assets/objects/creatures/alien/
Cube.001.mesh          Material.002.material  Material.005.material
Cube.001.mesh.xml      Material.003.material
Cube.001.skeleton.xml  Material.004.material
dev@dev-OptiPlex-745:~$ ls workspace/DungeonWorld2/assets/objects/creatures/alien/
alien.mesh          Material.002.material  Material.005.material
alien.mesh.xml      Material.003.material
alien.skeleton.xml  Material.004.material
dev@dev-OptiPlex-745:~$

But how do I actually load the material since the alien now turns up in the game with no material but it does render the mesh:

    Spatial model3 = assetManager
            .loadModel("objects/creatures/alien/alien.mesh.xml");
    model3.scale(0.3f, 0.3f, 0.3f);
    model3.setLocalTranslation(-40.0f, 3.5f, -20.0f);
    rootNode.attachChild(model3);


texts: Keep state in Unity editor without hitting serialization

texts:
In my game I have a MonoBehaviour WorldView that, when created at editor time, initializes a large dictionary. Later from a Editor WorldViewEditor I call WorldView.SetBlock() that tries to access this dictionary, but finds it empty.

If I understand correctly this is because my editor doesn't access the same WorldView instance, but rather a copy it received through serializing and de-serializing my original instance.
Pushing this dictionary through the serializing process is a performance nightmare and not supported by Unity out of the box.

This dictionary should never be shown in any editor, is private to the instance and initialization will be called every time the scene is loaded.
This sounds like a perfect case for keeping it somewhere outside the serialization process.

I could try to leverage ISerializationCallbackReceiver but this still requires me to pull the entire dictionary through some serialization process.
I'm looking into keeping everything state related in a separate library outside of unity, but this has it own downsides.

Is there a way to put this dictionary in a place where its state is kept?


texts: I can't seem to find any OpenGL headers for the RTX ray tracing extension, seems like they only want you to use Vulkan and optix with RTX


texts:
I am developing a SaveManager system for my games. Basicly what it should do is;

1) Gets the "ANY" user created Serializable class by Drag&Drop to inspector. (save data).

2) Writes that class to a file using either BinaryFormatter or XMLSerializer.

I want to be able to use it in my future games. So it should be save data class(type) independant (like serializers). I will use it like an asset, import the SaveManager, give serialized class as parameter, and let it do the rest. But as i said, it should be able to use any user created serialized class.

So the problem is, since that "serialized class" will be written by the user in the "game project" (not in the SaveManager project), and i don't have that "serialized" class type in my SaveManager project, i don't know how to make the SaveManager, reference the class from inspector.

So lets say i create this class in the game project (not in the SaveManager project)

[System.Serializable]
public class SaveData
{
    public string Name = "Name";
    public int Number = 5;
}

Now when i import the SaveManager project (asset) into my "game" project, i should be able to drag and drop the script to the SaveManager inspector and let it do the rest. Since BinaryFormatter works for every Serializable type, the name of the type is actually doesn't matter. I mean BinaryFormatter is type free as long as the type is serializable. I want to use that feature, and make the SaveManager type free too.

So in future if i want to use, say "MyNewSaveData" serialized class, "in an another game", i want to be able to drag and drop this to SaveManager inspector and let it do the rest.

Now the thing is, if i use

public object _SaveData;

in SaveManager script, unity inspector doesn't show it.

if i use

public Object _SaveData

it casts the user created type to an Object, and i lose the type i need.

I tried to use System.Type, but unity doesn't show it too.

Basicly what i want to do is, get "any" serialized class as reference. Like

public SerializedClass _SaveData;

or something like

public Script _SaveData;

That reference should accept "any" serialized class. Gets it's type, then casts it to that type.

When i use

public Object _SaveData

if i use _SaveData.GetType(), i get the type the "user created".
I have the type, in my hands, but i can't cast Object to that type. I don't know how to use that type for casting.

What ever i do, it either doesn't show up in inspector, or it casted to another type and i lose the data.

What should i do?


texts:
I'm developing an android game, and my screen is not displaying what I want it to. I've read various tutorials but they are either outdated or hard to follow. I have followed this tutorial and most of the code is identical. However, when running the game, the screen is black.

Game logic loop:

public void run(){
    while(running){
        long beforeTime = System.nanoTime();
        gameEngine.update();
        Canvas c = null;
        try{
            c = holder.lockCanvas(null);
            //synchronized (holder){
                c.drawRect(0,0,c.getWidth(),c.getHeight(),blackPaint);
                gameEngine.draw(c);
            //}
        }finally{
            if(c!=null){
                holder.unlockCanvasAndPost(c);
            }
        }

        this.sleepTime = delay-((System.nanoTime()-beforeTime)/1000000L);
        try{
            if(sleepTime>0){
                this.sleep(sleepTime);
            }
        }catch(InterruptedException e){
            Logger.getLogger(GameThread.class.getName()).log(Level.SEVERE,null,e);
        }
    }
}

Main activity:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                         WindowManager.LayoutParams.FLAG_FULLSCREEN);
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    setContentView(R.layout.activity_main);
}

engine.draw(Canvas c):

public void draw(Canvas canvas){
    Paint bluepaint = new Paint(Color.BLUE);
    canvas.drawRect(50,50,100,100, bluepaint);
}

EDIT:

@wondra I did test the break point, and the thread does actually get started, or so I think. The app runs and there are no errors thrown to the log console. Someone also suggested it was the emulator not running properly.

@fadden I have implemented what you suggested, still nothing... does starting the view from the xml and not from the Java have to do anything to do with it? Does the instance still exists if I don't declare it in Java?


texts: Why baked light differ so much from realtime light?

texts:
I'm trying to figure why Baked light differ so much from realtime lightning (whose final result I like and prefer!)

Left one: baked light, right one: realtime.

I've placed a:

Directional light
3 spot light
1 Reflection probe

There is also post processing beahviour with bloom enabled.

Follow my light settings:

I can't enable Realtime GI because is a webGl application.


texts: Unity Script and game not syncing after player respawn

texts:
I have a health system for my player that looks like this:

public int fallBoundary = -10;
public int Health;
public int numOfHearts;

public Image[] hearts;
public Sprite fullHeart;
public Sprite emptyHeart;

void Update() {
    if(Health > numOfHearts) //Health script works, why does heart display not?
    {
        Health = numOfHearts;
    }

    for (int i = 0; i < hearts.Length; i++) {
        if (i < Health) {
            hearts[i].sprite = fullHeart;
        } else {
            hearts[i].sprite = emptyHeart;
        }

        if (i < numOfHearts) {
            hearts[i].enabled = true;
        } else {
            hearts[i].enabled = false;
        }
    }
}

Unfortunately, after respawn, the hearts do not sync anymore. My debugging showed, that the elements of hearts still did their job, resetted and got replaced correctly. However, in my game, nothing changes after the respawn (should reset to full health and change if player gets damaged). For the respawn, I am loading my prefab, which I also checked (everything is there). To avoid confusion: my hearts never reset to 0, but stay at 1.

Player Prefab that loads during respawn

Hearts after respawn


texts: Convert the animation inside FBX into Unity

texts:
Recently i bought a package with an fbx and lots of animations.

Since I want full control and change a couple of details, I want to convert them into the regular Unities Animation System.
I cant convert them into the normal Unity Animations though.
They are "read only".

I can load them, copy paste them into my own "not-read-only" animation file.
But somehow i cant change the file anymore after I pasted something inside.

What am I doing wrong?
Is that something "impossible"?
Can you guys help?


texts: How to handle Tilled Map z index order with player in libgdx?

texts: The below 1st image is the example how I render tiled map with player, I can properly change the player z index, If I want to make the player below the box i just set the z index to 0. But the problem is the 2nd image below, I dont know how do I make the player above the box when the player is in the bottom then when in the top the player index should be less than the box.


texts: How are semitransparent polygons rendered in the correct order?

texts:
It is my understanding that while opaque triangles can be rendered in any order thanks to the Z buffer (especially when rendering in hardware), semitransparent triangles cannot. Instead, they need to be rendered from furthest to closest (from the camera's point of view) in order to get the correct result. If you render them in the wrong order, the result will be incorrect (and may even suddenly visually change if the rendering order changes as the camera moves).

Sorting polygons, even triangles, from furthest to closest is actually a difficult problem. In fact, in the general case it's an impossible problem (even with triangles) because in some pathological cases there is no unambiguous order in which they can be rendered correctly. For example, three triangles may overlap each other in a cyclic manner so that each one is partially in front of another (and thus it's impossible to render them without error, unless they are opaque and using a Z buffer, or without splitting at least one of the triangles). Using a naive sorting of triangles is very inefficient, especially if the need arises to split a triangle due to a cyclicity problem.

I know that there exist clever data containers that solve this exact problem and allow very quickly traversing the triangles from furthest to closest, regardless of where the camera is located, without the need to sort anything, and with any splitting of triangles already having been done in preprocessing. One example of such a data container (which name I can't remember now) is a binary tree where there's a triangle at each node which splits the entire space into two halves, with the rest of the triangles being on the left or right branches depending on which side of the plane defined by this triangle they are (and if a triangle intersects said plane, it's split in preprocessing into two using that plane). This binary tree allows traversing all the triangles from furthest to closest with a simple dot product (against the normal vector of the triangle) comparison at each node, regardless of where the camera is located.

While this construct is very clever, there's one problem with it: It only works with a completely static scene. The tree has to be precalculated (and triangles possibly split) as a preprocessing step (usually while building the project). Doing it at runtime on each frame would be madness.

But games use dynamic semi-transparent polygons all the time, for all kinds of particle effects etc. So how are they rendered properly?


texts: How to test ad mediation in cocos creator?

texts: I made a game in cocos creator and added Admob as my primary ad network and Ad Colony as secondary. But I am not sure how can I test if it's working? Can I just disable adMob ads (test ads) and see if the game still showing ads with AdColony (test ads)?


texts: How slow is generating a new Vertex Buffer?

texts:
I am currently working on a project that does 2D sprite-like graphics on Windows 8 (Metro-style app). For that purpose I am using Direct3D with quads to act as sprites.

My problem is that it get's very slow (30fps at 100 sprites) and profiling led me to believe that the bottleneck is withing the CreateBuffer call. How can I solve that problem in an elegant way? Wouldn't gathering copying vertex data from all elements that share the same texture in a single, bigger, buffer be more cost-prohibitive, as it is all done on the CPU?


texts: I want to use PlayFab to host and manage my server instances but I'm unclear on how to implement the requirements they listed here. My server SDK is in .Net and I'm hoping I can fulfill all the requirements with plugins written in C#. How can I and make parameters available in the command line input? Am I supposed to return information by printing on the console?


texts:
I am making a game using libGDX and Tween Universal Engine.
My problem is as follows:
I have 2 screens so fars, a splash screen with the logo, and a second one which is the main menu.
In the splash screen I use a SpriteBatch and a Sprite with the Texture of the image I want (which goes through some scaling.)
Now I use the Tween engine, along with a created SpriteAccessor to control the alpha of the sprite. I fade the picture in, then fade it out, then change it to the next screen.
In the next screen I have a single sprite, and a single, 3 slot, sprite array. In this screen I also use the tween engine, I fade the single sprite into the screen (it's the background image) then I try to, using the same method, (Tween.to) to change the alpah of the sprite array (each sprite by itself.),  I first set it to 0 using Tween.set, then using the method I change it.
This didn't work, after some tests I tried setting the alpha of a single sprite from the array to 0, and that didn't work.
It's like the program is ignoring the alpha value, I even printed out the alpha value, it saying 0, but the sprite is visible.
How can I fix this, or why might it be caused?


texts:
I render ~17.000 VAOs each frame. 2.840.386 triangles. Only applying texture, nothing else.

I have three computers and the performance across them is not as expected.

Cheap laptop(i3-4010U & Intel HD 4400) runs at ~20 fps.
Desktop1(FX-9590 & GT 630) runs at ~65 fps.
Desktop2(i7-5820k & GTX 970) runs at ~105 fps.

As the game is in a pretty early stage, the only CPU task each frame is to loop through a 3-Dimensional map containing VAO ids, and then render them.

When I look at the CPU Benchmarks and the GPU Benchmarks of my systems, I would expect a much bigger difference between my Desktop2 and the two other systems. The GTX 970's 3D score(8662) is more than 15 times better than the Intel HD 4400's (546), though it only run 5 times as fast. Even more ridiculous the GTX 970's 3D score is ~11 times better than the GT 630's (797), but run 1.6 times faster.

Even without taking the benchmarks into consideration I would still expect bigger difference. When I compare the performance differences in other games(Like GTA V) across my systems, there's a much bigger difference. Therefore I know the problem is my game, and not a hardware/driver related issue.

Am I right that I would expect larger differences between the different systems, if yes: How may I find the issue and how can I solve it?

Edit: I've read that GTX 590 is capable of 3.2 Billion triangles/second, where as my game is only able to squeeze ~300 million of a GTX 970.

Edit 2: I've tested my desktop1(GT 630) that runs 1080p at 65fps and if I change the resolution to 1 * 1, I only get a performance boost of 20fps(85fps).


texts:
I want to make Unity play a squish animation when the player hits the ground, but only once, until the player jumps and hits the ground again, although Unity its constantly detecting that the player is on the ground and keeps playing the squish animation over and over again, only jumping stops it cause the condition to play the animation is if the player is on the ground. (loop already disabled)
How I can possibly solve this?

 if (isGrounded == true)
        anim.SetTrigger("EnterGround");


texts: Dropping through a platform in Clickteam Fusion 2.5

texts:
I am using Clickteam Multimedia Fusion 2.5. Currently, I have a rudimentary platformer game, with the following setup:

player object is set as a physics platform, with the physics engine added to make it all work
the floor is a quick backdrop, with the obstacle type of obstacle
the only platform in the game is also a quick backdrop, with the obstacle type of platform

The way the game is setup, the player object can jump through the platform.

WHAT I WOULD LIKE TO DO

Is there a default, built-in way for the player object to be able to drop down through the platform? To be more specific, is there a default key press or a default combination of keys which would allow the player object to drop down through the platform?

I guess I could add it all in via the Event Editor, but I was wondering if there's a built-in way which handles it all.


texts: Unet spawning my 2 players in same location

texts: I have min and max number of players set to 2. I have 2 empty game objects in my scene with Network Start Position scripts attached. I have "Round Robin" as the player spawn method in my Network Manager. And yet my players often spawn on top of each other. Any ideas why? Thanks in advance


texts: Can't Use Hammer Editor Grid or 3d Camera

texts:
I can't place anything (tried Shift + R) and it shows two white lines making a right angle when I open a map. I can't edit my maps currently. Can anyone help? An alternative to editing maps?

Only ray-traced works for 3D:


texts: opengl z index changing does not zoom in

texts:
I am making a simple opengl application where I have a cube and I want to move forward to it with the glTranslate3d function, where I change the z index. One would expect the object to get bigger because of the view but it does not

My code:

    glClearColor(0, 0, 0, 1);
    glClearDepth(1.0);
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LEQUAL);
    glViewport(0, 0, width, height);
    glMatrixMode(GL_PROJECTION);
    glOrtho(30, width, 0, height, 100, -100);
    glMatrixMode(GL_MODELVIEW);

I have tried many things also I have been told that gluPerspective is out dated and should not be used....

EDIT: it works when I rotate the object you can see how 3d it is :p


texts: VBOs no longer renger when gluPerspective applied

texts:
I've written a basic program so I can make sure I'm properly learning VBOs before converting my 3d game's rendering to them.

Essentially, this question is why changing the perspective is the GL setup code stops my triangle from rendering:

GLU.gluPerspective(60f, (width/height), 0.1f, 200.0f);

Wihout that code, the triangle renders as expected. With it, only an empty screen is visible. I tried changing the triangle vertices but nothing worked. This may help explain why the VBO rendering isn't working in my game.

I've spent more time reading about gluPerspective but I'm not catching why it prevents the images from rendering.

My display/gl init code:

// Init display
Display.setResizable(true);
Display.setTitle( Game.name );
Display.setVSyncEnabled(true);
Display.setDisplayMode(new DisplayMode(Game.GAME_WIDTH, Game.GAME_HEIGHT));

// Set viewport
PixelFormat pixelFormat = new PixelFormat();
ContextAttribs contextAtrributes = new ContextAttribs(3, 0);
Display.create(pixelFormat, contextAtrributes);
glViewport(0, 0, Display.getDisplayMode().getWidth(), Display.getDisplayMode().getHeight());

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

glViewport(0, 0, Display.getWidth(), Display.getHeight());
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

GLU.gluPerspective(60f, ((float) Display.getWidth() / (float) Display.getHeight()), 0.1f, 200.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

I have a simple triangle drawing class that uses and interleaved VBO

triangleTesselator.addVertex(-0.5f, -0.5f, 0f);
triangleTesselator.addColor(1, 0, 0);

triangleTesselator.addVertex(+0.5f, -0.5f, 0f);
triangleTesselator.addColor(0, 1, 0);

triangleTesselator.addVertex(+0.5f, +0.5f, 0f);
triangleTesselator.addColor(0, 0, 1);

triangleTesselator.render();

I also tried several different vertex coords thinking the 0 was behind the clipping (near) plane of the perspective but that didn't work.

Update: I've added a basic camera system to this rendering test app, and after looking around a bit I've found the rendered cube behind me...


texts:
My game uses a lot of images, for the over-world, battle screens, chats, etc. I'm really meticulous when it comes to memory management, and I've noticed that even though I dispose every image when I load in a new one, the memory never goes down.

Isn't this what Dispose() should do or is my understanding wrong?


texts: Using AdMob with Games that use Open GLES

texts:
Can anyone help me integrating Admob to my game. I've used the badlogic framework by MarioZencher ... and My game is like the SuperJumper. I am unable to use AdMob after a lot of my attempts. I am new to android dev...please help me..I went thru a number of tutorials but not getting adds displayed ...

I did the following...

get the libraries and placed them properly
My main.xml looks like this

android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>

My Activity class onCreate method:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

RelativeLayout layout = new RelativeLayout(this);
adView = new AdView(this, AdSize.BANNER, "a1518637fe542a2");
AdRequest request = new AdRequest();
request.addTestDevice(AdRequest.TEST_EMULATOR);
request.addTestDevice("D77E32324019F80A2CECEAAAAAAAAA");
adView.loadAd(request);
      layout.addView(glView);
      RelativeLayout.LayoutParams adParams =
              new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                              RelativeLayout.LayoutParams.WRAP_CONTENT);
      adParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
      adParams.addRule(RelativeLayout.CENTER_IN_PARENT);
      layout.addView(adView, adParams);
      setContentView(layout);

requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                     WindowManager.LayoutParams.FLAG_FULLSCREEN);
glView = new GLSurfaceView(this);
glView.setRenderer(this);
//setContentView(glView);

glGraphics = new GLGraphics(glView);
fileIO = new AndroidFileIO(getAssets());
audio = new AndroidAudio(this);
input = new AndroidInput(this, glView, 1, 1);
PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "GLGame");

}
My Manifest file looks like this ....

    <activity android:name="com.google.ads.AdActivity"
      android:configChanges="keyboard|keyboardHidden|orientation|smallestScreenSize"/>

</application>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-sdk android:minSdkVersion="7" />

When I first decided to use the XML for admob purpose ..it showed no changes..it even didn't log the device id in Logcat...

Later when I wrote code in the Main Activity class.. and run ...
Application crashed ... with 7 errors evry time ...

The android:configChanges value of the com.google.ads.AdActivity must include screenLayout.

The android:configChanges value of the com.google.ads.AdActivity must include uiMode.

The android:configChanges value of the com.google.ads.AdActivity must include screenSize.

The android:configChanges value of the com.google.ads.AdActivity must include smallestScreenSize.

You must have AdActivity declared in AndroidManifest.xml with configChanges.

You must have INTERNET and ACCESS_NETWORK_STATE permissions in AndroidManifest.xml.

Please help me by telling what wrong is there with the code?
Can I write code only in xml files without changing the Activity class ...
I will be very grateful to anyone providing support.


texts: Vibration duration for mobile devices in Unity

texts:
I'm used the
Handheld.Vibrate() method. I know that if you call it several times, you can increase the vibration time, but when it is called once, the vibration lasts about 1 second. But I would like to make an imitation of clicking on the android keyboard. (Vibration ~ 0.2s)

How to set the duration of the vibration?


texts: Prevent camera from moving through walls (no engine or framework)

texts:
I'm building a fairly basic 3D first-person puzzle game. The only objects for which collisions matter are walls, and all walls are at convenient 90 degree angles aligned with the coordinate axes.

Unfortunately, I cannot consistently prevent the camera from moving through walls. There is no off-the-shelf game engine or framework involved, so I have to implement all this from scratch.

Currently, my algorithm (in GLSL-ish psuedo code) looks something like this:

void update_position(seconds){
    vec3 ray = Raycast(position, speed, map.grid);
    float xmax = max(ray.x-.01,0);
    float ymax = max(ray.y-.01,0);
    float zmax = max(ray.z-.01,0);

    float dx = speed.x * seconds;
    float dy = speed.y * seconds;
    float dz = speed.z * seconds;

    if(abs(dx) > xmax){
        dx = (dx > 0 ? xmax : -xmax);
        speed.x = 0;
    }
    if(abs(dy) > ymax){
        dy = (dy > 0 ? ymax : -ymax);
        speed.y = 0;
    }
    if(abs(dz) > zmax){
        dz = (dz > 0 ? zmax : -zmax);
        speed.z = 0;
    }

    position.x += dx;
    position.y += dy;
    position.z += dz;
}

In prose: I cast a ray from the player's/camera's current position along the speed vector, which extends until it hits wall. (The Raycast function is used elsewhere, so I already know it works correctly.) I then define the maximum distance the player is permitted to move in each dimension to be slightly less than the component of the ray in that dimension (so that we never end up exactly on a wall). I then compute a provisional set of deltas to add to the current position based on the speed and the time since the last frame (in fractional seconds), and check to see if any of them exceed the maximum allowed magnitude which would take the player through the wall. If they do, I clamp the magnitude of the offending component to its max value, and set the component of speed in that direction to 0; so, the player should end up just barely outside the wall, and sliding along it.

This usually works pretty well if you happen to run straight into a wall, but it fails frequently but unpredictably (as in, sometimes it doesn't fail) near corners, and especially near three-way corners (where two walls and a ceiling or floor come together).

So, what is wrong with this algorithm, and how do I fix it?


texts: Why is my Slick2D spritesheet animation cut off when it loops?

texts:
I am loading a SpriteSheet with Slick2D and using the Animation function in the render method to display it.
The spritesheet loads perfectly, but when the animation loops, it does so moved down a few pixels and cut in half.

It should always look like this:

But instead does this:

Here's my code. It's smalle because it's only a test.

package finalProject;

import org.newdawn.slick.*;
import org.newdawn.slick.state.*;

public class Dialogue extends BasicGameState {

    private SpriteSheet SSTommy;
    private Animation ATommy;
    Music playMusic;

    public void enter(GameContainer gc, StateBasedGame sbg) throws SlickException {
        playMusic = new Music("C:/OOP Resources/Bill Blaster.ogg");
        playMusic.play();
        playMusic.loop();
    }

    public Dialogue(int state) {
    }

    public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
        SSTommy = new SpriteSheet("C:/Users/Usuario/Documents/Etc/Tommy_SS.png", 41, 87);
        ATommy = new Animation(SSTommy, 150);
        ATommy.setPingPong(true);
    }

    public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
        g.drawString("This is the Play State", 100, 100);
        ATommy.draw(200, 200);
    }

    public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
        ATommy.update(delta);
    }

    public void leave(GameContainer gc, StateBasedGame sbg) {
        playMusic.stop();
    }

    public int getID() {
        return 1;
    }
}

I tried other SpriteSheets but it keeps doing the same. I think this is releated to the render method, but I don't know what's doing it.


texts: which quarter of a triangle the point is in

texts:
I've got a world made out of squares. The square are devided in four triangles like this:

The corners have their heights stored in a 2D array and the center height is the average of the corners. To calculate the players Y-coordinate I have to know in which triangle he is standing on. How can you calculate in which quarter the player is by the X and Y coordinates?

EDIT:

My algorithm:

bool h1 = false, h2 = false;

if(posZ < posX - posZ) //something weird going on here
{
    h1 = true;
}
if(posX < posZ - posX) // and here
{
    h2 = true;
}
if(h1 && h2)
{
    triangle = 0;
}
if(h1 && !h2)
{
    triangle = 1;
}
if(!h1 && !h2)
{
    triangle = 2;
}
if(!h1 && h2)
{
    triangle = 3;
}

This algorithm tries to find in which triangle you are. There is something wrong in that math.


texts: When does the memory transfer from CPU to GPU happen when creating a buffer?

texts:
I just finished my first DirectX 11 program. But I have several questions on memory transfer between CPU and GPU.

In my program, I create a vertex buffer first:

bool InitializeGeometry() {
    VertexType vertices[] = {
        XMFLOAT3(0.0f, 0.0f, 0.5f),
        XMFLOAT3(0.5f, 0.0f, 0.5f),
        XMFLOAT3(0.0f, 0.5f, 0.5f)
    };

    D3D11_BUFFER_DESC vbDesc;
    ZeroMemory(&vbDesc, sizeof(vbDesc));
    vbDesc.Usage = D3D11_USAGE_IMMUTABLE;
    vbDesc.ByteWidth = sizeof(vertices);
    vbDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    vbDesc.CPUAccessFlags = 0;

    D3D11_SUBRESOURCE_DATA vbData;
    ZeroMemory(&vbData, sizeof(vbData));
    vbData.pSysMem = vertices;

    if (FAILED(gDevice->CreateBuffer(&vbDesc, &vbData, &gVB)))
        return false;

    // ...
}

Later I will use this vertex buffer for rendering.
Note that the vertices array is a stack variable and it will be destroyed on after the return of InitializeGeometry.

Does actual memory transfer from CPU to GPU happen in CreateBuffer?
Or CreateBuffer just takes a reference to the vertices so I should give a longer lifetime to the vertices?

If the transfer does starts in CreateBuffer(or Unmap for dynamic buffers),
can I expect the GPU driver save a copy of my vertices?
I am afraid that the transfer takes so much time that InitializeGeometry function returns early, hence leaves transferring data incomplete.


texts:
I'm building a simple game engine (or mostly rendering engine) and I would like to separate the "engine" part from the "game" part. So, I've come up with an idea to build "engine" part as a library (static or dynamic) and the "game" part will link to this library. Simple.

However, there is one problem - "engine" part needs to reference some assets i.e. files with source code of builtin shaders (defualt shaders of the rendering engine).

Is there a way to include these shader files into an "engine" library? Or is there any other solution to this problem?


texts: Component oriented programming for rich RPG world

texts:
I've asked this question on several forums but didn't get the proper answer yet.
So, in my opinion, it is a really theoritical and deep, but I really can't deal with it by myself.
What is my goal?
I want to create a TES-inspired (The Elder Scrolls series) RPG with a really behaviour-complex world, when as a player you can, for example, not only play on guitar as a Musical Instrument, but use it as a Weapon or, what is perhaps more unobvious, throw it right to the furnace to get some heat in a cold winter night.
What did I get so far?
I started with upper-level ontology, because such world must have really deep complex hierarchies. There were an Entity, then MaterialEntity (with time and space extensions) and AbstractEntity (Notions, Relationships and so on). MaterialEntity was divided to Event, PhysicalObject (with mass and temperature). The last ones consisted of Creatures, Things, Substances (like water which is uncountable in the same sense as apples) and so on.
Then there was a big problem with tree-like inheritance: in the previous example a guitar was a MusicalInstrument, Weapon and Fuel at one time, furthermore there are a lot of another ways to interpret the thing and interact with it.
I decided that OOP with it's 2D Types (2D because every entity can be placed in a simple table with rows and columns) paradigm just not fit well in such complex case (like Newton's force formula for Mercury) and I need something better.
What did I tried?

Interfaces. Pros: Simple and obvious. Cons: A lot of code duplications and hard SRP-violation. Just imagine how many IOpeneable things you will have in code (door, bottle, box, chest, window and so on).
Strategy Design Pattern. Pros: More reusability that interfaces. Cons: old remain with DI handling added.
Components or Entity Systems. Pros: A lot of reusability, no duplication at all. Seems like this is a good choice for me, but...

The cons of COP (or just my misunderstanding)
I think that COP seems great for my task (and for other games) because it makes all the static compile-time coupling more runtime and dynamic, but it sacrifies a lot for it: the intelligibility of code, because now you see
entity.GetComponent<Openeable>.Open()

or
entity.GetComponent<Inventory>.AddItem( anotherEntity.GetComponent<Item>() )

instead of
box.Open();

or
inventory.AddItem( weapon );

As a developer I want my code to reflect the domain as much as possible, so the whole Component-Entity paradigm looks strange because there are nothing like components or systems in real (or game) world. In another words: I want more that just shift compile-time to run-time as COP does sacrificing the clarity of code.
Sorry for such long introduction, I just wanted to clarify the problem as much as possible.
The main question
Are there modern extensions of COP so far or should I just use another paradigm for my problem?
Thanks for your attention!


texts: What's the difference between CUDA and Shader?

texts:
I am new to CUDA, and it seems that CUDA and Shader are both GPU programs.

When we talk about GPU programming in rendering, like GPU voxelization, are we talking about CUDA or just converting data to Shader?


texts: What game development tool can I use on a computer that does not support shaders?

texts: I tried SFML, but found out that my computer does not support shaders. Given this restriction, what could I use instead?


texts: Unity3D - Using AddRelativeForce to push an object forever in zero gravity environment

texts:
Ok, I use AddRelativeForce to basically push an object. But it suppose to keep flying and keep accelerating as I hold down the key because I didn't set gravity. I just started Unity3D last month, so pls give me some advice.

// Force of individual thrusters
public float thrusterForce = 10000;
// Whether or not to add force at position which introduces torque
public bool addForceAtPosition = false;

private bool thrusterIsActive = false;
private Transform objectTransform;
private Rigidbody objectParentRigidbody;

void FixedUpdate() {
    if (thrusterIsActive) {
        if (addForceAtPosition) {
            objectParentRigidbody.AddForceAtPosition (objectTransform.up * thrusterForce, objectTransform.position);
        } else {
            objectParentRigidbody.AddRelativeForce (Vector3.forward * thrusterForce);
        }
    }
}


texts: Unity3D JavaScript/.NET code throwing compilation error with a List-thingy

texts:
So, I do this:

var intlist:List.<System.Int32>;
intlist.Add(1);

And where I say intlist.Add(1) I get:

NullReferenceException: Object reference not set to an instance of an object

Weird, huh? Apparently, the error is .NET related and List is a .NET thing. So, please clarify the problem. Thank you.

EDIT:

The "add comment" button isn't working, so I will respond in the form of an edit. No, I can't use a JavaScript array because for whatever reason it screws up in the context of my code and the Unity people say I shouldn't use them. The syntax I am using is correct (as far as I know) in JavaScript, but I don't know if it would be null or not. Obviously, it starts out empty. That's sort of the point.

EDIT 2:

It looks like I can't accept answers either. Thanks to the both of you. It turns out I did need to call the constructor, despite some rather strange syntax errors I was getting earlier. Blowing your magic fairy dust on it made the problem go away.


texts: How to draw point sprites with transparency in OpenGL without depth sorting?

texts:
I am trying to render point sprites with alpha transparency and because I render millions of points depth sorting would kill performance. My issue as you can probably imagine is that artifacts appear in some of the borders when the draw order is not correct:

My code for drawing:

glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDrawArrays(GL_POINTS,0,nSamples);

In my shader I just specify a alpha value in the output color depending on how close to the point center we are.

Is there any way to get rid of the artifacts and get a correct transparency render?


texts: Recommended formats to store bitmaps in memory?

texts:
I'm working with general purpose image rendering, and high-performance image processing,  and so I need to know how to store bitmaps in-memory. (24bpp/32bpp, compressed/raw, etc)

What is the "usual" or "normal" way to store bitmaps in memory? (in C++ engines/projects?)

How to store bitmaps for high-performance algorithms, such that read/write times are the fastest? (fixed array? with/without padding? 24-bpp or 32-bpp?)

How to store bitmaps for applications handling a lot of bitmap data, to minimize memory usage? (JPEG? or a faster [de]compression algorithm?)

I'm not working with 3D graphics or DirectX / OpenGL rendering and so I don't need to use graphics card compatible bitmap formats.

Some possible methods:

Use a fixed packed 24-bpp or 32-bpp int[] array and simply access pixels using pointer access, all pixels are allocated in one continuous memory chunk (could be 1-10 MB)
Use a form of "sparse" data storage so each line of the bitmap is allocated separately, reusing more memory and requiring smaller contiguous memory segments
Store bitmaps in its compressed form (PNG, JPG, GIF, etc) and unpack only when its needed, reducing the amount of memory used. Delete the unpacked data if its not used for 10 secs.


texts:
I have drawn a 2D circle in X,Y,Z. I wanted to draw something on specific vertices of that circle and I managed to do it. When I wanted to move the circle, I wanted the vertices to get the updated position, so I created another array of vertices and calculated the new vertex positions.

Now I want to rotate the circle, and while rotating it, the vertices should get the new orientation. How can I do this?

void creature::drawCircle(Vec3f Pos,float radius, int segments )
{

    // automatically determine the number of segments from the circumference
    if( segments <= 0 ) {
        segments = (int)math<double>::floor( radius * M_PI * 2 );
    }
    if( segments < 2 ) segments = 2;

    GLfloat *verts = new float[(segments+2)*3];
    GLfloat *vertsNew = new float[(segments+2)*3];
    verts[0] = 0;
    verts[1] = 0;
    verts[2] = 0;
    vertsNew[0] = 0;
    vertsNew[1] = 0;
    vertsNew[2] = 0;

    //Create circle
    for( int s = 0; s <= segments; s++ ) {
        float t = s / (float)segments * 2.0f * 3.14159f;
        verts[(s+1)*3+0] = math<float>::cos( t ) * radius;
        verts[(s+1)*3+1] = math<float>::sin( t ) * radius;
        verts[(s+1)*3+2] = 0;
    }

    //Transform points
    for( int s = 0; s <= segments; s++ ) {
    ci::Vec3f  m_newCirclePos;
        m_newCirclePos.x = verts[(s+1)*3+0];
        m_newCirclePos.y = verts[(s+1)*3+1];
        m_newCirclePos.z = verts[(s+1)*3+2];
        m_newCirclePos += ci::Vec3f(Pos);

        vertsNew[(s+1)*3+0] = m_newCirclePos.x;
        vertsNew[(s+1)*3+1] = m_newCirclePos.y;
        vertsNew[(s+1)*3+2] = 0;

    }

    // Attach tentacles on specific vertices
    for (int i=0; i<m_tentacle.size(); i++)
    {
        m_tentacle[i]->m_Nodes[0].x = vertsNew[(i+1)*3+0];
        m_tentacle[i]->m_Nodes[0].y = vertsNew[(i+1)*3+1];
        m_tentacle[i]->m_Nodes[0].z = vertsNew[(i+1)*3+2];
        m_tentacle[i]->enforceConstraints(Vec2f(0,0),0,0,0,0);
    }
    glPointSize(10);
    glEnableClientState( GL_VERTEX_ARRAY );
    glVertexPointer( 3, GL_FLOAT, 0, vertsNew );
    glDrawArrays( GL_POINTS, 0, segments + 2 );
    glDisableClientState( GL_VERTEX_ARRAY );
    delete [] verts;
    delete [] vertsNew;
}


texts: Why the size of my game increased on deploying it to Android using Unity3D?

texts:
When I deployed the game to 'Web Player', it's size was just 2.4 MB but when I deployed it to 'Android', it's size got increased to 38 MB.

Why this happened?  I can't provide any more information or code.


texts:
I am try make simple flying camera. Without character. But than I press forward camera moving to another direction.

    void Update()
{
    horizontalInput = Input.GetAxisRaw("Horizontal");
    verticalInput   = Input.GetAxisRaw("Vertical");

    var mouseX = Input.GetAxis("Mouse X");
    var mouseY = Input.GetAxis("Mouse Y");

    var trm = Camera.main.transform;

    if (horizontalInput != 0 || verticalInput != 0)
    {
        trm.position += moveSpeed * new Vector3(horizontalInput, 0, verticalInput);
    }

    var rotateValue = new Vector3(mouseY * 2, mouseX * -2, 0);

    trm.eulerAngles -= rotateValue;

    //trm.rotation = Quaternion.Euler(rotateValue);
}

Than I press 'W' camera moving  to left... I understand that it is necessary to coordinate the motion vectors and camera rotation. How best to do it?


texts: How to linearly blend between multiple points, deviating from a default point?

texts:
I have a set of 3D points that I need to "blend" between. Lets say I have points [A,B,C] and I have the amount I want to blend each as [0.5, 0.2, 0.8], how can I blend between these points with the amount I need? I asked this previously and got an answer.

But, when all values are 0, I need to return to a Default point, so all blending must take effect as if deviating from the Default.

How do I calculate this? I'm sure its not just a weighted barycenter anymore?


texts: How can I skew a SpriteRenderer in an animation to grow a side and decrease the opposite side by the same amount?

texts:
I am interested in the maths and maybe the shader code. I am almost sure that this would be a great starting point but I do not have any knowledge about shaders and the language they are written in.

The little project is just an attempt to create a flippable sprite, like the one I did in WPF but more interesting because of the "closer" perception. The objective is to learn. I have two animations, one rotating around the Y axis and the other one is this skew that I do not know how to do.

On the web I have found old answers and answers that use Image instead of SpriteRenderer, some complex math that I cannot comprehend yet.

Ideally the animation would go through all these states, from left to right, and then in the inverse order, from right to left (blue means unflipped state, green means flipped state):

I have started working with Unity since less than a week and I have forgotten a lot of maths and geometry I learned in school. But I am eager to learn again.

Thank you.


texts: How do I remove control points from imported curve in Maya?

texts:
When I create a path from an Illustrator file, it adds extra control points for bezier handles for each point in the AI file, even though I don't drag out the handles in Illustrator.  All my points in the AI file are hard edges.

I can clean this up by using the merge vertex tool, but that takes a long time on each model.  Is there a way I can:

Select all the control points at once and delete the extra curve handle points
OR
Import without the extra handle points and have only a flat polygon.

I'm importing the path as curves, because when I import as bevel it adds lots of extra geometry.  I'm new to Maya, but have taken several lessons, so please be gentle.


texts: How to get quality sprite sheet generation with rotations

texts:
I'm working on a game that uses sprite sheets with rotation for animations.  While the effect is pretty good, the quality of the rotations is somewhat lacking.  I exported a flash animation to png sequence and then used a C# app to do matrix based rotations (System.Drawing.Drawing2D.Matrix).

Unfortunately, there are several places where the image gets clipped.

What would you suggest for a way to get high quality rotations from either flash or the exported PNGs?  A circle should fit within the same image boundaries.  I don't mind a new program that I must write or an existing program I must download/buy.


texts:
I am trying to assemble scene assets and one asset needs an emission material where only the white part emits light:

I set up a texture with a simple (air-quotes) "mask" for the window...

...and tried to make only the white part emit light. This attempt blew up the entire material though (verified by checking model, adjusting intensity). I also tried plugging in the base texture directly but when I turned up the intensity, it looked like the black frame became a deeper black as well, which is not what I want.

Changing the intensity with just the white input and scalar multiplier does not reveal the black metal portion of the diamond pattern. How can I update this graph so that only the white part glows?

I want to use the texture to light the scene but may settle for filler lights, since it could be overkill. Here is the original scene I put together in Blender. The camera will be fixed like this. Note also that there are 9 other windows that emit light in this scene but are made invisible:

Thank you to everyone who takes an interest in helping me solve this problem, your time is appreciated.


texts: Camera.WorldToScreenPoint not working with perspective

texts:
transform.position = Camera.main.WorldToScreenPoint( new Vector3( origin.position.x, origin.position.y, origin.position.z ) );

I have this code on a Unity 4.6 UI object. The origin is some transform I want the UI element to stay above( like a floating health bar ).

The camera is top-down, but angled slightly on the x-axis. When the camera is moved, the UI element moves away from the origin slightly as if the camera was orthographic.

How would I go about compensating for the perspective? Is there another method I should be using to convert from world space to canvas space?

EDIT: Pictures added. Note that the transform is at the center of the model, not the base.


texts: What are some famous games developed with .NET and/or XNA?

texts: Are there famous games written in .Net and/or XNA?


texts:
So I've dipped my toe in and out of game programming pretty regularly over the past few years and all of the tutorials I've watched and books I've read have all had one thing in common that perplexed me.

Most of the logic in the games I've seen built is completely decentralized and distributed among the various components of the game. There isn't one (or several) central controller(s) that guide how everything interacts with everything else, or that objects and methods in the game defer to to enforce the rules/design.

If an object in a game (a player object for example) impacts a broader game system by say, resetting the level when it reaches 0 health, it doesn't call to some "LevelController" or "LevelController -> GameController" which then resets the level, it just does it itself by directly accessing a built-in game engine directive/method call.

Almost all the actions and interactions from initialization and set up, to combat, collisions, etc. are all resolved in a sort of case-by-case individual bases with all the rules contained solely within various game objects and the only "oversight" being the inherent limits of the game engine itself.

As someone who comes from a pretty traditional top-down Object Oriented development background this whole methodology feels scattershot and piecemeal. It has made it difficult for me to design any kind of holistic architecture for my game projects.

Is it just the case that most intro level projects are like this because they focus on the basic components of a game and how they work and less on more complex, higher level design? Or is it the nature of game design/development in general, perhaps a necessity due to the unique nature of the complexity of games?


texts: This is straight forward. I have an input field and I want to restrict the user of inputting any spaces. I was thinking to make a script that checks if the user typed in a space and then remove it, but is there a simpler way of doing this?


texts: Point to using vSyncCount higher than 1?

texts:
Is there a point to using QualitySettings.vSyncCount higher than 1?

From my understanding it sets the framerate to fractions of the screen refreshrate (i.e: FPS = refreshrate/vSyncCount). So 1 is standard VSync and 2 to 4 make no difference compared to 1 for eliminating tearing and only artificially limit framerate.

The only use for this that I can think of is for reducing power-draw for battery-driven devices like phones. Am I missing something?


texts: What C++ features should I know about for a graphics programming job interview?

texts:
I really don't want to be boring, I searched a lot but didn't found a focused answer to this question. I wanted to focus on the role of C++ in graphics programming.

Can  somebody explain, which are most likely/ most often used  C++ features (such as data structures), which are used in graphics programming? I am supposed to have an interview on this topic, so please shed some light on the features I should emphasize for an interview specific to C++ graphics programming.


texts: How do I make an entity move once per second in crafty.js

texts: I am trying to implement "Snake" using crafty.js but I can't seem to get the snake entity to move just once in a second. How do I do this?


texts: Unity3D Get object size in order to be used in Vector3 coordinates

texts:
I have a plane in Unity in 3D project, and I want to get its boundaries so I can use them in random function for getting Vector3 coordinates. Currently I am trying like this

GameObject ground;

void Start () {
        ground = GameObject.Find("Ground");
        moveAreaX = ground.GetComponent<Renderer>().bounds.size.x;
        moveAreaZ = ground.GetComponent<Renderer>().bounds.size.z;
        Debug.Log ("X Area: " + moveAreaX + ", Z Area: " + moveAreaZ);
        GetRandomTargetCoords();
    }

void GetRandomTargetCoords() {
        targetCoordsX = Random.Range(0f, moveAreaX);
        targetCoordsZ = Random.Range(0f, moveAreaZ);
        targetCoords = new Vector3(targetCoordsX, 1.1f, targetCoordsZ);

    }

And in the console I am getting this:

X Area: 108.5801, Z Area: 108.5801

The problem is the units provided by this bounds.size are not equal to the game object's Transform position's units, and so the game object gets out of the Plane's boundaries.

How can I make it have the same units for measurements?


texts: Basics of drawing in 2d with OpenGL 3 shaders

texts:
I am new to OpenGL 3 and graphics programming, and want to create some basic 2d graphics.  I have the following scenario of how I might go about drawing a basic (but general) 2d rectangle.  I'm not sure if this is the correct way to think about it, or, if it is, how to implement it.

In my head, here's how I imagine doing it:

t = make_rectangle(width, height)

build general VBO, centered at 0, 0

optionally: t.set_scale(2)
optionally: t.set_angle(30)
t.draw_at(x, y)

calculates some sort of scale/rotate/translate matrix (or matrices), passes the VBO and the matrix to a shader program

Something happens to clip the world to the view visible on screen.

I'm really unclear on how 4 and 5 will work.  The main problem is that all the tutorials I find either: use fixed function pipeline, are for 3d, or are unclear how to do something this "simple".

Can someone provide me with either a better way to think of / do this, or some concrete code detailing performing the transformations in a shader and constructing and passing the data required for this shader transformation?


texts:
I am using Unity3D 4.1 for one of my projects. I have a robot character which is always running. I am using mecanim animation system.

What I really want:When I press Space bar, the character should jump up in the air, triggering an animation clip and then by the time it reaches the ground, the animation clip should also end.
What actually is happening:When I press Space bar, the character jumps in the air. Animation clip plays as it should, but ends way before it reaches the ground. So, it looks like he is running in the mid air.
What have I done: I have this humanoid robot setup with a jump animation bounded with the space bar key. Also, instead of using root motion, I am directly moving the robot from code.

    //Jumping
if(Input.GetKeyDown(KeyCode.Space)){
    rigidbody.AddForce(Vector3.up*jumpVelocty);
    anim.SetBool("Jump",true);

}
else
    anim.SetBool("Jump",false);

Character's Details:

Rigidbody =
Mass:30, Freeze rotaion:x,y,z
Capsule Collider =
Material: metal, center(0,4.5,0), radius:1, height:11
Script =
jumpVelocity:20000

Jump Animation Clip: ~ 2 seconds.
I am really out of ideas how to synchronize everything. Should I make the character jump in some other way so that it quickly comes down and touches the ground to match the animation clip? If yes, please provide a direction.


texts: Are there cases where globals/singletons are useful in game development?

texts:
I know that having global variables or singleton classes creates cases that can be difficult to test/manage and I have been busted in using those patterns in code but often times you gotta ship.

So are there cases where global variables or singletons are actually useful in game development?


texts: Frame-rate drops when drawing 2D map tiles

texts:
Update: I figured out it has nothing to do with the camera but instead framerate drops when drawing my map tiles onto the screen.

Here’s a link to a video showcasing the bug in action (For further reference): https://streamable.com/m4zuf3
Any and all guidance is appreciated, thanks.
Here's the draw functions:
    protected override void Draw(GameTime gameTime)
    {
        m_mainLevel.Draw(spriteBatch);
    }

        public void Draw(SpriteBatch sb)
        {
            //Draw Background
            for (var i = 0; i < BackgroundTiles.Length; i++)
            {
                int id = BackgroundTiles[i].m_id;

                int column = id % TilesetTilesWide;
                int row = (int)Math.Floor((double)id / (double)TilesetTilesWide);

                int width = Map.TileWidth * 2;
                int height = Map.TileWidth * 2;

                float x = (i % Map.Width) * width;
                float y = (float)Math.Floor(i / (double)Map.Width) * height;

                Rectangle tilesetRec = new Rectangle(TileWidth * column, TileHeight * row, TileWidth, TileHeight);
                Rectangle dest = new Rectangle((int)x, (int)y, width, height);
                sb.Draw(Tileset, dest, tilesetRec, Color.White);
            }
        }

Is the problem that I'm drawing too many tiles per frame? the map size is 250 x 250 tiles, with each tile being 16x16px.


texts: Android: How to prevent player(drag/drop touch input) from moving through non-moving objects?

texts:
My player is moved around the screen by touch user input. The user touches the character and drags him to another position. (implemented in touchevent: actionmove and actiondown). I want the touch-movement to stop, as soon as the character reaches an object. So I don't want the character to pass through the object.

I used rect.intersect(player,object) to detect a collision between the player and the non-moving object. As soon as a collision is detected, I have to move the character back from the object, so that both don't overlap.
I used this minkowski-algorithm (Which Side Was Hit?) to find out on which side the collision occured. According to which side it is, I set back the player's position so it doesn't overlap with the non-moving object. Example for one side:

player.setPositionx(barrier.getCollision().left - player.getImage().getWidth());

or

 player.setPositiony(barrier.getCollision().bottom);

This is not working smoothly. When I move the player by touch really fast over the object, it still passes through and appears on the other side of the non-moving object (probably because the code for the other side is then being executed).
When I move the player along the left side, it suddenly appears on top of the non-moving object. When I move it on the bottom of the object, it may suddenly appear on the right or left side. (corners not smoothly)
How can I make sure that I can move the player (by touch input) around the object smoothly?


texts: Pixel Perfect Collision Detection in Cocos2dx

texts:
I am trying to port the pixel perfect collision detection in Cocos2d-x the original version was made for Cocos2D and can be found here: http://www.cocos2d-iphone.org/forums/topic/pixel-perfect-collision-detection-using-color-blending/

Here is my code for the Cocos2d-x version

bool CollisionDetection::areTheSpritesColliding(cocos2d::CCSprite *spr1, cocos2d::CCSprite *spr2, bool pp, CCRenderTexture* _rt) {
    bool isColliding = false;
    CCRect intersection;
    CCRect r1 = spr1->boundingBox();
    CCRect r2 = spr2->boundingBox();
    intersection = CCRectMake(fmax(r1.getMinX(),r2.getMinX()), fmax( r1.getMinY(), r2.getMinY()) ,0,0);
    intersection.size.width = fmin(r1.getMaxX(), r2.getMaxX() - intersection.getMinX());
    intersection.size.height = fmin(r1.getMaxY(), r2.getMaxY() - intersection.getMinY());

    // Look for simple bounding box collision
    if ( (intersection.size.width>0) && (intersection.size.height>0) ) {
        // If we're not checking for pixel perfect collisions, return true
        if (!pp) {
            return true;
        }

        unsigned int x = intersection.origin.x;
        unsigned int y = intersection.origin.y;
        unsigned int w = intersection.size.width;
        unsigned int h = intersection.size.height;
        unsigned int numPixels = w * h;
        //CCLog("Intersection X and Y %d, %d", x, y);
        //CCLog("Number of pixels %d", numPixels);

        // Draw into the RenderTexture
        _rt->beginWithClear( 0, 0, 0, 0);

        // Render both sprites: first one in RED and second one in GREEN
        glColorMask(1, 0, 0, 1);
        spr1->visit();
        glColorMask(0, 1, 0, 1);
        spr2->visit();
        glColorMask(1, 1, 1, 1);

        // Get color values of intersection area
        ccColor4B *buffer = (ccColor4B *)malloc( sizeof(ccColor4B) * numPixels );
        glReadPixels(x, y, w, h, GL_RGBA, GL_UNSIGNED_BYTE, buffer);

        _rt->end();

        // Read buffer
        unsigned int step = 1;
        for(unsigned int i=0; i 0 && color.g > 0) {
                isColliding = true;
                break;
            }
        }

        // Free buffer memory
        free(buffer);
    }

    return isColliding;
}

My code is working perfectly if I send the "pp" parameter as false. That is if I do only a bounding box collision but I am not able to get it working correctly for the case when I need Pixel Perfect collision.
I think the opengl masking code is not working as I intended.

Here is the code for "_rt"

_rt = CCRenderTexture::create(visibleSize.width, visibleSize.height);
_rt->setPosition(ccp(origin.x + visibleSize.width * 0.5f, origin.y + visibleSize.height * 0.5f));
this->addChild(_rt, 1000000);
_rt->setVisible(true); //For testing

I think I am making a mistake with the implementation of this CCRenderTexture

Can anyone guide me with what I am doing wrong ?

Thank you for your time :)


texts: Best way to learn iphone game development?

texts: I know php and some python, but not much c. Where should I start to learn iphone game development? Is there some recommended books/tutorials for beginners? I'm looking at using cocos2d but I'm open to anything that isn't too limited.


texts: How can I prevent pixel artifacts on programatically generated textures?

texts:
In the game I'm developing, rooms can be of various sizes, which means I need to vary the size of the floor texture appropriately.

The way I've solved this problem is to generate a Texture2D programatically, and set each pixel to be transparent (or not) as appropriate appropriately.

I get something like this:

Where, if you look at the top left, you'll clearly see the pixel artifacts from the floor texture against the dark blue background.

When I run into this with static textures, the fix is simple. Set the Texture's wrapmode to clamp instead of repeat. But when I try to do that programatically... (and change nothing else!) I get this:

I'm not quite sure what's happening, or why setting the wrapMode changes the results so markedly. Anyway I can avoid the pixel artifacts? I suppose it's possible to add an extra border around the generated texture (so that all edges can be transparent), but that doesn't seem a particularly clean solution.

Code is here:

void DebugFloorTextureMerge()
    {

        //sizeVector makes up the rectangle circumscribing the room's parallelagram
        Vector2 sizeVector = new Vector2(roomBounds.topRight.x - roomBounds.bottomLeft.x, roomBounds.topLeft.y - roomBounds.bottomLeft.y);

        //get the texture of the filled sprite
        Texture2D patternTexture = (Texture2D) floorTexture.image;

        //make a new texture of the size of the room.
        Texture2D fillTexture = new Texture2D( (int) sizeVector.x, (int) sizeVector.y, TextureFormat.ARGB32, false);

            //COMMENTING THIS LINE OUT MAKES THE TEXTURE WORK WITH ARTIFACTS
        fillTexture.wrapMode = TextureWrapMode.Clamp;
            //LEAVING IT IN MAKES THE FOLLOWING CODE WORTHLESS

        int patternX = 0, patternY = 0;

        Vector2 pointVector;
        Color transparent = new Color(0,0,0,0);

        for(int x = 0; x < sizeVector.x; x++)
        {
            for(int y = 0; y < sizeVector.y; y++)
            {
                pointVector = new Vector2(x,y);
                if(roomBounds.Contains(pointVector))
                {
                    //get the next pixel
                    fillTexture.SetPixel(x,y, patternTexture.GetPixel(patternX, patternY));
                }
                else
                {
                //pixel was not in the room, so set it to transparent.
                    fillTexture.SetPixel(x,y, transparent);
                    //resultx = x; resulty = y;

                }

                //increment the pattern counter and reset if necessary.

                //if you only increment this when Contains is true, you'll warp the texture
                patternY++;
                if(patternY >= floorTexture.fillSize.y) patternY = 0;
            }

            //increment the pattern counter and reset if necessary.
            //also reset y, so the pattern will line up properly.
            patternY = 0;
            patternX++;
            if(patternX >= floorTexture.fillSize.x) patternX = 0;
        }

        //set the PixelChanges.
        fillTexture.Apply();
    }


texts: Effective marketing strategies for independent game projects

texts:
I would really like to hear how other independents generally approach marketing their game with limited resources. I know how critical marketing is since I've seen it first hand on several fronts. I've been part of teams that didn't put an ounce of marketing into their project and didn't come close to meeting expectations. I've also poured a lot of time into visiting forums to discuss our previous title which resulted in minor bumps over time.

I really think Wolfire is doing some amazing grass roots marketing with the way they are managing their community around their Blog. They've massed a following that is willing to pay (far in advance) them for their game before they finish it to help support them. That's awesome.

But how many people are really willing to divulge such information that early? Should that be a concern? Should I start talking about my next project before I really have anything implemented?

What has worked for you? I would be particularly interested to hear how people approach Apple's iTunes store. I believe we're looking at around 33,000 games on the store these days.


texts: How do I handle parallel lines when looking for intersections?

texts:
I'm using the following method to determine the intersection point of two vector2:

public static Vector2 LineIntersectionPoint(Vector2 startPoint1, Vector2 endPoint1, Vector2 startPoint2, Vector2 endPoint2)
{
    // Get A,B,C of first line - points : startPoint1 to endPoint1
    float A1 = endPoint1.y - startPoint1.y;
    float B1 = startPoint1.x - endPoint1.x;
    float C1 = A1 * startPoint1.x + B1 * startPoint1.y;

    // Get A,B,C of second line - points : startPoint2 to endPoint2
    float A2 = endPoint2.y - startPoint2.y;
    float B2 = startPoint2.x - endPoint2.x;
    float C2 = A2 * startPoint2.x + B2 * startPoint2.y;

    // Check if the lines are parallel
    float delta = A1 * B2 - A2 * B1;
    if (delta == 0)
        throw new System.Exception("Lines are parallel");

    // Return the intersection point
    return new Vector2(
        (B2 * C1 - B1 * C2) / delta,
        (A1 * C2 - A2 * C1) / delta
    );
}

Currently the method throws an exception for parallel lines but I don't like the idea to wrap every call of that function in a try/catch.

Is there a better solution for this? I can't return null because Vector2 is a struct.

Maybe somthing like the following?

public static bool LineIntersectionPoint(Vector2 startPoint1, Vector2 endPoint1, Vector2 startPoint2, Vector2 endPoint2, out Vector2 intersectionPoint)


texts: How do I zoom in and out in a fully tiled based game

texts:
I am currently developing a tile based game in Java and trying to add the option of zooming. I do the zoom by reducing and enlarging the tiles, but the problem is that it creates spaces between the tiles.
The default form, in which I created all of these tiles from the beginning:

When zooming out - width -= 2 and height -= 2:

Bigger zooming out:

My question is very simple, how do I zoom in and out on a tile based world?


texts:
I have this Unity UI Image placeholder and here is the snapshot

 As you can see its edges are not smooth. First I thought this is editor problem but after making the build it remains the same. What i am missing?


texts: How do components access one another in a component based entity system

texts:
---Most of the stuff I am talking about I read here---

I am currently tring to wrap my head around component based systems to make a simple game engine of sorts.

I am having a hard time understanding how its supposed to work. I get that there are components which all inherit from the same base, which provides basic functions (init, update, end) and lets all of the different kind of components be stored in the same array of pointers. I get that. However I dont get how any efficient interactions of the components in a game object are supposed to happen.

Lets say I made a component that stores the amount of gold in a treasure chest (lets call it dataComponent).
Lets also assume I made a component that does something when its update function is called (lets call it logicComponent)

There is also a class called Entity

class entity{
private:
    vector<component*> components;
public:
    void addComponent(component* comp);
    void removeComponent(component* comp);
    void getComponent(int id);
}

Lets now say I plan to make treasureChest, without any functions. Its just a background model.
Then I will make a new enitity and using addComponent I will add the dataComponent(and give it 100 gold pieces in its constructor) and a logicComponent(and give it nothing in its constructor).
The player might take out, or put in as much gold as he likes. We dont know how much gold there is in the chest. There might even be multiple dataComponents storing how many jewels or weapons are in the chest.

Example:

void main(){
    Entity chest;
    chest.addComponent(new dataComponent<int>("gold",100)); //100 gold pieces
    chest.addComponent(new dataComponent<int>("guns",2)); //2 weapons
    chest.addComponent(new logicComponent()); //this is going to do the printing
    updateEnt(Entity);//simply iterates through all components of the entity and calls thier update functions.
}
EXPECTED OUTPUT:
This chest contains 100 gold and 2 guns

The logic components job is to somehow get its hands on the data and print it to the screen.

My question is:
How can the logic component get access to the other components in the same object as it is in and access the approperate ones (the ones it needs to function) without looking through the entire array every single time?