texts: Call native code from Unity iOS build error

texts:
I created NativeCallProxy.cs in Unity

    public class NativeCallProxy: MonoBehaviour
    {
        [DllImport("__Internal")]
        public static extern void iOSUnloadUnityGame();

        public static void UnloadUnityGame()
        {
#if UNITY_IPHONE
            // Now we check that it's actually an iOS device/simulator, not the Unity Player. You only get plugins on the actual device or iOS Simulator.
            if (Application.platform == RuntimePlatform.IPhonePlayer)
            {
                iOSUnloadUnityGame();
            }
#endif
        }
    }

and created two files in Assets/Plugin/iOS
NativeCallProxy.m

#import <Foundation/Foundation.h>
#import "NativeCallProxy.h"

@implementation UnityBridgeAPI
id<UnityBridgeNativeCallsProtocol> api = NULL;
+ (void) registerAPIForNativeCalls:(id<UnityBridgeNativeCallsProtocol>)proxy {
    api = proxy;
}
@end

and NativeCallProxy.h

#ifndef NativeCallProxy_h
#define NativeCallProxy_h

@protocol UnityBridgeNativeCallsProtocol
@required
- (void)unloadUnityGame;
@end

__attribute__((visibility("default")))
@interface UnityBridgeAPI: NSObject
+ (void) registerAPIForNativeCalls:(id<UnityBridgeNativeCallsProtocol>)proxy;
@end

#endif /* NativeCallProxy_h */

and when I try to compile exported project I get an error in Xcode.

How can I figure out it?


texts: Why does my game not update unless I'm moving the mouse?

texts:
I'm pretty confused by what's happening. Now that I've finally put something moving on my screen, I notice it doesn't update unless I move the mouse, or press a key, or trigger other events.

Using PIX, the "Frame: #" counter only goes up when I fire these events. This is all that happens in my game loop:

while(GetMessage(&msg, NULL, 0, 0) > 0 && m_isRunning)
{
        TranslateMessage(&msg);
        DispatchMessage(&msg);

        m_gameGraphics->BeginRender();
        m_gameGraphics->EndRender();
}

BeginRender clears the screen, and EndRender presents to the swap chain. I thought maybe it was a problem with WndProc, but comparing it to other DirectX 11 game WndProcs, I don't see any major differences. I'm pretty confused, never seen this problem before, and I have no idea what causes it. I'm just hoping maybe someone will have some insight on why this might be happening.


texts: Adjacency in procedural generation of dungeon

texts:
I wanted to make a procedural dungeon experimenting a new approach, it works nice for random-meaningless content (in example a procedural background to a level), however when I want it to be not-so-random I incur in some conceptual problem: basically I end up with a grid of numeric sector IDs in 2D.

Grid example:

27 |  56  | 74
---+------+----
35 |  31  | 115
---+------+----
14 |  52  | 12

The main problem is how to fix adjacency so that content is generated in a deterministic way:

Content of sector "31" should be generated as a function of adjacent sectors (this works)
However when I generate content for sector "35", I end up with a different link between sector "35" and "31".

So basically according from which direction I cross a sector I see a different passage each time (while the content of the sector is always the same).

As you see in the following image:

The passage between 35-31 is different according to which sector is used to start content generation, which is not what I want. I want the same passage arise.

To answer comments:

sector[id].content = generateContent( sector[id].neighboursIds());


texts: How can I accomplish Pokemon-style movement over tiles in java?

texts: I'm talking about where if you press a directional key once you walk over to the adjacent tile and can't do any other actions during the walk. I can get my character to move one tile width, but my trouble is animating the walk and having the character actually walk to the next tile, rather than teleport. The research I've done has pointed me in the direction of interpolation, but I don't really understand how to get it working.


texts:
I know a thing or two about Unity at this point, but I've still lots of subjective, best practice questions, Such as:
How do you decide what values are obtained via Start/Awake initialization, and which values are explicitly serialized into the scene? In my current project, game objects and behaviors reference each other in a complex graph. Initially, I did this on Start(), programmatically, with lots of raycasts and GetComponent<>() and such. Now though, I just declared stuff public (violating encapsulation?), to simply serialize this information to the scene once generated by an Editor script... Which is more correct? Should my methodology be that anything that can be serialized should be serialized? Or is it better to write more initialization code which conveys some explanation why the values are what they are?


texts: How do I upscale my scene to a larger viewport?

texts:
I want to:

Render my scene to a small viewport (some divisor of the full screen size).
Stretch the rendered image to cover the full screen size.

For example I want to render a complex, very slow scene at 960x520 and then stretch the resulting image over a full 1920x1040 screen.

Texture2D.LoadTextureFromTexture() can achieve that result, but is incredibly slow (far, far too slow for gaming). Similarly, Device.CopySubresourceRegion() or Device.CopyResource() copies the pixels exactly based on the size of the image, so they don't stretch at all and a 960x520 image will simply take up a corner of the full screen.

I could render the texture onto a quad, but I wanted to know if there was a way to do this programmatically before writing a shader just to stretch an image.


texts: Calculating missile trajectory around orbits before shooting

texts:
I'm building a game with Unity3D. It's a  Gravity Wars  clone. Both player and AI turrets shoot missiles at each other (giving an Angle and a Power variables), trying not to crash missiles on planets.
But here's my question: how do I make AI calculate power and angle before shooting his missile, considering a planet's gravity too?


texts: How does Vector3.MoveTowards work in Unity?

texts: What I mean is that I don't understand what each part does, like in the example in the API, it didn't give much on what did what! I kinda need this for an aim script in a shooter game I'm working on. Any help will be good, but a direct answer would be great!


texts: Can't add inspector variables to script?

texts:
So I just added this script to my project : https://www.assetstore.unity3d.com/en/#!/content/11278 Since this script only draws the lines on gizmos, I wanted to add a LineRenderer, so that I can draw the lines also in GameView. So I simply wrote :

public LineRenderer lr;

But this variable never appears in my inspector, can anybody explain me why this happens and how I could fix it?


texts: Instantiate and launch prefab that's overlapping player?

texts:
I’m very new to Unity and C#. I’m trying to create my first game and I have now invested about 15+ hours trying to find solutions to this issue...I’m stumped!

My player sprite (blue square) needs to launch a prefab sprite (red circle) of similar size ‘appearing’ to originate from itself. Here is a GIF of what I have so far...I don’t want the blue cube to collide and go flying.

After clicking and dragging on Player (drag-to-aim) via OnMouseDrag to set the target vector, I’m trying to Instantiate a prefab sprite (Dynamic RigidBody2D, CircleCollider2D) using the Player sprite’s position (a Dynamic RigidBody2D, BoxCollider2D) and have it APPEAR to be originating from inside the Player object. Launch is triggered via function called in OnMouseUp. Both objects should immediately come under control of Physics to collide with the environment which will include other moving RigidBody2D objects later. Targeting should allow 360 degrees to include straight into an obstacle allowing rebound effect.

Here is some excerpts of my code:

using System.Collections;
using UnityEngine;

public class Teleportation_Grenade : MonoBehaviour {

/*
    This script is attached to Player and requires_
    projectile prefab.

    tested with thrust set between 100 and 200.
*/

    public float thrust;
    public Transform prefab;
    public LineRenderer playerShotLine;

    private Vector2 playerToMouse;
    private Vector2 targetVector;

//...

    void OnMouseDrag()

    {
        Vector3 mouseWorldPoint = Camera.main.ScreenToWorldPoint (Input.mousePosition);
        Vector2 playerToMouse = mouseWorldPoint - transform.position;
        mouseWorldPoint.z = 0f;

        playerShotLine.SetPosition (0, transform.position);
        playerShotLine.SetPosition (1, mouseWorldPoint);
        playerShotLine.sortingOrder = 3;

        //opposite direction of line renderer
        targetVector = -playerToMouse;

    }

    void OnMouseUp()

    {
        SpawnPrefab ();
    }

    void SpawnPrefab()

    {
        Instantiate(prefab, new Vector3(transform.position.x, transform.position.y, 0), Quaternion.identity);

        prefab.GetComponent<Rigidbody2D> ().AddForce (targetVector * thrust, ForceMode2D.Impulse);
    }
}

This is only one of many, many iterations. It's the gist of it though. I appreciate any insight from the community.


texts: Why I cant change the GUILayout.Button color to green when click on a button?

texts:
I used a break point and it's getting to the line:

style.normal.textColor = Color.green;

But not changing the color of the clicked button.
And there are no any errors or exceptions.

using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using UnityEditor;
using UnityEngine;
using System.IO;

public class Manager : EditorWindow
{
    [MenuItem("Tools/Manager")]
    static void Manage()
    {
        EditorWindow.GetWindow<Manager>();
    }

    private void OnGUI()
    {
        var style = new GUIStyle(GUI.skin.button);
        style.normal.textColor = Color.red;
        style.fontSize = 18;

        string[] assetPaths = new string[2];
        string[0] = "Test";
        string[1] = "Test1";

        foreach (string assetPath in assetPaths)
        {
            if (assetPath.Contains(".test")
            {
                var i = assetPath.LastIndexOf("/");
                var t = assetPath.Substring(i + 1);

                if (GUILayout.Button(t, style, GUILayout.Width(1000), GUILayout.Height(50)))
                {
                    style.normal.textColor = Color.green;
                }
            }
        }
    }
}


texts: Libgdx: Using an AssetManager in every Screen or use a single AssetManager in Game class

texts:
I have a HexGame class extending Game and various Screens that receive the game object in their constructor. I was thinking of having one AssetManager in the game class and using it to load the necessary assets in each screen's constructor and unload them in the screen's dispose method.
The alternative would be to use a new AssetManager in every screen. What would be best practice?


texts: Why can't I directly change the position of a prefab using transform.position? (Unity3D)

texts:
I am relatively new to Unity, and I am currently working on some code. I am trying to change the position of Unity's standard assets first-person controller using

player.position = anotherObject.position + offset;

I'd like to add that I am setting the player's position when it collides with a box collider.

However, this isn't working for some reason. I've tried debugging it using print statements before and after the teleportation of the player, and this is what I see:

Player position: (0, 2, 0)
Player position after teleport: (32, 2, 0)
Player position one frame later: (0, 2, 0)

After one frame, the player returns to it's original position, as if it was never moved.

Here is my code, if it will help you better understand my problem.

public class PortalTeleporter : MonoBehaviour {

    public Transform player; // The player
    public Transform receiver; // Receiving portal

    private bool playerOverlap = false; // boolean to store whether player touches the box collider on portal

    void Update(){
        if(playerOverlap){
            Vector3 portalToPlayer = player.position - transform.position;
            float dotProduct = Vector3.Dot(transform.up, portalToPlayer);
            if(dotProduct < 0f){
                float rotationDifference = Quaternion.Angle(transform.rotation, receiver.rotation);
                rotationDifference += 180;
                player.Rotate(Vector3.up, rotationDifference);

                Vector3 positionOffset = Quaternion.Euler(0f, rotationDifference, 0f) * portalToPlayer; // Offset between player and portal
                Vector3 pos = receiver.position + positionOffset;
                print(player.position);
                player.position = pos;
                print(player.position);
            }
        }
    }

    // Triggered when player enters the portal
    void OnTriggerEnter(Collider other){
        if(other.tag == "Player"){
            playerOverlap = true;
        }
    }

    // Triggers when player untouches the portal
    void OnTriggerExit(Collider other) {
        if(other.tag == "Player"){
            playerOverlap = false;
        }
    }

Thank you for taking the time to answer my question!


texts: Cocos2d v2.0 and OpenGL 2.0/1.0: where to start

texts:
I started developing my very first game 3 months ago using Cocos2d 2.0 for iPhone. I am now in the stage where I'd like to add some cool effects to the bullets and some special weapons (see my waveforms question here). I got a good answer in the cocos2d-iphone forum (see this one).

Unfortunately I am a bit paralized now. I don't know if I will be overdoing by learning OpengGL 2.0 or if I should just stick ot the old 1.0. There is a good intro on various tutorial's written in Steffen Itterheims blog (see this post).

I would like to add to my game:

a blur effect to the bullets (here is a tutorial for OpenGL 1.0)
a waveform (see above)
some realistic water ripples (here is a nice sample code)

So now, given that I don't want to overdo things but at the same time I want to achieve those effects, from where should I start? Should I discard the OpenGL 1.0 tutorials? OR should I use only OpenGL 1.0 code?

How can I avoid confusion? I mean, it seems that the compiler recognizes both, but that there are some conflictual calls in some circumnstances, I am fairly sure this has some explanation, is there some reference to this somewhere?


texts: Say I've got a list of a hundred unique weapons, how can I programmatically and easily identify them all?

texts:
I've got a class, WeaponFrame, that has an int member, weapon_frame_id, that I intend to use as a way to identify the weapon, and I use that compare against other WeaponFrame instances.

The problem is that I want to pull the weapon from the global list of WeaponFrames and equip it on an Actor. As the designer, I might know that weapon_frame_id #2 is the bow weapon I want, but what is the best way to programmatically identify them?

If I assign an ID to the WeaponFrame on instantiation, I am unable to rely on the value being identical the next time the game is run, unless I assign the value to an enum or int then. That might work though.

I'm using C++11, would I just create a namespace somewhere, and enumerate all the weapon types,

enum class WeaponFrameIDs {
  Sword = 1,
  Bow = 2, //repeated a hundred-plus times
};

or would I make a ton of const integers in a header somewhere, even if effectively an enum that way too:

namespace WeaponFrameIDs {
  const int Sword = 1;
  const int Bow = 2;
}

I could also use strings mapped to an integer, but I'm losing compile-time verification (and I can't use constexprs with VS2013), and run the risk of duplicating entries. However it supports dynamic assignment to the list:

std::unordered_map<std::string, int> WeaponFrameIDs {
  {"Sword", 1},
  {"Bow", 2},
};

Is there an alternative that I'm missing? What is the best way to write a system for identifying weapons in a game?

If it's relevant, here's an example situation I'm trying to solve via code. I am not using a visual editor where I can drag a weapon onto an actor.

void set_up_actor()
{
  Actor actor;
  WeaponFrame* weapon_frame = AllWeaponFrames.at(WeaponFrameIDs::Bow);
  actor.weapon_frame = weapon_frame;
};

Points I'm looking to avoid:

Filling an entire header with enums
Needing to recompile the entire project because I changed that header
Losing the ability to verify the id at compile time
Eventually add user-generated ids. This conflicts a lot with the compile-time  verification.

I'm trying to solve the best way to pull the Weapon from a list, whether it's by ID, index, specially mapped key or something else.

If I use a literal ID, actor->weapon_id = 1, I don't know what weapon is tied to the ID of 1.
If I use an enum, or a const int, to represent the 1, I need to recompile the game for each of the new weapons I add.
If I change the id type to a string, I lose the ability to programmatically validate the string against the existing list of weapons.


texts: How do I have different colliders against different objects? Unity

texts: Say for example I have a ball, I want the sphere collider to be a certain radius when it comes into contact with one material (material A in diagram) and a different size when it comes into contact with another material (material C in diagram). How would I go about doing this? (Diagram attached)


texts: How to get point depth in shadow space for point light?

texts:
I'm implementing exponential shadow maps, and so far I have directional lights and spotlights working perfectly.  Currently I'm trying to apply this technique to point lights with cubemapped shadows.

The theory is, the visibility factor should be computed as a product of two exponentials:

visibility = exp(k*occluderDepth) * exp(-k*receiverDepth)

So the shadow map, instead of storing depth, stores exp(koccluderDepth), and the lighting pass multiplies this value by exp(-kreceiverDepth).

My shadowmap renderer looks like this:

//vsh
#version 410

uniform mat4 viewProjectionMatrix;
uniform mat4 modelTransform;

in vec4  position;

void main (void) {
    gl_Position = viewProjectionMatrix * modelTransform * position;
}

//fsh
#version 410

float lightExponentialConstant = 200.0;

layout (location = 0) out float exponentialMapVaule;

void main (void) {
    exponentialMapVaule = exp(lightExponentialConstant * map_01(gl_FragCoord.z, lightNearPlane, lightFarPlane));
}

The visibility for spot and directional lights is computed like so and it works perfectly:

uniform sampler2D shadowmapSampler;
uniform mat4 shadowSpaceProjection;

float map_01(float x, float v0, float v1) {
  return (x - v0) / (v1 - v0);
}

float computeVisibility(vec3 position) {

    mat4 shadowBias = mat4(
        0.5, 0.0, 0.0, 0.0,
        0.0, 0.5, 0.0, 0.0,
        0.0, 0.0, 0.5, 0.0,
        0.5, 0.5, 0.5, 1.0
    );

    vec4 shadowCoord =  shadowBias * shadowSpaceProjection * vec4(position, 1.0);
    float occluder = texture(shadowmapSampler, shadowCoord.xy/shadowCoord.w).r;
    float reciever = map_01(shadowCoord.z/shadowCoord.w, lightNearPlane, lightFarPlane);
    float visibility = clamp(occluder * exp(-lightExponentialConstant * reciever), 0.0, 1.0);

    return visibility;

}

So basically the receiver value is the depth of the world position projected into shadow space, and then mapped to the range [0, 1] according to the offset of that point from the shadow projection's near plane and far plane.

I have tried to apply the same logic to the cubemap shadowmap for my point light:

float map_01(float x, float v0, float v1) {
  return (x - v0) / (v1 - v0);
}

uniform samplerCube shadowCubemap;

float computeVisibility(vec3 position, vec3 lightPosition) {

    vec3 ray = position - lightPosition;
    float distance = length(ray);
    float occluder = texture(shadowCubemap, normalize(ray)).r;
    float receiver = map_01(distance, lightNearPlane, lightFarPlane);
    float visibility = clamp(occluder * exp(-lightExponentialConstant * reciever), 0.0, 1.0);

    return visibility;

}

So here, if I understand correctly, distance should be the length of the vector between the world position and the light position (which should be equivalent to the reprojected depth from the 2D example).  But everything is occluded when I use this method.

What am I missing?  In particular, I'm not sure if I am not confident about the cubemap sampling, or if I'm missing some step to ensure that the distance value used to compute the receiver value is actually being transformed correctly to shadow space.


texts:
I'd like to ask for reference. I met an article about how to cast shadows in games. I'm using html5 canvas (currently without webgl) with javascript for my projects.

The article mentioned above is located at http://willyg302.wordpress.com/2012/11/04/2d-visibility/.

I was thinking if this method is possible to employ with canvas (without webgl) and javascript?

More precisely, I have few shapes drawn on canvas some of them are complex made by arc and similar methods. Thus I don't have a simpel way how to describe one shape with an equation where I can store only a few parametrs (i.e. circle is described as centerX, centerY, radius with these I can easily draw it but with more complex shapes I don't have such information) therefore I thought about storing the whole canvas data by pixels with context.getImageData.data, then using method described in the article (polar transformation, ..., back to cartesian system) and putting the whole scene into canvas with canvas.putImageData method.

But before actually applying this I'd like to ask if it's even possible with canvas (no webgl) and javascript to create shadows dynamically (light source moving across the screen) this way without heavy fps loss (I can imagine this method works pretty good for still objects but the moment when I need to do it each time a light source moves I'm not sure if javascript + canvas can handle this in reasonable time, especially when I found information that putImageData and getImageData are quite slow)?

Or if anyone has tried to create dynamic shadows in different way in html5+js I'd appreciate your suggestions about these as well (I do it currently in similar way as is described in http://ncase.me/sight-and-light/, though I'm experiencing some troubles with concave shapes :( ).

This is getting awfully long, I hope I explained myself well enough.

Thank you very much for any advice you can share and I'm sorry that my post grew so large, although I'm asking just one question.

EDIT: Forgot to mention, I'm looking only for 2d solution.


texts: Create sprite sheet (texture atlas) from video with alpha

texts:
What's the best way to make a sprite sheet (texture atlas) from a video?

In my case, I have videos of animated character expressions (e.g., smiling, frowning, sad, excited), which I intend to use as frames on quads in my app. I have video sized for retina 2x of a small character, so it's approx 150px square for a 75px character, with alpha/transparency. My animator can output any common format. I'll have 50-100 frames. I do not need a power-of-two size output, any rectangle is ok. I'm working on MacOS.

Is the best workflow still: video -> folder with PNGs -> TexturePacker

Or is there any smarter way to do this? I'll be having a lot of iterations, so I'd like to make it as easy and fast as possible.

There are two older questions from 2010 and 2012 about making sprite sheets.


texts: How to limit Box2D bodies to only be affected on 1 axis

texts:
I have a side scrolling game, where I am randomly placing trees, bushes etc.. I would like these bodies to fall ( To Align with the ground ) but not to slide.

What is the best way to achieve this and to avoid the bodies moving left to right.

Current Create Body Code:

final shape = new CircleShape();
shape.radius = 60;
shape.p.x = 0.0;

final activeFixtureDef = new FixtureDef();
activeFixtureDef.shape = shape;
activeFixtureDef.restitution = 0.1;
activeFixtureDef.density = 5.00;
activeFixtureDef.friction = 0.1;

//Set mask bit filter for collision avoidance
Filter filter = Filter();
filter.groupIndex = -1;
activeFixtureDef.filter = filter;

FixtureDef fixtureDef = activeFixtureDef;
final activeBodyDef = new BodyDef();
activeBodyDef.linearVelocity = new Vector2(0.0, 0.0);
activeBodyDef.position = new Vector2(0, 0);
activeBodyDef.type = BodyType.DYNAMIC;
BodyDef bodyDef = activeBodyDef;


texts:
Is there any way to play a YouTube video given the URL in XNA? I know it can be done using a shockwave control but I need it in XNA.

I need to make a game where it has to be a YouTube video on the back... something like this:

Texture2D texture = YouTubevideoPlayer.GetTexture();

Because I need the streaming on a texture.

I think it can be done by using the youtube APIs... but some tutorial or useful code its a great help.


texts: Cocos2d -- Check if place is free before moving (all objects)

texts: Is there a method in Cocos2d like CGRectIntersectsRect, except instead of limiting it to one sprite, it checks for ALL objects?


texts: How do I generate a smooth random horizontal 2D tunnel?

texts:
I'd like to create a smoother version of the navigable and quite natural-looking random tunnel found in this classic helicopter game.

It should ideally be...

infinite, so more can be generated as the player progresses;
parametrised, allowing control of its thickness over time;
made of smooth curves, not rectangles as in the above game;
precomputable, as knowing its bounds in advance allows collision detection for e.g. positioning powerups inside the tunnel.

I'm looking for a generic method I could implement myself.
Further parameters and optimizations are welcome.

Asking here was suggested on StackOverflow. I think this fits in both places, as it's as much about the algorithm as about gamedev.


texts: GLSL per pixel lighting with custom light type

texts:
Ok, I am having a big problem here. I just got into GLSL yesterday, so the code will be terrible, I'm sure.

Basically, I am attempting to make a light that can be passed into the fragment shader (for learning purposes). I have four input values: one for the position of the light, one for the color, one for the distance it can travel, and one for the intensity. I want to find the distance between the light and the fragment, then calculate the color from there. The code I have gives me a simply gorgeous ring of light that get's twisted and widened as the matrix is modified. I love the results, but it is not even close to what I am after.

I want the light to be moved with all of the vertices, so it is always in the same place in relation to the objects. I can easily take it from there, but getting that to work seems to be impossible with my current structure. Can somebody give me a few pointers (pun not intended)?

Vertex shader:

attribute vec4 position;
attribute vec4 color;
attribute vec2 textureCoordinates;

varying vec4 colorVarying;
varying vec2 texturePosition;
varying vec4 fposition;
varying vec4 lightPosition;
varying float lightDistance;
varying float lightIntensity;
varying vec4 lightColor;

void main() {
    vec4 ECposition = gl_ModelViewMatrix * gl_Vertex;
    vec3 tnorm = normalize(vec3 (gl_NormalMatrix * gl_Normal));
    fposition = ftransform();

    gl_Position = fposition;
    gl_TexCoord[0] = gl_MultiTexCoord0;
    fposition = ECposition;

    lightPosition = vec4(0.0, 0.0, 5.0, 0.0) * gl_ModelViewMatrix * gl_Vertex;
    lightDistance = 5.0;
    lightIntensity = 1.0;
    lightColor = vec4(0.2, 0.2, 0.2, 1.0);
}

Fragment shader:

varying vec4 colorVarying;
varying vec2 texturePosition;
varying vec4 fposition;
varying vec4 lightPosition;
varying float lightDistance;
varying float lightIntensity;
varying vec4 lightColor;

uniform sampler2D texture;

void main() {
    float l_distance = sqrt((gl_FragCoord.x * lightPosition.x) + (gl_FragCoord.y * lightPosition.y) + (gl_FragCoord.z * lightPosition.z));
    float l_value = lightIntensity / (l_distance / lightDistance);
    vec4 l_color = vec4(l_value * lightColor.r, l_value * lightColor.g, l_value * lightColor.b, l_value * lightColor.a);

    vec4 color;
    color = texture2D(texture, gl_TexCoord[0].st);
    gl_FragColor = l_color * color;
    //gl_FragColor = fposition;
}

Result produced by this code:

http://i1177.photobucket.com/albums/x349/Jpdiffy/ScreenShot2012-11-16at93614PM.png

With Ken's edit:

http://i1177.photobucket.com/albums/x349/Jpdiffy/ScreenShot2012-11-17at32733PM.png


texts: Can I switch off scenery elements on a 3D model?

texts:
I am using a 3D asset that has flat scenery elements (3D island with 2D bushes). [1] Having encountered a number of problems with this scenery [2] I want to deactive it (not visible, not collidable, keep the island itself). Is this possible?

[1]: The asset set in question is http://u3d.as/content/dexsoft-games/platformer-2/3Uo - the problematic objects are things like AmbientOcclusion/platform2_floating_*.fbx which (I can see visually) include bits like plant_9.fbx which are the misbehaving elements.

[2]: The bushes are collidable making it difficult to move around on the island. Specifically you can walk through them in one direction but not the other. On the suggestion of the creator, we unchecked "Generate colliders" on the island model, but doing that means the whole island has no collider and you fall through it! In addition, the alpha levels on the bushes stopped working, and they appear as rectangular elements (alpha values have been lost, replaced by gray/white) - I must've messed up the alpha value setting but can't figure out how to turn it back on. (If comments reveal these issues are fixable I'll expand them into separate questions.)


texts: My 2D Sprite/Diffuse material is not lighting when I start the game

texts:
I put a Sprite/Diffuse Material on my Player.

In the scene, before starting the game it looks ok (1st screenshot).

After starting the game it still works fine, but when I am starting to move the player on x-axis the it becomes black (2nd screenshot).

Why?

This is the script I use to transform the Player's position and scale:

void Update()
{
    Move();
    {
        float moving = Input.GetAxis("Horizontal");
        characterAnim.SetFloat("Speed", moving);
    }
}

void Move()
{
    if (Input.GetKey("right"))
    {
        transform.localScale = new Vector2(1, 1);
        transform.Translate(Vector2.right * speed * Time.deltaTime);
    }
    if (Input.GetKey("left"))
    {
        transform.localScale = new Vector2(-1, 1);
        transform.Translate(Vector2.right * speed * Time.deltaTime);
    }
    //    rb2D.AddForce(transform.up * 20);
}


texts: Unity UI - Value of text input (assigned with OnChange event) is always "one letter behind"

texts:
I am having a problem in unity setting up a search field.
I will post pictures down reggarding my problem but first let me quickly explain what is going on.

I have input element in my ui and i have working search function ready to use. The problem is that the string i feed my search function with is assigned from the inputfield text element value, which appears to be always one step behind.

What i mean is when I type "Wooden door" inputfield value is "Wooden doo".

It is quite annoying and I have no idea what is going on. Please point me into right direction.

Let me post the pictures with quick descriptions.

My UI:

My problem (item I am looking for is named "Wooden door"):

Second image of my problem (door item should not be present):

Finaly my ui settings and code:

Assigning value here:

My search control script:

using UnityEngine;
using UnityEngine.UI;
public class SearchControl : MonoBehaviour
{
public InputField inputField;
public Text searchInput;

private void Start()
{
    inputField = GetComponent<InputField>();
    searchInput = inputField.textComponent;
}

public void Search()
{
    if (searchInput == null)
    {
        Debug.LogWarning("Can't find search field.");
        return;
    }
    //TODO: text value is always one letter behind.
    string searchVal = searchInput.text;
    Debug.Log("Searching value: " + searchVal);

    CraftingManager.instance.RenderSearchedRecipes(searchVal);
}
}

I think there is some kind of character "verification" going on there and the real value of that text field is really one letter behind (since i assign it befor it gets verified). But that is not acceptable and I have no idea what can i do to avoid it. Thank you for any help!


texts: My question is in a similar vein to this question, I am creating a pre-mapped pathfinding solution much akin to how Ash Blue was for my 2D platformer-style game (in XNA). As part of the process, I have to be able to 'neighbor' nodes in the pathfinding algorithm. To be able to do this, I need a procedural manner to precalculate the maximum capabilities of motion from a given game object at a given location. I am having a difficult time with one specific aspect of this: I cannot, for the life of me, figure out how to test whether or not a game object will be able to successfully jump to a given platform from where they are standing. I know there's a way to express this in some manner of equation, but I cannot find what the proper equation would be, it's probably in the vein of projectile physics, but the answer eludes me. If anybody can shed some insight into the matter, I would be very grateful.


texts: (Unity) does NativeArray.Copy, or NativeArray.CopyTo, allocate any memory?

texts:
Is there any memory allocation if there are two arrays of the same size and same type? If they are already of the same length, and the values are of struct, when there's the copy, is any more memory used? Like, is it the same as if I did a for loop setting values from one array to the other?

Are they the same?
https://docs.unity3d.com/ScriptReference/Unity.Collections.NativeArray_1.CopyTo.html
https://docs.unity3d.com/ScriptReference/Unity.Collections.NativeArray_1.Copy.html

[What should I write here? Is this enough for a question?]


texts:
I am trying to figure out how to drag a sprite. I know when the mouse is being hovered, pressed, or released over a sprite. I don't know how to tell if the mouse is being pressed and moved at the same time. Every time I try to use event.type, I only get one mouse event back (SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP, or SDL_MOUSEBUTTONDOWN). I tried doing something like (pseudo-code):

if(event.type == SDL_MOUSEMOTION && event.type == SDL_MOUSEBUTTONDOWN && mouse_in_sprite && left_button_pressed) {
    /* Never goes in here */
}

However, it never goes inside that if statement because the event.type is never more than one of the above mentioned every frame (unless I'm doing it wrong).

In the picture below, I am trying to make it so the scrollbar on the right moves up and down like a normal scrollbar would when pressing the left mouse button on the sprite and moving the mouse up or down.

Unfortunately, I don't know how to proceed further than getting the mouse position when the mouse is pressed on the sprite (pseudo-code):

if (mousePressed(SDL_BUTTON_LEFT)) {
   currentMousePosition = getMousePosition();

   /* Do something with currentMousePosition.x, currentMousePosition.y */
}

Any help would be appreciated! Thank you!


texts: How do I duplicate a Box2d simulation, mid-simulation?

texts:
I want to serialize the state mid-game, send it over the network to an identical computer (same CPU, same OS, same binary), load it there, and have the two games run in tandem doing the exact same simulation, without one of them drifting off and going haywire.

In short: I want pop-in, pop-out networking support on my HIGHLY physics-intensive game, where sending object coordinates every few seconds is impossible, due to having thousands of objects, and many clients.

I tried this with Box2D, and saving an object's location/velocity/etc wasn't enough... there's internal state that's not accessible through any public methods.

My current workaround is to force EVERY client to save its entire worldstate and reload it from scratch, whenever a new player connects... but this is obviously bad practice, because it hangs the game for everyone whenever someone new connects. However, it works, with zero desynchronization.

So, anyone know of any other techniques that can help me? Or should I just kiss my project goodbye?


texts: Handling multiple pressed keys with KeyListeners

texts:
I'm making a game Applet with Java that uses KeyListeners to control a paddle (for a game like Breakout/Pong). My basic implementation goes like this:

public void keyPressed(KeyEvent e) {
    switch (e.getKeyCode()) {
        case KeyEvent.VK_LEFT:
            direction = "LEFT";
            break;
        case KeyEvent.VK_RIGHT:
            //repeat for the rest
    }
}
public void keyReleased(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_RIGHT)
        direciton = "";//paddle doesn't move
}

My problem is that when the user tries to change the direction of the paddle twice too fast (let's say you press left, then right and left again super fast), the paddle freezes for a split second, and continues to move along its direction.

I understand that the problem is the logic in my code, but I can't think of a better implementation. What am I missing?


texts: How can I display and sort a game server list by latency in a scalable manner?

texts:
If I have a game that allows players to self-host a multiplayer session which other players can join by browsing a game server browser to select a game I ideally want to be able to sort that list by latency, so that the lowest latency servers are top of the list.
I'm unsure about how to do this in a scalable manner, if for example there are 10,000 servers active at a given time, and 100,000 players looking for a game then it feels like every client receiving all 10,000 servers and pinging all 10,000 servers would generate excessive network traffic with 100,000 clients pinging each server on some regular interval; especially as some players may already be playing on some of these servers. This would mean each server receiving 100,000 ping requests on a regular basis.
I realise that I could reduce the servers sent back to the client from the master server list; it's unlikely any player would ever want to browse all 10,000 servers so I could reduce it to say, 200 servers or so as that is probably sufficient to find a suitable game. The problem here though is that I would still be unable to determine the 200 servers with the best latency without pinging all 10,000 from the client for all 100,000 clients browsing the server list to find that top 200 by latency.
I could register the latency between the host and the master server in the master server list, and return servers to the client whose latency most closely matches the latency between the client and master server list and hope that enough of these servers are close to the client; but the risk here is that a client that's 100ms from the master server and a server that's 100ms from the master server could either be next to each other (0ms apart) or could be opposite sides of the master server geographically so be 200ms apart. I could have regional master servers to mitigate some of the most extreme cases here, but it still feels like a very suboptimal solution.
Finally, there are other issues; if a self-hosted server needs NAT punch through for clients to connect, or a relay server, then any latency check would also require these things; this further complicates the problem; initiating NAT punchthrough just to check the latency to one of, say, 10,000 servers feels excessive.
Does anyone have any advice on how producing a scalable server list sorted by latency for each client can be achieved? This seems to be something a number of games have supported over the years so it must be possible.
Any suggestions, or advice as to how this problem is typically solved, or can be solved, would be greatly appreciated.


texts: How to use an array of y values to render a 2D top-down Java game?

texts:
I'm fairly new to the world of coding, and there's probably a simple solution here. I made this array (the actual one is more complex since it includes everything I have so far) for the y values of every object that needs to be rendered, but I don't know how to use it to keep track of which y values correspond to which object in order to draw them from lowest y value to highest y value.

int [] yValues = {deer.getY(), sprite.getY(), tree.getY()+150};
    Arrays.sort(yValues);

The deer just randomly walks around, and the player (sprite) is controlled by arrow keys. I added to the y value of the trees so that characters that walk around would stay behind them.

Right now I've hard-coded the layering, depending on when the sprite is in front of or behind the tree (hair and skin y positions are dependent on the y position of the sprite, which is why I didn't include them in the yValues array).

//Printing order
    if (sprite.getY() < tree1.getY()+150) { //if the player is behind the tree

        g2d.drawImage(deer.getImage(), deer.getX(), deer.getY(), this);

        g2d.drawImage(sprite.getImage(), sprite.getX(),
            sprite.getY(), this);
        g2d.drawImage(skin.getImage(), sprite.getX(),
                sprite.getY(), this);
        g2d.drawImage(hair.getImage(), sprite.getX(),
                sprite.getY(), this);

        //the tree is drawn after everything else
        g2d.drawImage(tree.getImage(), tree.getX(), tree.getY(), this);
    }

    if (sprite.getY() >= tree1.getY()+150) { //if the player is in front of the tree

        //the tree is drawn before everything else
        g2d.drawImage(tree.getImage(), tree.getX(), tree.getY(), this);

        g2d.drawImage(deer.getImage(), deer.getX(), deer.getY(), this);

        g2d.drawImage(sprite.getImage(), sprite.getX(),
            sprite.getY(), this);
        g2d.drawImage(skin.getImage(), sprite.getX(),
                sprite.getY(), this);
        g2d.drawImage(hair.getImage(), sprite.getX(),
                sprite.getY(), this);
    }

From here, how would I use the yValues array to order the drawing?

[I found this post helpful to what I'm trying to do] (Java Slick2d image depth/layering).


texts: Where can I find resouces for developing an "Intro to Game Development" class at a Community College?

texts:
I am an adjunct professor at a technical College in South Carolina.  I currently teach courses in .Net programming and Oracle PL/SQL.  We’ve noticed an influx of students who want to learn more about computer programming and game development in particular.   Their main interest stems from their experiences with video games.  I am a pretty good programmer and have done some simple 2D games in the past.

Now I have been asked to look at possibly developing an "Intro to Game Programming".  The state actually allows the topic to be covered as an accredited course, just hardly any of the schools offer or have faculty that can instruct in the class.
So, I am looking for advice/resources on how to structure the class.  My initial outline is the following.

I plan to use Visual Studio Express C# Edition with XNA Game Development.  The XNA platform is very popular and allows a familiar environment for students and it is FREE!  I am personally a fan of Torque, but my students will all have been introduced to Visual Studio (via prerequisites) by the time they take this class, and I believe Torque will incur extra fees for them if they want to take work home and work outside the lab.
Keep it simple – Input with Controls, 2D side scrolling, character and object animation,  pong type games, basic sound effects and simple collision detection problems.  Being an Intro class and students having to learn C# as they go, I can’t see trying to make this too intensive.

So, now the heart of my question – has anyone done this?  What is the best book to use to teach XNA in a class room setting?

Should we try to write from scratch at the very beginning or go with a basic working game and teach the parts and then have them modify and improve as the semester goes along?

I also feel I need to make it team oriented and make the teams compete with a final demonstration of their games to be voted/reviewed by random selection of students and faculty.

Also, does anyone know of a program/business partnership where I could possibly be lent or given free hardware to use?  Over 90% of my students are full financial aid (Cheraw, SC is very economically depressed) so I need access to game controllers, etc.  Also, the computers we currently have (and budgets keep getting trimmed ) currently run Windows XP and not looking to be upgraded for at least another 2 years.  So an opportunity to borrow some higher end machines would be great along with maybe and Xbox 360!

Also, I am open to using a platform other XNA, but I don’t want to get technically deeper than XNA – therefore going straight against DirectX with C++ is out of question.  Also, it has to be free at least for educational usage.


texts: graphical interface when using assembly language

texts:
I want to learn a framework to use in assembly. I know that's not possible without learning the framework in C first. So I'm thinking of learning SDL in C and then teach myself how to interpret the program and run it as assembly language code. Then I will have a window and some graphics routines to display the game while using assembly to code everything in. I need to spend some time learning SDL and then some more time learning how to code all those statements using assembly while calling C functions and knowing what registers returned calls use and what they leave etc.

My question is, is this a good way to go or is there something better to get a graphical window display using assembly language?


texts: GLSL - Drawing 2D UI elements over objects in 3D space

texts:
I posted a similar question earlier but I wasn't specific enough about what I wanted to do.

I have meshes being rendered in 3D space as expected. What I would like to do is display 2D billboarded UI elements over these objects at their 2D positions in screen space, facing the camera like billboards and with uniform scale regardless of the distance to the 3D mesh.

Right now I calculate gl_Position for the meshes like this:

gl_Position = projection * (vec4(position, 1.0) * (transformation * inverse(view)));

I've tried a couple things, like setting the upper 3x3 portion of the transformation * inverse(view) product to the identity:

mat4 bbTransformation = transformation * inverse(view)
bbTransformation[0][0] = 1.0;
bbTransformation[0][1] = 0.0;
bbTransformation[0][2] = 0.0;

bbTransformation[1][0] = 0.0;
bbTransformation[1][1] = 1.0;
bbTransformation[1][2] = 0.0;

bbTransformation[2][0] = 0.0;
bbTransformation[2][1] = 0.0;
bbTransformation[2][2] = 1.0;
gl_Position = projection * (vec4(position, 1.0) * bbTransformation)

but the final result is slightly offset if the camera is not looking directly at the object, and the 2D elements are still scaled with distance.

This is what I currently have:

And this is what I want (mocked):

How can I get the effect I want?


texts: How to choose between 2D sprites versus 3D models for a 2D game?

texts:
I wanted to know how to decide between using 2D vs 3D models for games.
What are the advantages/disadvantages of using 3D models versus 2D sprites in 2D games?


texts: setting the position in different resolution

texts: I have a normal game window which is 640*480, and everything is fine, but when I try to maximize the window, the objects translate to different positions on the screen, for example If I have a circle which is drawn at the center in the normal window, when I try to maximize it, it shifts away from the center of the screen. How do I adjust it so it draws at the center in both normal window and maximized window ?


texts:
I am working on a paint project and it's almost complete but I want it to behave like the ms paint , in which whenever we draw an object (rectangle ,line) it shows it on the screen while we are moving our mouse .
I implemented it for only one object i.e the window shows which object I am drawing but when I start drawing another object it wipes the previously drawn one
import pygame
pygame.init()
run = True
screen =   pygame.display.set_mode((400,400))
clock = pygame.time.Clock()
screen.fill((255,255,255))
down = None
while run == True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
           run = False

        elif event.type == pygame.MOUSEMOTION:
            motion = event.pos
            screen.fill((255,255,255))
            if down:
                pygame.draw.line(screen,(0,0,0),(down[0],down[1]),\
                    (motion[0],motion[1]))

        elif event.type == pygame.MOUSEBUTTONDOWN:
            down = event.pos

        elif event.type == pygame.MOUSEBUTTONUP:
            up = event.pos
            pygame.draw.line(screen,(0,0,0),(down[0],down[1]),(up[0],up[1]))
            down = None

    pygame.display.update()
    clock.tick(60)

I tried saving the data of the all previously draw objects in an array and then calling a function make(self,arr) to draw it again on the screen but it's very slow.
How can I draw the objects like i showed in  my program and still have other objects stay on the screen ?


texts: Limiting GIF animation rate to its frame delay in JME3

texts:
I've figured out how to render a GIF image using this library as follows:

@Override
public void simpleUpdate(float tpf) {
    if (bgFrameIndex > 0) {
        guiNode.detachAllChildren();
    }

    guiNode.attachChild(bgNodes.get(bgFrameIndex));

    if (bgFrameIndex < bgDecoder.getFrameCount() - 1) {
        ++bgFrameIndex;
    } else {
        bgFrameIndex = 0;
    }
}

where bgDecoder is a GifDecoder, bgNodes is an ArrayList of nodes that contain the GIF's frames, and bgFrameIndex is the current frame index to render. By default, the tpf (ticks per frame) variable is at around 0.01 seconds, when I want to limit it to the frame delay of the current frame without changing the FPS of the entire game. What's the best way to do this?

EDIT

My new code from the answer of @1000ml (I also fixed frame removal):

private float bgFrameDelay = bgDecoder.getFrameCount() > 0 ? bgDecoder.getDelay(bgFrameIndex) : 0;

@Override
public void simpleUpdate(float tpf) { // ticks per frame
     bgFrameDelay -= tpf;

     if (bgFrameDelay < 0F) {
         bgFrameDelay = bgDecoder.getDelay(bgFrameIndex) / 1000F;

         if (bgFrameIndex > 0) {
             bgNodes.get(bgFrameIndex - 1).removeFromParent();
         }

         guiNode.attachChild(bgNodes.get(bgFrameIndex));

         if (bgFrameIndex < bgDecoder.getFrameCount() - 1) {
             ++bgFrameIndex;
         } else {
             bgFrameIndex = 0;
         }
     }
 }


texts: Map Generation Biome - 3D Zonation Altitude/Temperature/Moisture

texts:
I'm working on an endless map generator and I have a question about biomes selection.

I already have all the work done to generate PerlinNoise (actually for map altitude and moisture) but every graph I found take only account of Temperature/Moisture. (Or sometime Latitude/Moisture but as i'm into an Endless map Latitude do not exist).

Example found on Google:

Questions

Do I can assume that height of the map represent the temparature ? So high level are always cold and under snow, but sea level are always desert.
Do I need another noise (for Temperature) and found a 3D table to select biome (I didn't found any) ??

Holdridge life zones

I also found a kind of 3D Zonation with Holdridge life zones but I don't see how the 3 axis works..

I don't see how to implement my 3 axis into this (Image (1)).

I also try (into Image (2)) to create a 3D version of it, but using triangular force me to handle High as Cold and Dry ?

So I think my real need is a simple 3D axis representing all cases between [0;1] (Image (3)) but I never saw stuff like that ??

Any ideas ?


texts:
I am using Unity 5.0.1.  I have created the asset bundle of a sprite by selecting the name "img.unity3D" from the dropdown and then running the script :

BuildPipeline.BuildAssetBundles ("AssetBundles");

It successfully creates the "img.unity3D" file and "img.unity3D.manifest" file for that sprite in AssetBundles directory.

Now, I am uploading the "img.unity3D" to my server and trying to download it through :

 WWW www = WWW.LoadFromCacheOrDownload(URL, 0);

as I need to save the image on the local storage also.  When I am trying to get the main asset from the asset bundle and casting it as sprite, its returning null.

AssetBundle imageBundle = www.assetBundle;
testSprite.GetComponent<Image>().sprite = imageBundle.mainAsset as Sprite;

But, it doesn't seem to work.

Am I uploading the right file "img.unity3d" or I also need to upload .manifest file on to the server.
Is there any thing that I am missing, because I tried uploading only sprite and tried to download it, I was able to cast that to a sprite but not the case with assetbundle.

Sorry for such a long post...!!!


texts: Input and output of a server side game using web sockets

texts:
I am having a look at redeveloping an old flash based top-down zombie shooter game I made in highschool so that it supports multiplayer using socket.io. My experience over the last 5 years has been mostly writing server-side code, so writing the game logic itself on the server isn't a huge concern. The places I am having trouble with due to my very limited experience with sockets specifically is:

What the most appropriate input and output should be to and from the server in a game context.
How much data is appropriate to send.

Off the top of my head, I imagine the process would look something like:

The server runs the game (using NodeJS).
Clients that connect send their input to the server (key presses, clicks, etc).
Those inputs are queued against the client ID on the server and interpreted to move their character or whatever it does.
The server sends back the updated position of the client as well as everything else around the client in the "world".

The last point is where I have the most doubts. Assuming a reasonable collection of objects in the world, I am not confident that sending through the position of everything every ~30ms to every client would be sustainable (though I really don't know what is sustainable with web sockets). Then again, maybe it actually is perfectly fine to do this.

Obviously I can limit the amount of objects by only sending ones who have actually been updated (so static objects would never come through, etc) but I am not sure whether that is necessary at all or whether that is something extremely crucial. I also don't see this working if we implemented something like everyone being able to fire 100s of projectiles (or some other massive collection of constantly updating objects).

Are there any general guidelines or common knowledge around how much data you would expect to see come through a web socket and how frequently? Am I way off the mark or would this work okay for a moderate amount of clients?

I realize this all sounds very broad so to try tighten it up a bit I am specifically interested in how much data is realistic to send through web sockets and how frequently. Any auxiliary information based on the above is a great addition.


texts: Check whether object is looking in between a minimum and maximum angle in 3d Space

texts:
What I want to accomplish is to check whether an object is looking in between a minimum and maximum angle in 3D space

for example if a Helicopter is looking to the right...

it would have to check whether its rotation vector is within a cone like shape

when, the heli's rotation vector is inside, the method returns true, but false otherwise. So in the scenario above, the method would return false.

The answer is fairly simple in 2D as all I have to do is check whether minAngle < heli rot angle < maxAngle or use dot product to check, but in 3D I have to look at 2 dimensions against the Y axis to start.

I could define a cone class and check whether a vector is projected from the origin, but it seemed too excessive as I dont need variables like cone length, start radius, & end radius. I feel like I'm missing something simple that involves a bit of playing around from xz to xz->y. Is it possible to accomplish something similar just by checking heli's rot orientation?


texts: Slaving OpenSceneGraph to an external time base?

texts:
I'm working on an OpenSceneGraph animation, and I want events in the animation to be synchronized to a time reference provided by my audio player (BASS or FMod).  Yes, this is a demo :) .  Which time do I set, and where?  Sync is more important than frame rate or continuity - if the audio rewinds, I want the visuals to rewind, too.  (To support GNU Rocket.)

I have looked at the forum posts and Google results, but haven't seen a clear answer for this use case.

FrameStamps have a frame number, a calendar time, a simulation time, and a reference time.  I think the simulation time is what I should change - is that so?
Is specifying a new simulation time as a parameter to frame() or advance() the right way to specify the time?  Will that work even if time moves backwards?


texts: Moving Unit Parallel to Mouse in TBS Game

texts:
I'm writing a basic Turn-Based Strategy game using Unity3D.  It's not grid-based.  I've come to the point where I'm coding unit movement, and I'm having trouble figuring out how far to move the units based on the mouse position.  The following image is what I want:

The unit should snap forward along the red vector; it will always move in the direction it's facing.  The reason I'm doing it this way is because I want the user to be able to see the result of their move, and I want to avoid some sort of GUI slider.  The blue vector represents the vector from the mouse to the target point.

So, to sum it up: how do I calculate the movement (red) vector, based on the unit and mouse positions?  Pseudo-code would be great!


texts:
I've been using unity to make 2d indie type games for a while now. However, i've tried to branch into different genres and unity cant do some of the things that i want it to do(although it is still very good).

I really want to make a game from scratch were i have complete control over what happens, although i wouldn't have the slightest clue were to start.

tldr what resources do you need to build a game from the ground floor. or more or less. what resources/software/libraries did most well made indies such as super meat boy, braid or limbo use.


texts: I am starting work on a new Android game and I haven't had any experience implementing physics before. I am trying to steer clear of external libraries such as box2d, not just because I think it is overkill for my project, but I also want to code it myself for the experience. I am more just interested in getting 1 ball to bounce around the screen and bounce off of objects in my world. The game is in 2D and I was just looking for some advice on where to start with ball physics? I know I will need gravity,  x/y velocities... etc. I know I need to calculate how high the ball needs to bounce based on how fast it hit the object, I also know I will need to calculate the correct angle that the ball needs to bounce at. Just hoping to get some ideas on a good place to start and things I will need to take into account.


texts:
Im making a game where real-time data is exchanged between server and clients, and I was using java UDP sockets straight up, but I reached a point where I actually need to know if a few specific packets do arrive or not, like RemoveObject, ChangeLevel etc. UDP alone isnt enough, I needed some reliability.

So i tried to implement a thin layer on top of UDP by following this great article: http://gafferongames.com/networking-for-game-programmers/

Still, although it's being great to learn low-level networking, its also very hard and I've grown tired, so i looked up for a good alternative and found Kryonet.

Kryonet is said to handle both UDP and TCP requests at the same time, by using two ports (although apparently a single port for both protocols can be used...).

My initial idea (which seems more logical for me) would be to send via UDP the packets with info about object state updates and other real-time dependent information, whilst using TCP for object creation, removal, state-changes or even eventually chat-messages.

Still, every example i saw until now only uses TCP even for real time games, which i find odd when every article i read about game networking strongly discourages such.

I also do not understand how UDP and TCP work at the same time since the article states:

  The problem is that since TCP and UDP are both built on top of IP, the
  underlying packets sent by each protocol will affect each other.
  Exactly how they affect each other is quite complicated and relates to
  how TCP performs reliability and flow control, but fundamentally you
  should remember that TCP tends to induce packet loss in UDP packets.

Please explain how is Kryonet supposed to be used on game networking and why it should be used in such way regarding common knowledge about both protocols.


texts: Locking or overriding game object scale property coordinates in inspector window

texts: I want to know if it is possible to lock or override the X and Y coordinates of the scale property in the inspector window so that changing one coordinate immediately changes the other and scrubbing through one coordinate changes the value of the other. If yes, how can it be done?


texts: LibGDX FrameBuffer no Transparency when drawing

texts:
I try to draw severeal Sprites to a FrameBuffer. The Sprites are PNGs with transparency. When I draw them directly to the screen it's fine. But when I draw on the FrameBuffer and then draw the resulting texture on the screen the transparent parts are cut out and the glBackground shines through. Any idea how to solve this?

Here is how I do it:

FrameBuffer fbo = new FrameBuffer(Format.RGBA8888, width, height, false);
Sprite fboTexture = new Sprite(frameBufferObject.getColorBufferTexture());
fboTexture.flip(false, true);

fbo.begin();
batch.begin();
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.draw(sprite1, 0,0);
batch.draw(sprite2, 0,0);
batch.draw(sprite3, 0,0);
batch.end();
fbo.end();

batch.begin();
batch.draw(fboTexture, 0,0);
batch.end();


texts: How to reduce server traffic for 100+ multiplayers game?

texts:
I'm working on fast-paced multiplayer game which has 100+ players in single session.

To sync entire game state to each player, server should send massive data if I did not any compression:

24(transform per object) * 100(total objects) * 100(total players) * 30(server update frequency) = 7.2MB/s !

This is completly unacceptable size. So I investigated someting technique for recuding packet size (like https://gafferongames.com/post/introduction_to_networked_physics/)

Maybe I can reduce data size of (transform per object), by using quantization, Y-axis only rotation and so on.

Also, there is chance to reduce (total objects) for specific player (ex, send only near or visible object for that player).

Reduced packet size example is (worst-case):

16(transform per object) * 30(visible objects per player) * 100(total players) * 30(server update frequency) = 1.44 MB/s !

I think this is still large for server! Is there any technique for more optimizing packet size?

Another question, if I sending large-block of state packet, should I split entire payload into small UDP packets for avoiding fragmentation? (application-level packet fragmentation and assembling is efficient?)

Thanks.


texts: Preventing character's movement if it won't fit(Unity2D)

texts:
I'm creating a pacman game copy and I set up my movement. But there's a problem. My character can try to go up whenever I press but in the original you cannot go if there's a wall above you or your character won't fit.

For example in this situation you can still go up but you'll bounce off wall. So my question is how to prevent character from movement if there's a wall or it won't fit there.


texts: How to rotate a triangle towards the point in Qt?

texts:
I have an issue with items rotating.

I have a point and a triangle which needs to be rotated with its apex point towards the taregt point. The right side of the picture represents how it is should to be, and the left side represents how it works. Red dashed arrows represent motion, the triangle moves along its arrow. Green dashed arrow represent rotation, the triangle should rotates along its arrow.

How do I do calculations:

calculating desired velocity aka direction

velocity(direction) = Vec2DNormalize(targetPoint - locationPoint) * maxVelocity;

calculating angles for target point and location point

float angleLoc = atan2(rect->location.y, rect->location.x);

float angleTarg = atan2(rect->target.y, rect->target.x);

rotating after subtracting angleLoc - angleTarg

rotate((angleLoc - angleTarg) * 100);

Here it is the source code.

ster.cpp

#include "steer.h"
#include <QPointF>
#include <QBrush>
#include <QPen>
#include <vector2d.h>
#include <QGraphicsPolygonItem>
#include <QPolygonF>
#include <QPointF>
#include <QGraphicsItem>
#include <QDebug>
#include <cmath>
#include <vector>
#include <QtWidgets>

void Steer::seek()
{
    //calculating desired velocity aka direction
    rect->desired = Vec2DNormalize(rect->target - rect->location) * rect->maxspeed;

    //calculating steering force
    rect->steer = rect->desired - rect->velocity;

    //if the steer force is bgger than maxforce
    rect->steer.Truncate(rect->maxforce);

    //adding to acceleration steering force
    rect->acceleration += rect->steer;

    //add to velocity acceleration which has steering force only
    rect->velocity += rect->acceleration;

    //if the velocity is bgger than maxspeed
    rect->velocity.Truncate(rect->maxspeed);

    //changing our position
    rect->location += rect->velocity;

    //reset the acceleration
    rect->acceleration *= 0;

    viewport()->repaint();
}

Steer::Steer(QGraphicsView *parent)
    : QGraphicsView(parent)
{
    scene = new QGraphicsScene;
    rect = new Vehicle;

    scene->setSceneRect(0, 0, 500, 500);

    polygon <<  QPointF(5.0, 0.0) << QPointF(-5.0, 0.0) <<  QPointF(0.0, 20.0);
    rect->triangle = scene->addPolygon(polygon);

    this->setScene(scene);

    timer = new QTimer(this);
    QObject::connect(timer, SIGNAL(timeout()), this, SLOT(seek()));
    timer->start();

    this->show();
}

void Steer::paintEvent(QPaintEvent *)
{
    QPainter painter(viewport());

    painter.setBrush(QBrush(Qt::green));
    painter.setPen(QPen(Qt::black));

    painter.save();

    //moving to position
    painter.translate(rect->location.x, rect->location.y);

    //calculating angles for target point and location point
    float angleLoc = atan2(rect->location.y, rect->location.x);
    float angleTarg = atan2(rect->target.y, rect->target.x);

    //rotating after substracting angleLoc - angleTarg
    painter.rotate((angleLoc - angleTarg) * 100);

    painter.drawPolygon(polygon);

    painter.restore();

    for(int i = 0; i < vec.size(); i++)
        painter.drawEllipse(vec[i].x() - 1, vec[i].y() - 1, 1 * 2.0, 1 * 2.0);
}

void Steer::mousePressEvent(QMouseEvent * click)
{
    point = mapToScene(click->pos());

    vec.push_back(point);

    rect->target.x = point.x();
    rect->target.y = point.y();
}

Here the whole project.


texts: Stencil buffer appears to not be decrementing values correctly

texts:
I'm attempting to use the stencil buffer as a clipper for my UI system, but I'm having trouble debugging a problem I'm running in to.

This is what I'm doing: A widget can pass a rectangle to the the stencil clipper functions, which will increment the stencil buffer values that it covers. Then it will draw its children, which will only get drawn in the stencilled area (so that if they extend outside they'll be clipped). After a widget is done drawing its children, it pops that rectangle from the stack and in the process decrements the values in the stencil buffer that it has previously incremented.

The slightly simplified code is below:

static void drawStencil(Rect& rect, unsigned int ref)
{
    // Save previous values of the color and depth masks
    GLboolean colorMask[4];
    GLboolean depthMask;
    glGetBooleanv(GL_COLOR_WRITEMASK, colorMask);
    glGetBooleanv(GL_DEPTH_WRITEMASK, &depthMask);

    // Turn off drawing
    glColorMask(0, 0, 0, 0);
    glDepthMask(0);

    // Draw vertices here
    ...

    // Turn everything back on
    glColorMask(colorMask[0], colorMask[1], colorMask[2], colorMask[3]);
    glDepthMask(depthMask);

    // Only render pixels in areas where the stencil buffer value == ref
    glStencilFunc(GL_EQUAL, ref, 0xFF);
    glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
}

void pushScissor(Rect rect)
{
    // increment things only at the current stencil stack level
    glStencilFunc(GL_ALWAYS, s_scissorStack.size(), 0xFF);
    glStencilOp(GL_INCR, GL_INCR, GL_INCR);

    s_scissorStack.push_back(rect);
    drawStencil(rect, s_ScissorStack.size());
}

void popScissor()
{
    // undo what was done in the previous push,
    // decrement things only at the current stencil stack level
    glStencilFunc(GL_ALWAYS, s_scissorStack.size(), 0xFF);
    glStencilOp(GL_DECR, GL_DECR, GL_DECR);

    Rect rect = s_scissorStack.back();
    s_scissorStack.pop_back();
    drawStencil(rect, s_scissorStack.size());
}

And this is how it's being used by the Widgets

if (m_clip)
    pushScissor(m_rect);

drawInternal(target, states);
for (auto child : m_children)
    target.draw(*child, states);

if (m_clip)
    popScissor();

This is the result of the above code:

There are two things on the screen, a giant test button, and a window with some buttons and text areas on it. The text area scroll box is set to clip its children (so that the text doesn't extend outside the scroll box). The button is drawn after the window and should be on top of it completely. However, for some reason the text area is appearing on top of the button. The only reason I can think of that this would happen is if the stencil values were not getting decremented in the pop, and when it comes time to render the button, since those pixels don't have the right stencil value it doesn't draw over. But I can't figure out whats wrong with my code that would cause that to happen.


texts:
I have a game with some ball and I want to make it bounce. I already have movement, gravity, collisions implemented, I only need to make it bounce. Thing is, using this code:

player.getVelocity().y *= Player.ENERGY_LOSS;
player.getVelocity().y = -player.getVelocity().y;

indeed it makes the ball bounce but obviously the .y will get to very small values causing the ball to 'vibrate' and never stop.

How can I 'clamp' this value? Let's say I just want the ball to bounce just 2 - 3 times?


texts:
I am trying to figure out why, at sharp cutoffs in geometry, some vertices seems to be culled for some reason.

I have a heightmap for demonstrating it like this

And this is the result I get

See the red rectangles where the geometry is just cut and the skybox is shown behind.

I am not quite sure where to start looking where the problem might be.
I know for a fact it's not colliding with the z-near value.
Any non-steep geometry is fine. Any pointers?

EDIT: at certain angles, re-orienting the camera ever so slightly changes things, like this


texts: Writing to multiple RenderTarget2D's from HLSL shader

texts:
I need to write to two render targets: one for colour and another for depth+normal (for post-processing).  I have a problem, though.  Both targets seem to be getting the value output by COLOR0, while the second should logically be getting the value from COLOR1.  What did I do wrong?

RT Initialization:

renderTarget = new RenderTarget2D(device, gameResolution.Width, gameResolution.Height, false, graphics.PreferredBackBufferFormat, DepthFormat.Depth24);
extraTarget = new RenderTarget2D(device, gameResolution.Width, gameResolution.Height, false, SurfaceFormat.Color, DepthFormat.None);

Using RTs:

Device.SetRenderTargets(new RenderTargetBinding(renderTarget), new RenderTargetBinding(extraTarget));

Relevant HLSL:

struct Pixel
{
    float4 Color : COLOR0;
    float4 Extra : COLOR1;
};

Pixel PS(Middle input)
{
    Pixel output;

    // perform other shader code

    output.Color = float4(totalDiffuse * matDiffuseColor * color.rgb + totalSpecular * matSpecularColor, color.a);
    output.Extra = float4(input.Position.z / input.Position.w, clippedNormal);

    return output;
}


texts: How can I communicate a Joystick with a SurfaceView?

texts:
I have two classes:

JoystickView (Extends View).
GameView (Extends SurfaceView): It will be updated by a Thread that call the onDraw Method.

Now, if I retrieve a direction by OnTouchEvent inside the JoystickView, how can send this information to the GameView? Can I use another thread for JoystickView and allow a communication between the thread of Joystick and the thread of the GameView? otherwise how can I do this?


texts: What is the procedure followed by game programmers for saving and resuming game state? like files/mappings. I want to save it for tower defense game and I am using unity3D game engine.


texts: Do I need to install any libraries or SDKs to use OpenGL?

texts: I am wondering if I have to install libraries for openGL programming or if I can already use header files from the core library. I am asking this because I went to the SDK and there is no Core library for OpenGL development. There is however a few libraries to choose from. I am new to this.. If you could please help clarify the subject for me that would be great.


texts: Is it possible to make/translate a 3d engine to ruby on rails?

texts:
I am looking to make a 3D FPS that runs inside web browsers. I looked into using WebGL, but it didn't seem far enough along into development. I decided on using RoR because Ruby was a language I knew.

I realize this may seem like a ridiculous question, but is there any way I can port/rewrite/whatever a game engine(Say for instance IrrLicht) to run inside Rails? Or for that matter, any other language on the web.


texts: XNA 4.0, FBX and Texture Loading Failures

texts:
I've been going through several tutorials on how to use XNA and understand a lot thus far.  I've got a screen, I've got 2D sprites working, got a shader system operational, so far so good.  Now I've hit a wall.

I'm attempting to load a 3D model (FBX Format) I've exported from 3DS.  My issue, is the texture system.  First, I'm trying to avoid embedding the textures directly into the FBX as I'll be reusing a lot of the textures for different things, no need to load multiple copies of the same texture.  I know my texture, even though not embedded, is making it to my XNA classes because I can see it inside the FBX (when saved as ASCII) and get a compiler error if I attempt to move the texture out of its original location.  I can also see it compiling the image during a rebuild.

However, if I attempt to render the object, no texture.  Loading code:

protected override void LoadContent()
{
    objModel = LoadModel("Models/OriginModel");
}

objModel is defined as a Model higher up in the cs file.

My display code:

foreach (ModelMesh mesh in objModel.Meshes)
{
    foreach (Effect currentEffect in mesh.Effects)
    {
        currentEffect.CurrentTechnique = currentEffect.Techniques["TextureNormalMap"];
        currentEffect.Parameters["World"].SetValue(objTransforms[mesh.ParentBone.Index] * worldMatrix);
        currentEffect.Parameters["View"].SetValue(viewMatrix);
        currentEffect.Parameters["Projection"].SetValue(projectionMatrix);
    }
}

I've stripped out the matrix transforms and such as they're not causing the issue.  TextureNormalMap is my shader I've written that displays a texture with a normal map.  This generates a black model.  If I however add...

metalTex = Content.Load<Texture2D>("Textures/brushedmetaltexture");

and

currentEffect.Parameters["ColorMap"].SetValue(metalTex);

where needed, I get the texture to display.  This is of course, the problem.  I have to include the texture in my Content system, causing the image to be compiled twice (which generates a warning..compiled once from the FBX, compiled once from Content).  More importantly, I would have to hand-texture all the models again inside the XNA system in order to get them to display, which is what I'm trying to avoid.  I've already textured them once in 3DS, do I really need to specify, inside XNA during object load, all the textures again?

So, any ideas on what I'm doing wrong here?  What magical step am I skipping?  Am I supposed to, somehow, figure out what the texture name is from the FBX file itself and get a pointer to the extracted image to feed into my Texture2D?  Is there a different object I should use that includes the texture from the FBX?  Do I need to bite the bullet and just go with embedding (which still doesn't work with the above code btw)?

I've been going off of tutorials as I mentioned, but this step seems to be missing, or am I just being daft?  I apologize if this seems trivial, but I just can't solve it.  Is there some step in the object loading process I'm missing?


texts:
I am working on a platformer game which includes music with beat detection. I am currently detecting beats by checking for when the current amplitude exceeds a historical sample. This doesn't work well with genres of music, like rock, which have a pretty steady amplitude.

So I looked further and found algorithms splitting the sound into multiple bands using FFT...  then I found the Cooley-Tukey FFt algorithm

The only problem I'm having is that I am quite new to audio and I have no idea how to use that to split the signal up into multiple signals.

So my question is :

How do you use a FFT to split a signal into multiple bands ?

Also for the guys interested, this is my algorithm in c# :

// C = threshold, N = size of history buffer / 1024
    public void PlaceBeatMarkers(float C, int N)
    {
        List<float> instantEnergyList = new List<float>();
        short[] samples = soundData.Samples;

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

        // Calculate instant energy for every 1024 samples.
        while (sampleIndex + nextSamples < samples.Length)
        {

            float instantEnergy = 0;

            for (int i = 0; i < nextSamples; i++)
            {
                instantEnergy += Math.Abs((float)samples[sampleIndex + i]);
            }

            instantEnergy /= nextSamples;
            instantEnergyList.Add(instantEnergy);

            if(sampleIndex + nextSamples >= samples.Length)
                nextSamples = samples.Length - sampleIndex - 1;

            sampleIndex += nextSamples;
        }

        int index = N;
        int numInBuffer = index;
        float historyBuffer = 0;

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

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


texts: How to stop a tap event from propagating in a XNA / Silverlight game

texts:
I have a game with Silverlight / XNA game where text and buttons are created in Silverlight while 3d is done in XNA.

The Silverlight controls are drawn ontop of the 3D and I dont want a click on a button to interact with the 3D underneath

So I have

private void ButtonPlaceBrick_Tap(object sender, GestureEventArgs e)
{
    e.Handled = true;

But my gesture handling on the 3d objects still runs even though I have set handled to true.

private void OnUpdate(object sender, GameTimerEventArgs e)
{
    while (TouchPanel.IsGestureAvailable)
    {
         // Read the next gesture
         GestureSample gesture = TouchPanel.ReadGesture();
         switch (gesture.GestureType)

How am I supposed to stop it from propagating?


texts: I think I have succeeded in making an aabb out of 6 quads in opengGL but how would i get it to stay with its centre-point at the centre-point of all objects. I know it is easy for one object how would I do it automatically for all objects?


texts:
I'm creating a cube in WebGL made of mirros that have to reflect the object inside of it.

At the moment I'm stuck because I don't understand the correct logic to implement to achieve the result.
I tried put a camera in every face of the cube in order to have a cubemap to apply. The problems come when I try to rotate the cube: I'm not able to make the cameras follow the rotation.

What's the correct logic to implement?

These images could give the idea of what I'm trying to do:


texts: In PhaserJS, how do I get a clicked Physics.P2 body's data?

texts:
I have a sprite with Phaser.Physics.P2 enabled, using a custom shape loaded with loadPolygon() from a .json file. I have also activated its debug and debugBody properties, so I can see the custom shape:

How could I collect the shape data information when I click on the debug shape?

For example, if I were to click the head of the sprite, can I get the polygon information from the click event?


texts: Matrix.CreateBillboard centre rotation problem

texts:
I'm having an issue with Matrix.CreateBillboard and a textured Quad where the center axis seems to be positioned incorrectly to the quad object which is rotating around a center point:

Using:

BasicEffect quadEffect;

Drawing the quad shape:

Left = Vector3.Cross(Normal, Up);
Vector3 uppercenter = (Up * height / 2) + origin;
LowerLeft = uppercenter + (Left * width / 2);
LowerRight = uppercenter - (Left * width / 2);
UpperLeft = LowerLeft - (Up * height);
UpperRight = LowerRight - (Up * height);

Where height and width are float values passed in (it draws a square)

Draw method:

quadEffect.View = camera.view;
quadEffect.Projection = camera.projection;

quadEffect.World = Matrix.CreateBillboard(Origin, camera.cameraPosition, Vector3.Up, camera.cameraDirection);

GraphicsDevice.BlendState = BlendState.Additive;

foreach (EffectPass pass in quadEffect.CurrentTechnique.Passes)
{
     pass.Apply();
     GraphicsDevice.DrawUserIndexedPrimitives
         <VertexPositionNormalTexture>(
         PrimitiveType.TriangleList,
         Vertices, 0, 4,
         Indexes, 0, 2);
}

GraphicsDevice.BlendState = BlendState.Opaque;

In the screenshots below I draw the image at Vector3(32f, 0f, 32f)

The screenshots below show you the position of the quad in relation to the red cross. The red cross shows where it should be drawn. It rotates around the red cross position.


texts: How can I make Network.RPC call a method with params object[]?

texts:
Why do I need to do this? The game I'm working on fully conforms to a component style design. Every component that a game object uses is placed on the object and is disabled/enabled based on it's state machine's current state. This means if I have two components that share a base class that has an RPC method, they won't work due to this:

"RPC function names should be unique accross the scene, if two RPC functions in different scripts have the same name only one of them is called when RPC is invoked"

http://docs.unity3d.com/ScriptReference/NetworkView.RPC.html

This means an arbitrary component will be the "this" of the RPC method that actually gets called. So, to fix this I've added a unique name to every component and have to do some relatively slow searching and reflection in order to have a safe RPC call. So, now every RPC call should go through my RPC method. This method simply serialises the parameters into a string and sends them to unity's RPC method.

This works great, except one tiny thing. Serialising the entire array results in Unity doing no serialisation in NetworkView.RPC. That's fine, except as far as I can tell, Unity's NetworkView.RPC method is the only thing in the universe that knows how to serialise a NetworkViewID properly.

So, serialising the whole array of objects isn't an option. So, I now I serialise them IF they're not a NetworkViewID, then send the entire object array to Unity, which it does interpret correctly:

protected void ComponentRPC( string methodName, RPCMode mode, params object[] args )
{
    object[]                serialisedObjects       = new object[args.Length + 2];

    serialisedObjects[0] = uniqueName;
    serialisedObjects[1] = methodName;
    for( int i = 2; i < serialisedObjects.Length; ++i )
    {
        if( args[i - 2].GetType() == typeof( NetworkViewID ) )
        {
            serialisedObjects[i] = args[i - 2];
            continue;
        }
        serialisedObjects[i] = base.Serializer.Serialize<object>( args[i - 2] );
    }

    // Serialise arguments and call our RPC method through Unity.
    networkView.RPC( "ComponentRPCNetwork", mode, serialisedObjects );
}

I also put the unique component name and method name in the array. The only problem now is, Unity won't put the objects it serialises into my params object[] parameter. The RPC method:

[RPC] private void ComponentRPCNetwork( params object[] args )
{
    // First we have to deserialise the method arguments.
    string              uniqueID                    = ( string )args[0];
    string              methodName                  = ( string )args[1];
    object[]            deserialisedArgs            = new object[args.Length - 2];
    for( int i = 0; i < deserialisedArgs.Length; ++i )
    {
        if( args[i + 2].GetType() == typeof( byte[] ) )
        {
            deserialisedArgs[i] = args[i + 2];
            continue;
        }
        deserialisedArgs[i] = base.Serializer.Deserialize<object>( ( string )args[i + 2] );
    }... // More stuff.

So, my question is, can I get Unity's NetworkView.RPC method to put it's serialised objects into this "args" parameter? If not, can anyone see anyway around this?

By the way I'm using Vexe's framework, so you might see unusual things like "base.Serializer" etc.


texts: How to choose what to use in Java: Enums or Objects?

texts:
I'm in a dilemma over using Enum Types or using class objects in that particular part of my java project.

Let's suppose I have an array where I constantly add and remove things from it, but I also render textures from that array via accessing the texture with an enum type from its class like:

public static Texture requestTexture(Type type){
    if(type == Type.One){
        return textureOne;
    }
}

// can be improved with hashmap

I wonder if I can use classes instead of enums? Will it slow down my performance since I will be constantly creating new objects and deleting them since they leave the stack, but on the other hand, it will be more cleaner and structured code?


texts: (GameMaker) Smooth scaling and transparency while zooming

texts:
My game has a zoom function. There is a man in a spaceship, we can see the interior of the room room from side on as the outside is totally transparent. When I zoom out I want the outside of the spaceship to become gradually less transparent and the window sprite to shrink to give the illusion of depth. When zooming the opposite will happen. With my current code the scaling and alpha changes are triggered when a the zoom factor is above or below 1.5.

My question is this - How can I make the scaling and alpha changes directly link to the zoom level so the change is smooth and directly correlates to the zoom value at all times, not just at a set point such as 1.5?

Thanks for your help, here is my code :

*****(Event: oWindow_Step_1)*****

    ///set up transparency & scaling

//make transparent to start
if oPlayer.zoom = 1
    {
    image_alpha = 0
    image_xscale = 1
    }

//if camera zooms out make window smaller and more opaque
if oPlayer.zoom > 1.5
    {
    image_alpha += 0.01
    image_xscale -= 0.03
    image_yscale -= 0.03
    }

//if camera zooms in make window bigger and more transparent
if oPlayer.zoom < 1.5
    {
    image_alpha -= 0.01
    image_xscale += 0.03
    image_yscale += 0.03
    }

//stop image_xscale exceeding 3
if image_xscale >= 1.5
    {
    image_xscale = 1.5
    image_yscale = 1.5
    }

//stop image_xscale being less than 1
if image_xscale <= 1
    {
    image_xscale = 1
    image_yscale = 1
    }

///set up transparency & scaling

//make transparent to start
if oPlayer.zoom = 1
    {
    image_alpha = 0
    image_xscale = 1
    }

//if camera zooms out make window smaller and more opaque
if oPlayer.zoom > 1.5
    {
    image_alpha += 0.01
    image_xscale -= 0.03
    image_yscale -= 0.03
    }

//if camera zooms in make window bigger and more transparent
if oPlayer.zoom < 1.5
    {
    image_alpha -= 0.01
    image_xscale += 0.03
    image_yscale += 0.03
    }

//stop image_xscale exceeding 3
if image_xscale >= 1.5
    {
    image_xscale = 1.5
    image_yscale = 1.5
    }

//stop image_xscale being less than 1
if image_xscale <= 1
    {
    image_xscale = 1
    image_yscale = 1
    }


texts: Change all boolean parameters of an Animator in Unity

texts:
How can I change all boolean parameters of an animator to false?

Here is a solution which I found:

foreach (AnimatorControllerParameter parameter in playerAnimator.parameters)
{
    playerAnimator.SetBool(parameter.name, false);
}

The problem with this solution is that I will get a warning in console if my parameter in Animator is not a boolean. I would not like to be getting that. So, I need somehow to being able to take only parameters of type boolean.


texts: Reimplemented steering seek behavior from PyGame to LÖVE is much slower than original

texts:
I'm learning about steering behaviors and watched this nice explanation tutorial - https://www.youtube.com/watch?v=g1jo_qsO5c4&feature=youtu.be with the source code available at https://github.com/kidscancode/gamedev/blob/master/tutorials/examples/steering/part01.py. The example app is written in python and PyGame and behaves like:

The main code parts of it are:

MAX_SPEED = 5
MAX_FORCE = 0.1

def seek(self, target):
    self.desired = (target - self.pos).normalize() * MAX_SPEED
    steer = (self.desired - self.vel)
    if steer.length() > MAX_FORCE:
        steer.scale_to_length(MAX_FORCE)
    return steer

def update(self):
    self.acc = self.seek(pg.mouse.get_pos())
    self.vel += self.acc
    if self.vel.length() > MAX_SPEED:
        self.vel.scale_to_length(MAX_SPEED)
    self.pos += self.vel
    # ...

I tried to reimplement this example in lua with Love2d framework and HUMP vector utility, source code is available at - https://github.com/voronianski-on-games/sandbox/blob/master/src/steering/seek_love2d/main.lua.

The code is pretty similar with the same constant values of MAX_FORCE and MAX_SPEED:

function Mob:new ()
  -- ...
  self.maxVelocity = 5 -- a.k.a MAX_SPEED
  self.maxSeekForce = 0.1 -- a.k.a MAX_FORCE
  -- ...
end

function Mob:seek (target)
  self.desired = (target - self.pos)
  self.desired:normalizeInplace()
  self.desired = self.desired * self.maxVelocity

  local steer = (self.desired - self.vel)

  if steer:len() > self.maxSeekForce then
    steer = steer:trimmed(self.maxSeekForce)
  end

  return steer
end

function Mob:update (dt)
  self.acc = self:seek(vector(love.mouse.getPosition()))
  self.vel = self.vel + self.acc * dt

  if self.vel:len() > self.maxVelocity then
    self.vel = self.vel:trimmed(self.maxVelocity)
  end

  self.pos = self.pos + self.vel * dt
  -- ...
end

But behavior is different. Square is much more slower in lua implementation though the values are the same:

What could be a problem? Or what is the difference that I couldn't notice?


texts: Positioning 2D (non-UI system) game objects

texts:
As an old Flash dev I'm slightly confused about how you position game objects on the screen in Unity since game objects have no width or height (only a scale).

Let's say I have a container gameobject that has several child game objects with sprite renderers representing tiles on them. If I set the container to x0, y0, the whole tile layout will extend from the screen center upwards and to the right.

What are the commonly used ways to position the game object so that it would be centered on the screen? I could calculate the width/height of my container but that would still not be very useful because the x/y coordinates work in a different scale than pixel (right?). E.g. my test screen is 640x1024 and to center my container (while running in the editor) I'd have to set x/y to -4.5. How does that make any sense?

Of course Unity's UI system would be a solution but I don't want to create the playfield with the UI system.


texts:
This has been asks at least a quarter dozen times, I know. This has a second part the others didn't. In my question I am looking towards a math function that can be used and inverted for finding exp/ levels.

From my reading, Runescape does: Exp for next level = (Previous Level XP + Previous Level XP * 10%)

What kind of math function could I look to to find your current level from a number of XP?


texts: How do I turn an image into a Box2D physics object?

texts:
I'm using Box2D for a Game Programming course, and I was wondering if it is possible to choose the best shape and size of shape for the rigidbody/fixture for a sprite based on its transparency.

I've tried to build with the idea of new content being easy to add (all data for enemies, terrain, etc. is stored in XML documents). Because of this, there will not be a new class for every enemy. This makes creating the fixture shapes difficult, since it has to be a generic solution but still map realistically to the sprite when the game is being played. The best solution I've come up with so far is to somehow figure out where the majority of the non transparent pixels are in the sprite and build the shape from that.

Does something like this exist? If not, would it be hard to implement?


texts: Push or Pull Input Data In the Game Logic?

texts:
In the process of preparing my game for networking I'm adding a layer of seperation between the physical input (mouse/keyboard) and the actual game "engine"/logic. All input that has any relation to the game logic is wrapped inside action objects such as BuildBuildingAction.

I was thinking of having an action processing layer that would determine what to do with the input. This layer could then be set up to either just pass the actions locally to the game engine or send it via sockets to the network server depending on whether the game was single- or multiplayer.

In network games it would make sense that the player's actions should be sent to the server, but should the game logic be pulling (polling?) the data through some sort of interface or should the action processing layer be adding the actions to an input queue in the game logic code?


texts:
Currently I have a playerWorld matrix which holds the position of my player, just a simple sphere. When I press a key to move the model, it does some crazy thing and flies off the screen really fast, and not even in the direction I want it to go.

    if (kbs.IsKeyDown(Keys.W))
        {
            playerWorld += Matrix.CreateTranslation(playerWorld.Forward * elapsed);
        }

Why is this happening? elapsed  is a float variable:

    float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

Here is the draw code, maybe it's being drawn wrong?

    public void Render(ThirdPersonCam cam)
    {
        foreach (ModelMesh mesh in playerModel.Meshes)
        {
            foreach (BasicEffect effect in mesh.Effects)
            {
                effect.View = cam.view;
                effect.Projection = cam.proj;
                effect.World = playerTransforms[mesh.ParentBone.Index] * playerWorld;
            }
            mesh.Draw();
        }
    }


texts:
So I'm writing a small game using Direct3D 9 and I'm using multitexturing for the terrain. All I'm doing is sampling 3 textures and a blend map and getting the overall color from the three textures based on the color channels from the blend map. Anyway, I am getting a massive frame rate drop when I sample more than 1 texture, I'm going from 120+ fps to just under 50.

This is the HLSL code responsible for the slow down:

float3 ground = tex2D(GroundTex, multiTex).rgb;
float3 stone  = tex2D(StoneTex, multiTex).rgb;
float3 grass  = tex2D(GrassTex, multiTex).rgb;
float3 blend  = tex2D(BlendMapTex, blendMap).rgb;

Am I doing it wrong ? If anyone has any info or tips about texture sampling or anything, that would be nice.

Thanks.


texts: How does a segment-based rendering engine (as in Descent) work?

texts:
As far as I know Descent was one of the first games that featured a fully 3D environment, and it used a segment based rendering engine.

Its levels are built from cubic segments (these cubes may be deformed as long as it remains convex and sides remain roughly flat). These cubes are connected by their sides. The connected sides are traversable (maybe doors or grids can be placed on these sides), while the unconnected sides are not traversable walls. So the game is played inside of this complex.

Descent was software rendered and it had to be very fast, to be playable on those 10-100MHz processors of that age. Some latter levels of the game are huge and contain thousands of segments, but these levels are still rendered reasonably fast. So I think they tried to minimize the amount of cubes rendered somehow.

How to choose which cubes to render for a given location? As far as I know they used a kind of portal rendering, but I couldn't find what was the technique used in this particular kind of engine. I think the fact that the levels are built from convex quadrilateral hexahedrons can be exploited.


texts: Calculate new coords of camera after a 90 degree rotation in an isometric 2D projection

texts:
I made a 2D isometric renderer. It works fine but now I want to show my scene from 4 different points of view (NE NW SE SW) but, on a 90° rotation, my camera cannot keep the center of my scene on screen.

What's working :

I calculate new projection of scene to match the new viewport (x y z in my world).
I reorganise part of my scene(chunk) to draw them in a correct order
I reorganise 'tiles' of 'chunks' to draw them in a correct order
I can keep the correct center with a 180 degrees rotation.

What's do not working :

I cannot find a correct translation to apply to my camera after a 90 degrees rotation.

What I know :

To keep the same center on a 180° rotation with my camera I have to do this :

camera.Position -= new Vector2(2 * camera.Position.X + camera.Width, 2 * camera.Position.Y + camera.Height);

Illustation of the problem :