texts: RPG - Accuracy Formula (HIT or MISS only)

texts:
I am creating the combat system of a simple RPG. The only two factors in this system are damage and accuracy.

Accuracy in this game simply means either the attacker HITS or MISSES. There is no partial damage or partial hits. The target has no chance of dodging the attack if the attacker HITS. A player's accuracy is represented with a percentage, e.g. 75% of the time the player will HIT.

In combat, the damage formula determines the damage inflicted on a target, but the damage will only be inflicted if the player HITS the target.

I have already created a damage formula; however, I do not know how to create a simple and practical accuracy formula. I have thought of this, but it's quite impractical because of how it will need to be manipulated if the player's accuracy improves/increases:

An array is filled (Player's accuracy)% with 1's, remaining percent with 0's
At random, one index of the array is chosen
If it's a 1, the player HITS; if it's a 0, the player MISSES

I have looked around this network at accuracy/hit or miss formulas but they involve other factors such as dexterity and evasion. I've also looked elsewhere online, but again the formulas involve other factors.

Is there a simple and practical formula to accomplish this?


texts: Appropriate database schema for heroes' skills in a Tower Defense game?

texts:
In a Tower Defense game, each hero (or character) has some skills. Each skill has some "chance of appearance" (CoA for short) when attacking enemies and if appeared it has some "hit accuracy" (i.e. hit on enemies) (HA for short) and has effects on the enemies (if hit by the skill) (EoH for short).
Examples:
Skill #1: Frost 1, CoA: 50%, HA: 100%, EoH: (1) slow enemy down for 4s and (2) yield 200 damage points.
Skill #2: Frost 2, CoA: 100%, HA: 50%, EoH: (1) make enemy frozen for 8s.
I first tried to breakdown skills into "atomic" effects and come up with tables as below:

All looks good?
But now we want to update Skill #1 a bit to make it more complicated:
Skill #1: Frost 1, CoA: 50%, HA: 100%, EoH: (1) slow enemy down by 40% for 4s and (2) yield 200 damage points. (Please pay attention to the 40% here!)
Or even coming up with more complicated skills:
Skill #3: Frost 3, CoA: 20%, HA: 100%, EoH: (1) frozen enemy for the first 4s then slow enemy down by 50% for next 4s and (2) yield 200 more damage points.
Skill #4: Frost 4, CoA: 10%, attack enemy 3 times continuously, each time: HA: 50%, EoH: (1) frozen enemy for the first 2s then slow enemy down by 50% for next 2s and (2) yield 400 more damage points.
Each effect now has more parameters to be specified -- which makes my current schema not fit anymore. Please help deal with this!


texts: Making objects larger than 1 tile in a pixel art tile map

texts:
I'm working on a pixel game, and started creating a little town to test some stuff.

My question is whether there is a way to create bigger objects without having to split them into several parts.

My grass tiles and similar are 16 pixels wide, but how do I build a house for example, I want to stay at 16 pixels with all objects but the house would be far too small this way.

I know I can build it by creating the parts separately, but is there an easier way?


texts: Why do I get these errors in VS when I use OGRE_NEW?

texts:
I am trying to get more experienced with Ogre 3D and I am following the basic tutorials on the website. All the code samples compile just fine.

The first time I encountered an "error" was in Basic Tutorial 3.

The code line where Visual Studio says something is not right is

mTerrainGroup = OGRE_NEW Ogre::TerrainGroup(mSceneMgr, Ogre::Terrain::ALIGN_X_Z, 513, 12000.0f);

Visual Studio compiles this line but it shows an ugly red line beneath it and on mouse hover it says

  #define OGRE_NEW new (__FILE__, __LINE__, __FUNCTION__) Error: no instance of overloaded 'operator new' matches the argument list" or if I mouse hover over Ogre::TerrainGlobalOptions() it says "Error: expected a type specifier

I searched on Google but couldn't find my answer. I got about a year C++ experience but that was mainly with the WinSock libary.

Thanks in advance.


texts:
New version of Unity is causing rather weird problems on Galaxy S device. The GUI starts to flicker, tear and disappear altogether at random in different screens. But this only happens on the second launch. The first launch after full uninstall works perfectly.

Normal(first launch):

Screenshot of the flickering(after first launch)

There are no errors in LogCat that clarifies the problem and this does not affect functionality of the app, only the GUI goes bananas. This happens on other Galaxy S devices too, not just mine. This also happens in my other projects, one which is smaller and one which is larger. But on other devices like Galaxy S2 and Motorola Xoom, there are no issues.

What could be the issue here?

P.S I have contacted Unity support, but have not heard from them


texts:
I am concerning a 3D Scroller game which is like Subway Surf or Temple Run. The thing I am confused about is their way of generating 3D environment. For example for 2D games like Flappy Bird, there is a camera and player which have fixed positions respect to the X axis. And the environment is being generated, moved into camera's viewport, and finally gets destroyed after getting out of viewport. I mean, player and camera does not move in general, the environment does.

Is this approach efficient by means of performance for 3D scrollers? Do they use a box which covers the camera's viewport, and when objects get out of the box, destroy them? Or do they create the environment via code as the player goes further, then make the camera follow the player and they are moving both? Is this a valid approach and what are the advantages or disadvantages of these implementations?

Thanks in advance!


texts:
As a hobby project I'm building a 2D game with a custom game engine in Android. Currently I can render a json map, and let the user interact with objects on the map. The game should be an open world map, with multiple maps. One of my current maps has a 150 x 150 tile pattern, with on every tile one or more objects. Thus, the map has 22.500, multiple layers, and more attributes. The player can edit objects (like fish in water object, plant seeds in soil, etc.), so every object needs to be stored separately. Some objects, like growing plants, need to be updated over time, even when the player is not playing the game.

My question is about efficiently saving and loading the game state. I think I need to store all the attributes of the maps, together with the objects, player progress, npc progress, and so on. Since this is a lot of data for a mobile device, I can't think of a good way to store this on the phone (or in the cloud).

I've tried the following:
- Store the entire game state in a serialized file. The parsing of this file took way to long while loading, and when one object's state changed, the whole game had to be loaded.
- Store every object in a sqlite database, with for every attribute a column. This was even slower than the first option, so not an option either.
- Store every object serialized as a blob in the database. This option wasn't much faster than the previous one.

I've been looking at ObjectBox, but in order to create the entity values for this database, I need to change a lot of reference values to ToOne<> or ToMany<> objects, which will take a lot of time and since I am using the map attributes to render the maps, the wrapping and unwrapping of the objects would cause (unnecessary) delay. (This is an assumption)

How do I save the game state without causing a 20-minute loading delay?


texts:
I am following the unity tutorial here and when i drag my environment into the Hierarchy everything i already lit up on my Game view, i noticed this was also the case in the Space Shooter tutorial that i followed before this but i ignored it. Does Unity5 automatically light up things for you if you don't have any lights? I tried setting the ambient Intensity to zero but it literally changes nothing. When i drag in the lighting prefab it also doesn't seem to do much because the scene was already lit up somewhat.

It is still dark but it isn't pitch black like it should be in the Game view.


texts:
I am currently creating a game in need of networking i.e. server and clients. I have basic experience with socket programming and am able to transfer data between two machines via UDP sockets using sdl_net. Now I would like to start building a game server and client for one of my current projects. Ive taken a look at https://gafferongames.com to help with packet compression and emulating a connection, however i am stumped from there on.

Because my game will be a real-time game, it constantly needs to be sending packets back and forth (perhaps at a set interval) to exchange data and check for timeouts. How do I structure my server? Should I have a thread constantly listening for clients packets and another broadcasting game states every time interval? Or should I stick to a single thread (If so how do I approach it)?

Simply put, I'm a little lost on how to properly make a efficient game server. Any help and explanation would be great!


texts: What's the difference between Textures and VertexTextures in XNA?

texts:
The GraphicsDevice class of XNA has the properties Textures and VertexTextures.

What is the exact difference? I don't really understand what MSDN tells me about this.

I usually use Effect parameters to pass textures to my HLSL shaders. What are the differences between these methods, which is faster?


texts: How to freeze rotation with a Rigidbody 2D?

texts:
So I am looking to freeze rotation in the Y axis on a Rigidbody 2D. I'm not sure how to set this in my code. This is what I have so far, can you point out my errors?

public class PlayerMovement : MonoBehaviour
{

    public float speed;
    public float height;
    GameObject Player;
    RigidbodyConstraints pos;
    Transform P;
    // Update is called once per frame

    void OnAwake()
    {
        Player = GameObject.Find ("Player");
        pos = RigidbodyConstraints.FreezeRotationY;
        Rigidbody2D. = pos;
    }

    void FixedUpdate ()
    {
        if (Input.GetButton ("Horizontal"))
        {
            transform.Translate (Vector3.right * speed * Time.deltaTime);
        }

        if( Input.GetButton("Left"))
        {
            transform.Translate (Vector3.left * speed * Time.deltaTime);
        }

        if (Input.GetButton ("Jump"))
        {
            transform.Translate (Vector3.up * height * Time.deltaTime);
        }

    }
}


texts: Do I need a company name to publish on Google Play?

texts:
I'm going to upload my Android mobile game on Google Play. But it seems like all games are developed by companies(such as Zynga, and King) and I don't see individual's names as developers. Do I need to register a company name officially? I think it costs a few hundred dollars... If I have to, how and where do I register? or instead of registering a company for a few hundred dollars, if I make a domain website that is named as my company name, would it provide me some protections?
Also, do I need to trademark my game's title as well?
Thanks!


texts: How to store and update data table on client side (iOS MMO)

texts:
Currently I'm developing an iOS MMO game with cocos2d-x. The game depends on many data tables (Excel file) given by the designers. These tables contain data like how much gold/crystal will be cost when upgrade a building (barracks, laboratory, etc.). We have about 10 tables, each have about 50 rows of data.

My question is how to store those tables on client side and how to update them once they have been modified on server side?

My opinion: use SQLite to store data on client side, the server will parse the Excel files and send the data to client with JSON format, then the client parse the JSON string and save it to SQLite file.

Is there any better method?  I find that some game stores CSV files on client side, how do they update the files? Could server send a whole file directly to client?


texts: Display a Message Box over a Full Screen DirectX application

texts:
In our custom assertion handler, I'd like to display a message box asking to see whether or not this failure can be ignored.  However, when our DirectX game is full screen, I can't get the MessageBox function to display above the full screen.

Note: The first parameter to MessageBox is the the HWND used to create the device, and it still does not work.

Is this even possible?


texts: AS3/Flash Game Dev: Looking for good & current step by step

texts:
Flash tutorials and examples have been around so long it is hard to know what sites to actually read for good, current AS3 game dev.

I'm looking for a good start to finish for flash game development, covering things such as:

Preloader (when to use, how to implement)
UI (AS3 only, no FLEX)
OOP architecture.  (I come from C++/C# world)

I'm just trying to create a simple game, sort of an "escape the room" style.


texts: What is the maximum width of a Facebook game page?

texts:
I read it was going to be changed to 520px, but I keep seeing pages that are new that are the older 760px width. Is it safe to build at the wider width still or should we be building at 520px?

Anyone know if you can still design for 760px width? If not, what's the new width?


texts: Data model design using Core Data and Spritekit

texts:
I have a entity called Item, and every item can have two or three bonuses...

What would be a good model design in this situation. I can think of something like:

To have many optional attributes inside Item entity i.e.

(Item)

fire_rate_bonus
energy_bonus
damage_bonus
health_bonus
some_other_bonus

And then when creating an item, I would set the values for appropriate bonuses and rest of attributes will be set to null.

I find that this approach solving my problem, but is there some other/better/efficient way? If you need more info about this, I will update my question. Thanks in advance...

EDIT:

Doing like above in my case will do the job, because I don't have much possible bonuses. But let's say there is a lot of possible bonuses, and an item can have only few bonuses. Then I think this method could be overkill because:

Item entity will have too much unused attributes.

What I can think of (I know that Core Data is not relational database system, but I like to think in relational way) is to make new entity called Bonus with relationship between Item entity (one Item can have many bonuses) with attributes :

bonus_name, bonus_modifier or something like that.

And then when creating an Item just assign appropriate bonuses to it. I hope this make some sense.


texts:
I'm trying to implement a radiosity processor. I'm aware of many places online to find information about radiosity. I found a great source on NVidia's website is  GPU Gems - Chapter 39 . On this page they talk about Hemispherical projection. I've implemented a projector that will place mesh 'vertices' on a unit hemisphere...the problem is that the rasterizer only linearly interpolates between vertices along an edge...

...is there a way to adjust the method of interpolation?

Here is shader code for hemispherical projection...it does place the objects correctly, however, the edges between the vertices are straight...when true hemispherical projection would create rounded edges...

float4x4 mW;
float4x4 mV;
float4x4 mP;
float4x4 mOrtho;
float2 vNearFar;
static const float PI = 3.14159265f;

texture g_TextureDiffuse;
sampler g_SamplerDiffuse = sampler_state
{
    Texture = <g_TextureDiffuse>;
    MinFilter = Point;
    MagFilter = Linear;
    MipFilter = Linear;
    AddressU = Clamp;
    AddressV = Clamp;
};

struct VS_IN
{
    float4 Position : POSITION0;
    float3 Normal : NORMAL0;
    float2 UV : TEXCOORD0;
};

struct PS_IN
{
        float4 Position : POSITION0;
    float3 Normal : TEXCOORD0;
    float2 UV : TEXCOORD1;
    float4 Pos2 : TEXCOORD2;
};

PS_IN VS( VS_IN input )
{
    PS_IN output = ( PS_IN )0;

    float4x4 mWV = mul( mW, mV );
    float4x4 mWVP = mul( mWV, mP );
        half4 vPos = mul( input.Position, mWV );

    half3 vHemi = normalize( vPos.xyz );

    half3 fNearFar = vNearFar.y - vNearFar.x;

    output.Position.xy = vHemi.xy * fNearFar;
    output.Position.z = ( vPos.z / ( vNearFar.y - vNearFar.x ) );
    output.Position.w = fNearFar;
    output.Pos2 = output.Position;
    output.Normal = mul( input.Normal, mWV );
    output.UV = input.UV;
    return output;
}

float4 PS( PS_IN input ) : COLOR0
{
    //float2 uv = input.UV - 0.5;
    //float z = sqrt( 1.0 - input.Pos2.x * input.Pos2.x - input.Pos2.y * input.Pos2.y );
        //float a = ( z * tan( ( PI / 2 ) * 0.5 ) );
        //return tex2D( g_SamplerDiffuse, ( uv * a ) + 0.5 );

    float4 diffuse = tex2D( g_SamplerDiffuse, input.UV );
    return diffuse;
}

technique Render
{
    pass Pass0
    {
        VertexShader = compile vs_2_0 VS();
            PixelShader = compile ps_2_0 PS();
    }
}

Here is screenshot:

It may be difficult to tell, but the cube has two faces( triangles ) per side( 6 sides, 12 faces ). From the picture you may be able to see the problem with flat edges...this problem is well documented...I'm trying to avaoid having to render 5 different images( hemicube ) to approximate a hemisphere...I'm mostly interested in hearing about methods of implementing a hemisphere...I also tried( to no avail ) to write a pixel shader that would warp the final( post scene render ) image. I didn't get great results...

...it also just came to me that I don't necessarily need a render result for computing the form factor...just the area that the projected object consumes within the area of the hemisphere base...

...any thoughts are appreciated!

... here is a screenshot of the cube subdivided...much better...still not accurate


texts: Unity: Object is underneath another object but shouldn't be

texts:
I have a simple collision detection program. The red object is controlled by the user and the yellow object is always moving up and down:

However, when the objects are supposed to collide, the red object ends up being underneath the yellow object. I wrote code that should destroy the red object on collision. This is a 2D game project, so I'm not sure how that works. They both have 0 set value for Order In Layer field.

Movement code for red object:

using UnityEngine;
using System.Collections;

public class Movement : MonoBehaviour {

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        //GetKeyDown checks if a button is clicked, but GetKey checks if a button is held down.

        //LEFT
        if (Input.GetKey (KeyCode.LeftArrow))
        {
            transform.Translate(-1 * Vector2.right);
        }

        //RIGHT
        if (Input.GetKey (KeyCode.RightArrow))
        {
            transform.Translate(Vector2.right);
        }

        //UP
        if (Input.GetKey(KeyCode.UpArrow))
        {
            transform.Translate(Vector2.up);
        }

        //DOWN
        if (Input.GetKey(KeyCode.DownArrow))
        {
            transform.Translate(-1 * Vector2.up);
        }
    }
}

Movement code for yellow object (contains collision event):

using UnityEngine;
using System.Collections;

public class EnemyMovement : MonoBehaviour {

    private bool moveUp;

    // Use this for initialization
    void Start () {
        moveUp = true;
    }

    // Update is called once per frame
    void Update () {

        if(transform.position.y == 30)
        {
            moveUp = false;
        }
        else if(transform.position.y == -30)
        {
            moveUp = true;
        }

        if (moveUp)
        {
            transform.Translate (Vector2.up);
        }
        else
        {
            transform.Translate (-1 * Vector2.up);
        }
    }

    void OnCollisionEnter (Collision col)
    {
        if(col.gameObject.name == "player_character")
        {
            Destroy(col.gameObject);
        }
    }
}

Also, I'm a complete newbie with Unity, so sorry if I'm asking something that should be obvious.


texts: How to randomly rotate a D20 Dice in Unity?

texts:
I'm working on a Dice Application in Unity that involves randomly rotating a dice model on instantiation and then dropping it. But in order for this application to be useful I need to guarantee that the Dice Roll is close enough to random to be used for a live tabletop game. The problem I'm getting is that after some testing the dice rolls are not random at all.

Here's some pictures of a a D20 I'm working with as it looks at instantiation.

Bottom view:

Top view:

Side view 1:

Side view 2:

Side view 3:

My first attempt at randomizing the dice rolls was to use this code:

m_Instance.transform.Rotate(UnityEngine.Random.Range(0.0f, 360.0f), UnityEngine.Random.Range(0.0f, 360.0f), UnityEngine.Random.Range(0.0f, 360.0f));

But after 250,000 test rolls, the data shows that it's almost twice as likely to land on a side face than it is the top or bottom faces

After doing some digging, I found a recommendation to use this code instead:

m_Instance.transform.rotation = Quaternion.Euler(UnityEngine.Random.Range(0.0f, 360.0f), UnityEngine.Random.Range(0.0f, 360.0f), UnityEngine.Random.Range(0.0f, 360.0f));

Which gave me the exact opposite results, where faces on the top and bottom of the dice were suddenly twice as likely as those on the sides.

So my mad-scientist approach to this problem currently is to randomly pick between the two rotation methods. So that way it's randomly decided if one face will be twice as likely as another.

int randomRange = UnityEngine.Random.Range(0, 2);
    if (randomRange == 1)
    {
        m_Instance.transform.Rotate(UnityEngine.Random.Range(0.0f, 360.0f), UnityEngine.Random.Range(0.0f, 360.0f), UnityEngine.Random.Range(0.0f, 360.0f));
    }
    else
    {
        m_Instance.transform.rotation = Quaternion.Euler(UnityEngine.Random.Range(0.0f, 360.0f), UnityEngine.Random.Range(0.0f, 360.0f), UnityEngine.Random.Range(0.0f, 360.0f));
    }

Which is getting me close, but not quite perfect.

But it's not quite close enough for my liking as some faces like 10 seem favored by both methods. So my question is: is there something wrong with my code that's making the rolls not as random as I'm imagining? And if not, is there a way of rotating a dice in Unity such that the result of the rotation is suitably random enough to be used in a potentially professional setting?

EDIT: Thanks for the response DMGregory! That's definitely looking better, but I'm still seeing that 10 and 11 are favored sides after a million test rolls. with both getting a > '5.8' percent chance of landing there. Perhaps there's something wrong with my implementation of your code?

public void RandomizeDice()
{
    m_Instance.transform.rotation = UniformRandomRotation();
}

Quaternion UniformRandomRotation()
{
    float x0 = UnityEngine.Random.value;
    float theta1 = UnityEngine.Random.Range(0f, Mathf.PI * 2f);
    float theta2 = UnityEngine.Random.Range(0f, Mathf.PI * 2f);
    // Make this theta2 in the range (0, PI * 1) if you want w > 0

    float r1 = Mathf.Sqrt(1f - x0);
    float r2 = Mathf.Sqrt(x0);

    return new Quaternion(
        Mathf.Cos(theta2) * r2,
        Mathf.Sin(theta1) * r1,
        Mathf.Cos(theta1) * r1,
        Mathf.Sin(theta2) * r2);
}

public void UnRandomizeDice()
{
    m_Instance.transform.rotation = Quaternion.Euler(270, 270, 270);
}


texts: Calculating a matrix to have the model follow terrain

texts:
So I've been messing around with 3D graphics in Java (using lwjgl), and I've hit a bit of a roadblock. I have a heightmap and a cube, and I want to find a way to have the cube rotate to follow the terrain smoothly. At the moment, the cube can rotate freely around the y axis (up is 0,1,0), and it can move directly in the direction it's facing.

Here's my idea: find the plane formed by projecting the bottom corners of the cube onto the terrain. That's the plane that I want to rotate my cube's bottom face into, so I took a cross product with the up vector and the normal vector of that plane. Then I took the angle between the two, and calculated an axis-angle rotation matrix around that plane. I mulitplied the y rotation matrix by that matrix, and used that as my model matrix:

    Matrix4 upTransform = Matrix4.createRotateY(yrot);
    // calculate plane of cube
    Vector3 bl = new Vector3();
    bl.x -= SCALE / 2;
    bl.z -= SCALE / 2;
    bl = upTransform.transform(bl);
    bl.y = game.getMap().getY(position.x + bl.x, position.z + bl.z);
    Vector3 tl = new Vector3();
    tl.x -= SCALE / 2;
    tl.z += SCALE / 2;
    tl = upTransform.transform(tl);
    tl.y = game.getMap().getY(position.x + tl.x, position.z + tl.z);
    Vector3 br = new Vector3();
    br.x += SCALE / 2;
    br.z -= SCALE / 2;
    br = upTransform.transform(br);
    br.y = game.getMap().getY(position.x + br.x, position.z + br.z);
    Vector3 normal = Vector3.cross(Vector3.diff(br, bl),
                                   Vector3.diff(tl, bl)).normalize();
    // calculate rotation axis
    Vector3 axis = Vector3.cross(normal, up).normalize();
    // calculate angle between plane of cube and plane of texture
    float angle = (float)Math.acos(Vector3.dot(up, normal));
    // calculate rotation
    Matrix4 terrainTransform = new Matrix4().setRotate(axis, angle);
    Matrix4 rot = Matrix4.multiply(upTransform, terrainTransform);

game.getMap().getY(x, z) returns the height of the map at the x,z coordinate provided. Vector3.diff(a, b) returns a - b, and Matrix4.multiply(A, B) returns A * B.
My issue is that the cube rotates weirdly and has strange shear effects.
Does anyone have comments on my general approach, or on my implementation? I'm really not sure what to do here, as this is pretty much where my linear algebra knowledge reaches its limits.


texts: Creating a unit selection box in Unity (2D)

texts:
I've been trying to get my head around how to create a selection box for a selected unit in a 2D top-down type game. When you click on a unit, a small box would appear around that unit based on some sort of box-size.

I do not know/understand how to either calculate the size that box needs to be, draw the box (have an object under the game object that is sized appropriately with the selection box texture?) or how to make the selection box adjust it's size/shape like in this gif: http://i.imgur.com/xY7XW6C.gif

I don't expect anyone here to hand feed me what I need to use, but some idea of how to go about doing this in Unity (starting from the smallest, and most simple thing, like just making the box) would be very much appreciated.

Thanks!


texts:
I am trying to move my character to point that taken from mouse position.

here is my code:

private Vector3 hittedPoint=Vector3.zero;

 if (Input.GetMouseButtonDown (0)) {
             Ray ray = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>().ScreenPointToRay(Input.mousePosition);
             RaycastHit hit;

         if (Physics.Raycast(ray, out hit)) {
             //get object
             GameObject hittedObject=hit.transform.gameObject;

             if(hittedObject==GameObject.FindGameObjectsWithTag("Ground")[0]){

                 hittedPoint= new Vector3(hit.point.x,transform.position.y,hit.point.z);
                 //hittedPoint = transform.TransformDirection (hittedPoint);

             }
         }
     }

             if (hittedPoint != Vector3.zero) {
                 float delta = (transform.position - hittedPoint).magnitude;
                 if (delta > 5) {
             controller.Move (hittedPoint*Time.deltaTime);
             Debug.Log (transform.position);
                 } else {
                     hittedPoint = Vector3.zero;
                     }
             }

The problem is that my object moves according to its first position at the scence. For example if I move character towards right then towards forward; at second movement it goes diagonal. It is like it makes its movements according the first position of it in scence.

The second problem is; i couldn't find efficient method for stopping movement when character reaches the point. If I decrease delta; character skips the point and if I increase it, character stops to early.


texts:
I'm working on an editor where one important feature is to save and load changes (all type of changes like adding and removing objects and their components and components property values)

I want to know there isn't a Unity solution for that and I have to make a data format to save all of them on a string and load all of them? As I searched there is class serialization solutions that works like I said and has its own difficulties. Is there any thing or asset that performs all of this simply?


texts:
I've got a game situated in space, and I'd like to issue movement orders, which requires pathfinding. Now, it's my understanding that A* and such mostly apply to trees, and not empty space which does not have pathfinding nodes. I have some obstacles, which are currently expressed as fixed AABBs- that is, there is no unbounded "terrain" obstacle. In addition, I expect most obstacles to be reasonably approximable as cubes or spheres.

So I've been thinking of applying a much simpler pathfinding algorithm- that is, simply cast a ray from the current position to the target position, and then I can get a list of obstacles using spatial partitioning relatively quickly. What I'm not so sure about is how to determine the part where the ordered unit manoeuvres around the obstacles.

What I've been thinking so far is that I will simply use potential fields- that is, all units will feel a strong repulsive force away from each other and a moderate force towards the desired point. This also has the advantage that to issue group orders, I can simply order a mid-level force towards another entity. But this obviously won't achieve the optimal solution.

Will potential fields achieve a reasonable approximation given my parameters, or do I need another solution?


texts: Box collider don't catch mouse button press event

texts:
I have a cupboard with 2 colliders - one for cupboard and one for it's box. When I press on the box, I want to open/close it. It worked fine, but now by some reason it only work when I press on the edge on the box. When click on the center, it don't work.

Video: https://youtu.be/OozsAi7KNzs

Here is the code, which play animation (open/close cupboard), when I press on the box:

public Animation[] animations;
public string[] animationName;
public bool playOneDirection;   // should revert animation speed after second playing?
public AudioSource myAudioOpen;
public AudioSource myAudioClose;

private bool isDoorClosed;
private bool isAimationReadyToPlay = true;
private Collider thisCollider;

public void Start()
{
    thisCollider = GetComponent<Collider>();
}

void Update ()
{
    if (Input.GetButton("Fire1"))
        if(DoPlayerLookAtButton() && isAimationReadyToPlay)
            OpenCloseDoor();
}

bool DoPlayerLookAtButton()
{
    RaycastHit _hit;
    Ray _ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0));
    bool isHit = Physics.Raycast(_ray, out _hit, 1.5f);

    if (isHit && _hit.collider == thisCollider) return true;
    else return false;
}

public void OpenCloseDoor()
{
    if (!isDoorClosed) // Play animation with normal speed
    {
        myAudioOpen.Play();
        for (int i = 0; i < animations.Length; i++)
        {
            animations[i][animationName[i]].speed = 1.0f;
            animations[i].Play();
        }
    }

    if(playOneDirection)
        return;

    if (isDoorClosed) // Play animation with revert speed
    {
        myAudioClose.Play();
        for (int i = 0; i < animations.Length; i++)
        {
            animations[i][animationName[i]].speed = -1.0f;
            animations[i][animationName[i]].time = animations[i][animationName[i]].length;
            animations[i].Play();
        }
    }

    StartCoroutine("DelayBetweenAnimations");
    isDoorClosed = !isDoorClosed;
}

IEnumerator DelayBetweenAnimations()
{
    isAimationReadyToPlay = false;
    yield return new WaitForSeconds(0.5f);
    isAimationReadyToPlay = true;
}


texts: LibGdx Sound start to give an error after loading GameScreen multiple times

texts:
I have a LibGdx game, where the user taps on the screen, and a Sound will play. When the user taps on the screen, a texture will "fire" another texture as a missile, and can hit a target, when this target "dies", another sound will play.

I use these two Sounds often in the game, Shooting Sound, and Hit Sound.
When I load the game, everything works fine - the sound doesn't get an error when I load multiple instances of the Sound/Textures on level 1 - so it doesn't seem to be related to memory, because this error can appear when I use a lot less instances of sound/textures, but when I have loaded the "game screen" more times, it starts to appear.

The error is only related to two sound-files, one when the user taps the screen, and the other when the "target" dies. So it does only happen when I load Sounds a lot of times.

The problem only occurs when I go to higher levels, and load the game screen more times. I load the same game screen over and over, only with more instances of "targets".

Error:

W/SoundPool﹕ Sample was not loaded. Waiting for 30ms.
W/AudioTrack﹕ AUDIO_OUTPUT_FLAG_FAST denied by client
com.mygdx.game.android E/AudioTrack﹕ AudioFlinger could not     create track,     status: -12
com.mygdx.game.android E/SoundPool﹕ Error creating AudioTrack

I load my Sound like this:

 Sound playDeadSound;
 public void playDeadSound(){
 soundDead = Gdx.audio.newSound(Gdx.files.internal("dead.ogg"));
 soundDead.play();
 soundDead.dispose();
  }

Things I have tried

To instantiate the Sound file in the create method, and then use the
same object over and over.
I have tried to call soundDead.resume(); instead of play(); to load
the sound.
I have tried to re-sample my audio to 48KHz, and to the lowest (which
was around 5-8KHz IIRC).
I have tried to start out with 40 targets, and I get no errors, and I
have tried to start out with 5 targets, and errors start appearing
when I go a few levels higher and the targets are 10-15.
I have tried to remove all other sounds except one of the Sounds that
creates the error (Shooting Sound/Hit Sound).
I have tried to stop and then dispose the sound, and then create it when I call it.
I have tried to have 2 sound files, and then call them one after
another, so they doesn't get used at the same time.

The files are 5KB big each, and around 1 second long.
Any ideas on what could cause this error? Thanks!

Solution:

The problem was that I reloaded the Sound over and over when I started a new level, hence why the problem never occured when I was at level 1. The problem got fixed when I used the same sound during the whole app's lifetime. A big thanks to Alesegdia for coming up with the answer.


texts: Pong paddle algoritm - How to know the direction of the ball when the paddle is at bottom

texts:
I hope you can understand my question! I'll try to be very clear.

Watching a pong tutorial (it was originally written in Javascript but I made the game in Python) The developer used an algorithm to determine, depending on which part of the paddle the ball hit, the ball velocity changed.

As you can see, if the ball hits more towards the bottom or top of the paddle, the angle in which it bounces gets larger, and if it hits closer to the middle, the angle becomes narrower.

Here is the algorithm and it works (Check code comments):

player_interesected_ball = detect_collision(ball, player) #It's a function that just detects if two rectangles collided
if player_interesected_ball :
    offset = (ball.y + ball.s - player.y) / \
             (player.height + ball.s) # ball.s is the ball size like 10px it means that is 10px wide and 10px high
    phi = 0.25 * math.pi * (2 * offset - 1)

    ball.vel_x *= -1
    ball.vel_y = ball.speed * math.sin(phi)

This code works when the paddle is placed on the Right or Left side of the screen but I want to know what should I change in these values to make it work when the paddle is placed on the bottom of the screen.

Like this:

:) Thank you before hand!


texts:
I'm creating a bullet shooter much in the style of Touhou. Right now I want to have a very simple circular shot being fired from the enemy.

However, the spacing is very uneven, which isn't very good if you want to survive.

The code I'm using is this:

private function shoot() : void
{
    const BULLETS_PER_WAVE : int = 72;
    var interval : Number = BULLETS_PER_WAVE / 360;

    for (var i : int = 0; i < BULLETS_PER_WAVE; ++i)
    {
        var xSpeed : Number = GameConstants.BULLET_NORMAL_SPEED_X * Math.sin(i * interval);
        var ySpeed : Number = GameConstants.BULLET_NORMAL_SPEED_Y * Math.cos(i * interval);

        BulletFactory.createNormalBullet(bulletColor_, alice_.center, xSpeed, ySpeed);
    }

    canShoot_ = false;
    cooldownTimer_.start();
}

I imagine my mistake is in the sin &  cos functions, but I'm not entirely sure what's wrong.


texts: Database vs classes in a rpg character sheet app for android

texts:
i'm trying to develop an android app to handle character sheets in roleplay games like D&D and Pathfinder.

My target is to avoid calculations of bonuses by the player who only cares to set which talent is he using or by which magic he is afflicted.

The easiest way (imho) is to handle all talents and magic with classes, with methods that modify the attributes of the character class.

Another way is to store all talents and spells in a db and read from it when the user choose or use a talent or a spell.

Am i right saying that with 1st way i use more memory than the 2nd? (if not i'm choosing it)

If is better using db, I don't know how to save the data because is poorly structured:

Talent Improved Bluff: +2 to Bluff checks

Talent Speed: if the character wears no armor or light armor he moves 5 feet fast than his base speed

I can save the talent description as a meta-code string and parse it whithin the program but it seems too complicated. Do you have any better ideas for this db?


texts: How can I create JSON sprite sheet data from a regular sprite sheet?

texts:
I want to use some art from OpenGameArt for my game. The piece I want to use is a sprite sheet containing a bunch of sprite tiles compiled into a single PNG:

I want to create a JSON file with the names and coordinates for each tile. Doing this manually would probably take took long.

I've tried TexturePacker but it seems that it only accepts separate image files which it compiles into a single image. It doesn't have an option to load precompiled sprite sheets; then select and name each tile inside of it.

How could I accomplish this?


texts: For my game's multiplayer matchmaking and back-end, every player is assigned a unique GlobalID and LocalID. The GlobalID is used for keeping track of all players and the LocalID is for keeping track of players in a specific room. How can I assign to each player a unique ID so that at any one time 2 players don't have the same GlobalIDs or LocalIDs? I think I can manage with assigning each player their own GlobalID and let them keep it after they log off but I definitely need to reuse LocalIDs Note: I'm using C# for my server which handles the IDs.


texts:
I'm working on a 2D game for WPF8 using XNA 4.0.

Everything goes great, but it's too fast. I was just wondering, what could I do between the end of the game and the score screen, and before the game starts? I'm looking for a sample of how to do that (black screen with "loading" write in windows phone style) or a way to implement it.


texts:
I'd like to simulate a day/night cycle, and am thinking to do this with two components:

an underlay to simulate sky color, accompanying either an alternating cloud or star rotation animation containing lots of transparency depending on time of day.  The sequence for the sky's color-shifting is the focus of this post.

a translucent overlay for the ground, which may or may not tint for color, but would reflect light intensity for time of day.

Looking at similar posts on this site, the authors were interested in either an intensity curve between black and white to reflect the non-linear way sunlight changes (useful for my overlay objective), or just a handful of states (night, dawn, noon, dusk).  My game has a realistic look and feel, and I'd like to try for subtle shifts in chroma.
While I'm interested in precision, I don't care about accuracy for a particular lat/long or time of year.  A generic light cycle model would do, and, if I do decide to simulate seasons, I'll just adjust the proportion of light vs. dark length in the daily sequence.
At a minimum the day/night simulation would take a minute.  30 fps * 30 seconds = 900 frames. Besides adjusting how many frames I spend on each step, I imagine I would also be padding this by stretching out how long the animation stayed at pitch black or high noon.
An alternate solution would be if I could find a time-lapse video of the sky throughout the day.  With GIMP and the GAP plugin, I could turn this into a texture atlas I can use in my game (I'm programming in Java libGDX, btw).  Even if the video were focused on landscape and not the sky, if I just had a tiny, unobstructed patch of the sky in frame (a pixel, even) I could crop the video to that portion of the frame and expand it to fill the screen later in my game.  I've not found any such videos though.  Besides a google search, the site I've used the most to find videos to deconstruct is www.videezy.com
Minus a sequence chart, or a video, I'll start experimenting with sequences.  My first thought is to start from black, and then plot a path mostly along the edge of the RGB color cube: black(255,255,255)->magenta(255, 0, 255)->red(255, 0, 0)->yellow(255,255,0)-[diagonal from yellow to cyan, bypassing green]->cyan(0,255,255).  I'd step through all the states between each of these vertices in a straight line, and, upon reaching the endpoint, I'd reverse the sequence.


texts: how do i convert my pygame games to executable

texts: I have a lot of python games I made in pygame and want to compile them so I can distribute them on sites like itch.io and gamejolt.com, the thing is, when I try to my executable game it says "fatal error detected" and "failed to execute script Pong". I was using pyinstaller to create a standalone file.


texts: Get intersected volume of two planes in 3D

texts:
I'm working on AABB - AABB collision response and I'm having trouble figuring one part out. My situation is as follows (see image).

I have a player AABB (blue) and an object which collides (brown). I've drawn a few faces for both AABB's. The player moves towards the cube and collides with two planes (colliding planes have their normal's drawn). These normals will be returned in the code in the 'normals' vector. I then check the opposing planes and try to get the volume of the intersected plane (right side of image).

I based my face detection algorithm on the following question : AABB - AABB Collision, which face do I hit?

The Two AABB's colliding (blue is Player AABB and brown is object)

If I have multiple normals returned (which happens when two faces collide) I want to calculate the highest intersected volume between the collided faces and take that normal as the normal to base my collision response on (right side of image). It works for some faces but for the other half it doesn't work and I assume this has to do with change of vertex order which make my substractions pointless in some cases.

Is there some general way to calculate the volume of two intersecting planes in 3D that helps me resolve my response?

Code attempt for calculating highest volume between two (not working as it should):

functionThatDoesCollisionResponse
{
    [...]
    // Calculate size differences first
    for(int i = 0; i < normals.size(); i++) // Normals is vector filled with all intersected plane normals.
    {
        Vector oppNormal = normals[i].Negative();
        Plane pFace = this->GetPlaneFromNormal(player, oppNormal); // Returns plane with specified normal
        Plane oFace = this->GetPlaneFromNormal(object, normals[i]);
        sizeDifs.push_back(this->CalculateSizeDifference(pFace, oFace)); // Pushes differences of size in Vector for later calculation
    }

    // Don't take average but take highest intersected volume plane
    GLfloat min = 9999999.99f;
    Vector bestNormal;
    for(int i = 0; i < sizeDifs.size(); i++)
    {
        GLfloat opp = sizeDifs[i].x * sizeDifs[i].y * sizeDifs[i].z;
        if(opp < min)
        {
            min = opp;
            bestNormal = normals[i];
        }
    }
    [...]
}

Vector CollisionEngine::CalculateSizeDifference(Plane p1, Plane p2)
{
    GLfloat xDif = p1.topLeft.x - p2.topLeft.x;
    GLfloat yDif = p1.topLeft.y - p2.bottomLeft.y;
    GLfloat zDif = p1.topLeft.z - p2.bottomRight.z;
    return Vector(abs(xDif), abs(yDif), abs(zDif));
}


texts: How to kill a fired bullet sprite after certain amount of time in Phaser?

texts:
The bullet should be killed after it was shot from the player, and after a certain amount of time.

function create() {
    bullets = game.add.group();
    bullets.enableBody = true;
    bullets.physicsBodyType = Phaser.Physics.ARCADE;
    game.physics.enable(bullets, Phaser.Physics.ARCADE);
    timer = game.time.create(false);

    for (var i = 0; i < 100; i++) {
        bullet = bullets.create(0, 0, 'bullet');
        bullet.exists = false;
        bullet.visible = false;
        bullet.checkWorldBounds = true;
        bullet.events.onOutOfBounds.add(resetBullet, this);
    }
}

function update() {
    if (game.input.activePointer.isDown) {
        fire();
    }
}

function fire() {
    if (game.time.now > bulletTime) {
        bullet = bullets.getFirstExists(false);

        if (bullet) {
            bullet.reset(player.x, player.y);
            game.physics.arcade.moveToPointer(bullet, 300);
            bulletTime = game.time.now + 150;
            timer.add(1000, resetBullet, this);
            timer.start();
        }
    }
}

function resetBullet(bullet) {
    bullet.kill();
}

As you can see I already tried adding a timer into the fire function which calls the resetBullet function after one second. But my game crashes one second after fire() was called:

Uncaught TypeError: Cannot read property 'kill' of undefined

Does anyone know how to achieve the kill of the sprite?


texts:
I'm writing a textbox class for my XNA game and I'm using SpriteFont to draw the text. It's only a single line textbox so when the text width exceeds the size of the rectangle box, it currently just keeps going.

In Windows textboxes extra text is cut off so that you may only see half a letter. I'd like to emulate this with my custom control. However, I see no overload with SpriteBatch.DrawString that would allow for anything that could cut off text that didn't fit within certain bounds.

Does anyone know of a method that would allow for this? I'm still quite new to the XNA API so I'm not sure what out there exists for this sort of thing.. Thanks


texts: SpriteBatch, trying to reduce draw calls

texts:
This my main draw call:

       Matrix Camera_transformation = player_camera_.GetTransformation();

        // Background - AlphaBlend
        spritebatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null, null, Camera_transformation);
        background_.Draw(spritebatch);
        spritebatch.End();

        // Particles (of a player power, I want them behind him!) - Additive
        spritebatch.Begin(SpriteSortMode.Deferred, BlendState.Additive, null, null, null, null, Camera_transformation);
        player_.DrawParticles(spritebatch);
        spritebatch.End();

        // Player - Alpha Blend
        spritebatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null, null, Camera_transformation);
        player_.Draw(spritebatch);
        spritebatch.End();

        // Hub/Ui - Not to be influenced by the camera, but always on top
        spriteBatch.Begin();
        UI.Draw(spritebatch)
        spriteBatch.End();

Is there a way to reduce the number of calls here?
If my particle system didn't need an additive drawing, I would have merged the first three calls, but I can't. Is there something I am missing about spritebatch ordering?


texts: How do I render a mirror or other reflective surfaces?

texts:
I just wondered how to create a mirror within a 3D game?
My suggestion is/was to trace rays, hitting the "mirror" object then drawing a picture of a second cam onto the "mirror" object which is located at the original camera's mirror "point" by using the hit side of the mirror object as mirroring plane.

We would have to use the one ray coming from the center of the original camera to determine the point where the center of the vision is located on the mirror plane.


texts: The game-server model to handle user actions

texts:
I'm starting to work on a mobile game that will have a server-side part (to handle user's interactions between them) and, of course, the client (game itself) part. It's not meant to be a browser game and the goal is for it to run even when not connected to the internet.

I would want to have the network-requireing functions disabled when the network isn't accessible (so user can't send a message to another user when offline, obviously, or trade with other users) but when the network becomes available, the game should sync with the server.

Now, my main concerns are:

how to handle the syncing part? What would be the best way to handle it? Should I just send full game state from the device to the server? This way if a user plays the game on 2 different devices, one of them can get out of sync, but lets say I can live with that...
how to ensure there's no "cheating"? I mean, having some kind of server API exposed, would there be a possibility that someone makes a request that creates some powerful item on the server for him, right?

What would be best practices to approaching thos


texts: Unity Editor: Get Mouse coordinates on left click on Scene Editor

texts:
I need a simple script which does the following:

When I left-click somewhere in the Editor-Scene:

(doesnt matter if there is an object under the cursor- or not)

Do NOT deselect the current selection in the Inspector.
Do not select the object under the cursor.
and

Just print the mouse X and Z interception with the Y-Plane in the Debug.Log();

i stumbled on many solutions but somehow i couldnt get this to work.

i tried:

HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive));

and

Tools.current = Tool.None;

both seem to do nothing ..... X.x

EDIT:

Happens that
"HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive));"
needs to be inside:
public void OnSceneGUI()
and called every frame - to "block" the mouse clicks on the editor.
i thought it toggles it off.

still the problem of the mouse coordinates persists.


texts: How to apply two pixel shaders in one go

texts:
Is there any possible way to apply two pixel shader simultaneously in directx-9.
For example I am having two pixel shaders one to apply ripple effect and another to modify the color of the texture rendered on the screen. Is there any way that I can render the effect of the two pixel shaders simultaneously without combining them in the same shader file.
Any kind of help is appreciated.


texts: Unity 2D Problem: Tilemap Tearing ONLY in Scene View

texts:
Facing an annoying problem with unity, googled to no avail. Basically I was having tilemap tearing so I created a sprite default material with pixel snap on. This fixed the tearing when running the game, but caused massive tearing in just my scene view. This does not affect gameplay but is very annoying when trying to create backgrounds and stuff.
Pic of scene view: https://media.discordapp.net/attachments/810052982220652577/836562483883016192/tilemaptearing.PNG
My problem is identical to the one asked in this thread here but the solution this person came up with was to not use pixel snapping, but I need that to prevent tearing in the actual game. Anyone know what could be causing this and how could I fix?
Edit: Current version 2019.5.0a5, currently updating to most recent version


texts: Correct way to abstract an XBox Controller

texts:
I've got a XBox360 controller which I'd like to use as input for an application.

What I can't work out is the best-practice way to expose this via an interface.

Behind the scenes, the class which handles the controller(s) relies on polling button state.

I initially tried something link:

Event ButtonPressed() as ButtonEnum

where ButtonEnum was ButtonRed, ButtonStart, etc...

This is a little limited in that it only supports button presses, not holds / patterns (press twice, etc.)

The next idea was to simply expose the button state to the app eg

Property RedPressed as Boolean
Property StartPressed as Boolean
Property Thumb1XAxis as Double

This is very flexible but really it forces too much work into the app and requires the app to poll - I'd prefer event driven if possible.

I considered adding multiple events eg:

Event ButtonPressed(Button as ButtonEnum)
Event ButtonPressedTwice(Button as ButtonEnum)
Event ButtonHeldStart(Button as ButtonEnum)
Event ButtonHeldEnd(Button as ButtonEnum)

but this seems a little clunky and was a real pain on the "Bind button" screen.

Can someone please point me at the "correct" way to handle inputs from controllers.

NB: I'm using SlimDX inside the class which implements the interface. This allows me to read state very easily. Any alternatives which would solve my problem are also appreciated


texts: Detecting Screen Resolution in Android/AndEngine to display high or low quality images

texts: I am developing a game with 1024x600 resolution. I can't target smaller resolution devices at this resolution, so I intend to use two graphics for the game. How do I detect which graphics to use for which device?


texts:
The game I am developing is in unity and I want to make a shader which can be put on a mesh that only 'draws' color on each vertex point. I am not proficient with shaders, and out of all my searching I have come up empty handed; I unfortunately don't even know how to look up this question (I seem to only find results about point clouds, which only serves to confuse and scare me more ;P).

Any help or if you can point me in the right direction on what to search, I would be very much greatful.


texts: jQuery - calculate map polygon Width and Height

texts:
Let's say I have this map:

<map name="diffmap1" id="diffmap1" class="myMap">
<area shape="poly" coords="152,347,253,292,264,307,167,358" class="diff diff1">
<area shape="poly" coords="93,244,164,215,171,233,97,264" class="diff diff2">
</map>

and jquery:

$('.diff').click(function(e){
//code here
});

How can I calculate the maximum height and width of each polygon?

LE: https://www.dropbox.com/s/erplo5fwtp284oh/qwe.jpg


texts: Can I use sdl_net2.0 lib with cocos2d-x? And how it cconects to each other. Or analog lib to use?


texts: Image drawing tools (that aren't Photoshop) that work in the sRGB colorspace

texts:
I'm looking for a way to create sRGB raster images. Now, I could use Inkscape and just have it render to a raster format, but are there any image drawing tools other than Photoshop that work in sRGB?

Here's what I want to be able to do more specifically. Let's say the image is all one color. I want to be able to pick color 0x808080, which is in the sRGB colorspace. I want the file to write an image where every pixel is 0x808080. And then, when I read it, I can tell OpenGL that it's sRGB color data, so it will treat the 0x808080 color has being from the sRGB colorspace.

The important part is that, when I'm selecting colors in the tool, the colors I'm selecting are from the sRGB colorspace.


texts: OpenGL 2.1+ Render with data returned form assimp library

texts:
I have just read this tutorial about how to load a 3D model file. Its render routine uses a recursive_render function to scan all nodes.

My question:

What does a aiNode struct store?
What the difference between this method and above method:

for (int i=0; i < scene->mNumMesh; ++i) {
   draw scene->mMeshes[i];
}


texts: Degenerate AABB (axis aligned bounding box), does this always intersect?

texts:
I'm studying ray-AABB intersections and I'm asking myself: what would happen if one of the dimensions of the axis aligned bounding box was degenerated?

For instance:

AABB_min = {1,1,1}
AABB_max = {5,5,1}

in this case the Z coordinate would be the same for the AABB maximum and minimum point. You can think of this AABB as a 2D rectangle.

In such a case, would this always yield "true" as intersection with a ray if the ray's Tmax and Tmin were something like +inf and -inf (so that we don't need to bother with them)?


texts: Can I make a flash file I developed to run on Androis / IOS?

texts:
I've created a simple game using ActionScript 3.0 and Adobe Flash CS5.
Is there any way to run this creation on Android / Apple IOS ?
(Even if so, I still have no Idea how to work with "touch" interfaces, just want to know if such thing is possible first.)


texts: Farseer: Difficulties with ContactListener

texts:
How can I register the ContactListener in XNA? In the box2d manual is written:

9.4 Contact Listener
...
At run-time you can create an instance of the listener and register it with b2World::SetContactListener. Be sure your listener remains in scope while the world object exists.

http://www.box2d.org/manual.html#_Toc258082975

How can I do that? I want to use PreSolve to disable collision between the character and some tiles.


texts: Vector class throwing an error after publishing the FLA for generating .ipa from flash CS5

texts:
I am creating a flash game for iPhone using Flash CS5. Everything runs smoothly when creating the SWF via Ctrl+Enter. But when I am attaching the .p12 and provisioning profile files and publish the FLA to generate the .ipa there is an error thrown by the compiler that is:

"Incorrect number of arguments, Expected no more than 0"

private static function closestVertexOnOBB(p:Vector,r:RectangleParticle):Vector
{
    var d:Vector = p.minus(r.samp);
    var q:Vector= new Vector(r.samp.x, r.samp.y);

    for (var i:int = 0; i < 2; i++)
    {
        var dist:Number = d.dot(r.axes[i]);

        if (dist >= 0) dist = r.extents[i];
        else if (dist < 0) dist = -r.extents[i];

        q.plusEquals(r.axes[i].mult(dist));
    }
    return q;
}


texts: How can I set 3d sound to my game in unity5?

texts:
I have been working on a racing game in unity5. Now I want to set 3d sound so that if the game objects are far away from and coming towards the camera then it sounds like began to attenuate and then louder when closer to the game camera.

But I don't know how to do that.......if anyone knows then please help me out.
Thanks...!


texts:
I trying create simple Multi-player with HTML5 Canvas, JavaScript(too using John Resig simple Inheritance library) and Node.js with Socket.IO.
My client code:

var canvas  = document.getElementById('game');
var context = canvas.getContext('2d');
var socket  = new io.Socket('127.0.0.1', {port: 8080});

var player = null;

var UP    = 'UP',
    LEFT  = 'LEFT',
    DOWN  = 'DOWN',
    RIGHT = 'RIGHT';

socket.connect();

socket.on('connect', function() {socket.send();
    console.log('Connected!');
    player = new Player(50, 50);
});

socket.on('message', function(msg) {
    if(msg == 'UP') {
        player.moveUP();
    } else if(msg == 'LEFT') {
        player.moveLEFT();
    } else if(msg == 'DOWN') {
        player.moveDOWN();
    } else if(msg == 'RIGHT') {
        player.moveRIGHT();
    } else {

    }
});

socket.on('disconnect', function() {
    console.log('Disconnected!');
});

var Player = Class.extend({
    init : function(x, y) {
        this.x = x;
        this.y = y;
    },
    setX : function(x){
        this.x = x;
    },
    getX : function(){
        return this.x;
    },
    setY : function(y){
        this.y = y;
    },
    getY : function(){
        return this.y;
    },
    draw : function(){
        context.clearRect(0, 0, 350, 150);
        context.fillRect(this.x, this.y, 15, 15);
    },
    move : function() {
        this.x += 1;
        this.y += 1;
    },
    moveUP : function() {
        this.y--;
    },
    moveLEFT : function() {
        this.x--;
    },
    moveDOWN : function() {
        this.y++;
    },
    moveRIGHT : function() {
        this.x++;
    }
});

function checkKeyCode(event) {
    var keyCode;
    if(event == null) {
        keyCode = window.event.keyCode;
    } else {
        keyCode = event.keyCode;
    }

    switch(keyCode) {
        case 38: // UP
            player.moveUP();
            socket.send(UP);
        break;
        case 37: // LEFT
            player.moveLEFT();
            socket.send(LEFT);
        break;
        case 40: //DOWN
            player.moveDOWN();
            socket.send(DOWN);
        break;
        case 39: // RIGHT
            player.moveRIGHT();
            socket.send(RIGHT);
        break;
        default:
        break;

    }

}

function update() {
    player.draw();
}

var FPS = 30;
setInterval(function() {
    update();
    player.draw();
}, 1000/FPS);

function init() {
    document.onkeydown = checkKeyCode;
}

init();

And server code:

var http = require('http'),
    io = require('socket.io'),
    buffer = new Array(),

server = http.createServer(function(req, res){
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('Hello world');
});
server.listen(8080);

var socket = io.listen(server);

socket.on('connection', function(client){

    client.on('message', function(message){
        console.log(message);
        client.broadcast(message);
    })
    client.on('disconnect', function(){

    })

});

And when I run two client's I with first client can move second client Rect and with second client move first client rect and something like with third client can move first and second client rect's.

I have question how to create real Multi-Player? something like:
Open three client's and first client get rect1, second rect2 and last rect3. First client only can move rect1, client third can move only rect3.

Maybe anyone have idea? I search in Google but don't find answer.

Sorry for my English language, Thanks.


texts: Questions about networking theory in a 2d shooter game

texts: So currently I am starting to work on a 2d top down space shooter game, and I have just got to networking. So far the client can draw a ship at a desired x, y and rotational coordinate with any set of vertex data (referenced from pre-existing vectors of data). The problem I am having is just the main idea of how the game loop should revolve around the networking. My idea was have each loop of the game set to 1000/60ms, and then ask the server for some data, render it and sleep for the remaining time in the frame. Problem with that is that I realised a normal ping to a game server is around 100ms, meaning the game would only be getting around 10fps. The solution I assume is to only receive events 10 times a second versus the 60 refreshes the game is getting, but how would you render and be polling to receive data at the same time? Finally I am using enet as the networking library if anyone is interested because it seems to be pretty simple in its concept, but if there is a better one for this type of game out there it would be nice to know. (I did try googling all of this stuff but its kind of hard to describe exactly what I am confused about, so thanks for any help).


texts:
What is the best way to handle animated lights on rides in a night time amusement park scene?

Is there a better way that doing lots of emission lights?

At the moment I have been using emission lights, but there could be a lot of them in a park (some are just static lights) and I would also like to animate some of them on some rides.

Best example I could find was from GTA 5:

Video: https://youtu.be/zVj8D0lqgl4?t=146


texts: Symbol not found Error in Unity3d - IOS Buid in Xcode

texts:
I new to IOS build , when  i try to build following error showing

I using Unity 5.2.1f1  and Xcode 7.0.1(7A1001)  . Previous   unity version was 5.0.1  , in that version , same error was found thats why  i updated unity , even though same error is existing

When i taking build Xcode showing  "Buid Succeeded" , when running on simulator , following error is showing .

Warning: Error creating LLDB target at path '/Users/UserName/Library/Developer/Xcode/DerivedData/Unity-iPhone-dzxhzbvzarcxwncwpymwfynqdipi/Build/Products/Release-iphonesimulator/GameName.app'- using an empty LLDB target which can cause slow memory reads from remote devices.

_dyld: Symbol not found: _assignIdentifiersAndCallbackGameObject
  Referenced from: /Users/UserName/Library/Developer/CoreSimulator/Devices/400B12B2-B711-453C-B0E3-7DDF12A770F0/data/Containers/Bundle/Application/E62986EE-618C-4530-B5F8-A09D43162DBD/GameName.app/GameName
  Expected in: flat namespace
 in /Users/UserName/Library/Developer/CoreSimulator/Devices/400B12B2-B711-453C-B0E3-7DDF12A770F0/data/Containers/Bundle/Application/E62986EE-618C-4530-B5F8-A09D43162DBD/GameName.app/GameName
(lldb)

please help me , how to solve this problem


texts:
How would one of these work?

(If you don't know what I'm talking about, think like in a game where you shoot a big gun, and your screen bounces in the opposite direction.)

I've been experimenting with a couple different ideas but none are either fully working, or fully smooth.

Using this function for setting the camera position:

x = -target.x + halfScreenW;
y = -target.y + halfScreenH;

One problem I've run into is when setting the camera to move a certain distance in a direction, it will reach its target X or Y before the other, causing it to go travel in a straight line for a short while. I believe the solution to this is using the Bresenham line algorithm?

What would be the best way to achieve a camera shake?

edit: Related - Realistic Camera/Screen Shake from Explosion


texts: Serialize classes based on Generics. Is it different?

texts:
I have a certain ScriptableObject.

public class Biome : ScriptableObject { ... }

If I write the following in a component:

public List<Biome> list1;

This is what appears in the inspector:

So far so good. But if I try to make my list more generic, like this:

public class DistributedList<T>
{
    public List<T> items;
}

[System.Serializable]
public class BiomeList : DistributedList<Biome> { }

This is what I get on the inspector:

All I can seem to be able to add now is just a name, not the Object itself.

Why is this?


texts: How to apply a filter to the screen of a running program?

texts:
The idea is to take old games without modifying them, but have the graphics card apply a series of filters to their output before sending them to the monitor. A very crude example would be to take a game that has a resolution of 640x480 and do:

Increase the resolution to 1280x960
Apply a blur (low pass filter)
Apply a sharpen (1 + high pass filter)

These steps may not necessarily be the best to improve the visuals of an old game, but there are a lot of techniques that are well-known in image processing for this purpose.

The question is, do the (NVidia) graphics cards give the ability to load a program that modifies the screen before sending it to the monitor? If so, how are they called and what terminology should I use to search? I would be comfortable with doing the programming myself if this ability is part of a library.

Also, would the solution be different between Windows and Linux? If so, either is fine, since most of the games are probably runnable by wine.


texts: Can I leverage the fact that my scene is often static to improve OpenGL (JOGL) performance?

texts:
My scene is drawn based on the location of several (often several million) vertices (kept in VBO's) and a camera.  I can easily tell in my code when my scene has changed and when it hasn't.  There are also some odd cases such as the window being resized, but I believe I can easily enumerate and handle those as well.

Can I (in user code or through some OpenGL property) leverage this to increase the performance when the scene is static?  Clearly when the scene is changing, all of the math must be done to properly calculate what should be rendered.  But when the scene is static, that picture isn't changing each frame.

I've tried implementing something in my code to do this, but the result is a flickering scene (and I'm not entirely sure why).  Basically I check to see if anything has changed and if it hasn't I simply return from the display(GLAutoDrawable drawable) function that is invoked by the JOGL FPSAnimator.

I feel like this is probably a common problem that should have a standard solution.  However, I haven't been able to find anything so far.


texts:
What do i need to keep my player model from going through environment objects like walls, trees etc?

Im trying to figure out if should use rigid bodies and the built in physics but i feel that its too difficult to predict what will happen then.

Is there an alternative that still will prevent the player from going through environment objects?

At the moment my player is a 3d model compsosed of some primitive shapes and a capsule collider.


texts:
I'm coming from modo and want to try to create mesh assets for Unity3D in Maya. As a simple example how do I create an exact 1m cube in Maya? In modo it's easy to do.

In maya I draw a roughly 1m cube onto the grid and then want to set it's exact size but the channel box already displays scale 1x1x1 even if it's not an exact 1m for each size.

How do I set it to exactly 1m (or whatever exact measurement)? Surely it must be possible?


texts: How can I use a Seekbar as a brightness slider?

texts:
I am using the GLSurfaceView Renderer. I want changes to a seek bar's progress to increase the brightness of a GLSurfaceView proportionally.

How do I apply a color matrix to a GLSurface view? Is there a better way?


texts: UE4 Code Project is not showing sub folders created within C++ Classes Folder even though they exist

texts:
These were my steps.
Created an empty code project in UDK4.
The editor starts up.
On the left bottom you have:

If you try to right click on C++ Classes,
Or select [Add New] while having C++ Classes highlighted
The option to add a new folder is greyed out.

This seems odd, since you can add a new C++ Class and set your sub folder in there. When the class gets created and our IDE in my case (Visual Studios) opens up the folder gets created in there no problem. I also tried setting the public or private option when making a new c++ class that just added a sub folder of /private /public where my new class gets nested in code but still not seeing the folder format display on the Unreal Editor.

So what's going on with UDK4? It seems highly unlikely that the issue is actually a bug.
Is it something I'm doing wrong? Or some second step I need to do?

Different Attempts:
1) Tried making the sub folder in the class create pop up, that created the folder in Visual Studios but still did not show up in the Unreal Editor
2) Restarted Unreal Editor to see if it would refresh the folder hierarchy, no luck.
3) Shutdown both UDK4 and VS and restarted UDK4 then VS also tried VS then UDK4 just in case as a second test.
4) Attempted to drag and drop a folder into the hierarchy from Visual Studios you just get a red O with a slash next to the mouse icon stating it wont allow it.


texts:
I want to the obstacle Scale-In and Scale-Out using Dotween PlugIn? means some effect??

See this link: https://www.youtube.com/watch?v=_Tq4t0gx49g&t=569s

Image:

I want to give a effect on the obstacle?

script:

Obstacle.cs

void Update()
{
        goTopToDown();
}

void goTopToDown()
{

  foreach (Transform item in GetComponentsInChildren<Transform>())
  {
      if (item.tag == "obstacleobject") //some obtsacle slow
      {
          item.localPosition += Vector3.down * speed * Time.deltaTime;                   //move top to down object
      }
      if (item.tag == "movefastobject") //some obstacle fast
      {
           item.localPosition += Vector3.down * movefastobjectspeed * Time.deltaTime;     //move fast object
       }
  }
```


texts: Java Game How to find the x and y for a tile?

texts:
Hello I have a java game where you build houses I want to be able to dag my mouse form point a to point b and I want to fill that area with tiles when I release the mouse. What I cant do is get the first x and y coordinate of the selected area then put the tile there then move on to the next area I tried to do something like this:

    bx = Math.min((dragX / 20) * 20, (curX / 20) * 20);
    by = Math.min((dragY / 20) * 20, (curY / 20) * 20);
    w = Math.abs((curX / 20) * 20 - (dragX / 20) * 20);
    h = Math.abs((curY / 20) * 20 - (dragY / 20) * 20);

    if (dragging & w >= 20 && h >= 20) {
        g.setColor(new Color(26, 216, 26, 128));
        g.fillRect(bx, by, w, h);
        g.setColor(new Color(17, 142, 17, 255));
        g.drawRect(bx, by, w, h);

        int posx = play.bx * 20;
        int posy = play.by * 20;
        for (int i = 0; i <(play.w * play.h / 20) / 20 ; i++) {

            play.b.add(new wall((posx), (posy), play.selectedRot));
            posx +=20;
            posy+=20;
        }
    }

dragX and dragY is where it starts and curx and cury is where it is currently
the tiles are 20x20 pixels so I place them every 20 pixels on the screen so it is like a grid.
if I select an area that is 2 tile wide and 2 tiles high and each tile is 20 x 20 pixels that is 1600 pixels I divide that number by 20 and get 80 and then divide that by 20 again to find out how many tiles I need to place in total which in this case is four. what I don't know is how to find the x and y that I need to place that tile then I don't know how to move on to the next one. Please help me. Thx to everyone who reads this.


texts: Techniques for lighting a texture (no shadows)

texts:
I'm trying to learn about dynamic shadows for 2D graphics. While I understand the basic ideas behind determining what areas should be lit and which should be in shadow, I don't know how I would "lighten" a texture in the first place.

Could you go over various popular techniques for lighting a texture and what (dis)advantages each one has? Also, how is lighting a texture with colored light different from using white light?


texts: Will having many timers affect my game performance?

texts:
I'm making a game for android, and earlier today I was trying to add some cool stuff to my game. The problem is this thing needs like 5 timers. I build my timers like this:

timer += deltaTime;
if(timer >= 2.0f){
    doStuff;
    timer -= 2.0f;
} // this timers gets stuff done every 2 secs

Will having to many timers like this, getting checked every frame, screw up my games performance? The effect I wanted to add was a crosshair every 2 sec, then remove it after 2 sec and do a timed animation. So an array of crosshairs dependent on a bunch of timers to be exact. This caused my game to shut down when used, so thats why Im wondering if using that many timers causes my game to flip out.


texts: How can I manipulate a single pixel with LWJGL?

texts:
This is a very simple question. Is there a way to manipulate a single pixel?

Here's an example of what I want in pseudo-code:

while(gameIsOn) {
    renderAllObjects();
    setPixel(x,y,r,g,b);

}

Is this possible in any way? (Notice it's is not a solution to render a 1 by 1 quad, since it's too resource expensive.)


texts: How to implement OpenGL triple buffering of buffer objects to avoid stalls?

texts:
I'm trying to implement the triple buffering described here. The intent is to gain higher frame rate by avoiding waiting for glBufferSubData() to finish.

My understanding is that this is how to implement triple buffer:

- make 3 buffers with glGenBuffers()
Current frame:
  - bind to buffer3
  - draw last frame
  - bind to buffer1
  - glBufferSubData for all the vertices,
  keep track of their texture/vertex count,blend function, etc
Next frame:
  - bind to buffer 1
  - draw last frame (bind texture, blend func, glDrawArrays)
  - and so on

There doesn't seem to be any performance gain between this and doing glBufferSubData() and then immediately calling glDrawArrays().

Am I missing something or misunderstand how triple buffer should work?

Also is there a way to know when glDrawArrays() stalls due to glBufferSubData() still not being finished?


texts: How to achieve a for loop without Unity crashing?

texts:
I want to make a for statement that repeats constantly until a stop variable becomes "1". But wherever you type a "for" statement in any way or even without anything in the statement, Unity just crashes without even a report. So is there a way to achieve the same effect without using the for statement?

(Here's an example script that would crash.)

#pragma script
var stop : int;

fucntion Start()
{
  for(stop=0;stop<2;stop++ )
  {
    Debug.Log("Hi");
  }
}

No matter where you put it, or what you do with it, or how you change it, it just crashes. So my question is: Is there an alternative to for statement?


texts: How can I implement an inventory that stores different types of items?

texts:
Let’s assume I want to create an RPG with collectible items my character can pick up and store in his inventory.

One item could be a sword, with an attack, defense, and level attributes.

Another item could be an apple, heal percentage, freshness, and servings attributes.

Both items are collectible items, and both objects can be stored in the players inventory, but they share separate sets of attributes.

I am trying to think of a way to set this up in the database. I originally looked to the EAV database model, so I could define a single collectible item entity, and bolt on separate attributes as I needed them, but I discovered EAV is slow because of multiple calls to the database to construct an entity, which wouldn't make it very suitable for a game in my eyes.

I also can't find any game development tutorials that use EAV, so there must be a more common solution I'm not aware of.


texts: Dragging UI element lags behind the cursor

texts:
Have been at this for 2 days straight trying different ways to solve this, and I can't.

I'm simply dragging around a UI panel using PointerDown and Drag events.  I set the transform.localPosition inside the Drag handler.  It works as expected, only problem is, the UI element seems to lag behind the cursor.

I created a GIF to show the issue in a build version to rule out the Editor.

Not sure how well you can see the issue, but the faster you move the cursor the worse it is.

Any ideas of what the issue is and how can I solve it?

Thanks


texts: Should I use a VBO if the vertex data changes from time to time?

texts: If I have a very large number of vertices, but they're static for about 70% - 80% of their life time, should I use a VBO for them? If so, what usage should I specify? This doesn't sound like a case for GL_STATIC_DRAW.


texts: Are there well-known tools for chasing down VRAM & GTT memory leaks?

texts:
Problem. I have inherited a large C++ 3D graphics codebase (with some shader code). The program runs for about 1-5 minutes before crashing.

Problem Data. Using system tools, one can see a sharp rise in VRAM memory usage after the program launches, which eclipses into a crash. The same is true for GTT memory usage also (although the spike isn't quite as dramatic as with the VRAM).

Questions.

Does this (probably) mean that there is a memory leak in OpenGL shader code somewhere (as opposed to a leak in regular C++ code)?
Are there well-known tools for tracking down vram/gtt memory leaks (similar to the way that valgrind can be used to track down system memory usage)?


texts: Is there a way to make a game object invisible to only certain players?

texts:
I have found a few posts and blogs here and there. But all of the solutions they provide seem to be global.

Is there a way for let's say a multiplayer scenario where maybe an enemy has a cloaking device. Player 1 can't see said enemy but because Player 2 has thermo-goggles he can see the enemy just fine.

Is there an example of that scenario somewhere? I assume that it would have to be done at the camera level instead of the object instantiation. Maybe a state machine to designate these objects are invisible and one on the camera to state that you can see said invisible objects?


texts: Followed the XNA GameStateManagement sln, but my doesn't work. What am I doing wrong?

texts:
If someone has the time I wanted to know if you would be willing to check out my solution file here: http://elvis.rowan.edu/~majeko02/AwesomeShip.zip

I followed the XNA GameStateManagement on AppHub, but nothing comes up from me. and I haven't the clue why.

I believe I done everything correctly and verified it as well.

I wanted to know if someone has the time could they check it out?

Download link here: http://elvis.rowan.edu/~majeko02/AwesomeShip.zip

I am racking my brain trying to figure out why it doesn't work.

Any help, is greatly appreciated.


texts: How to debug DXGI_ERROR_INVALID_CALL errors?

texts:
I am developping an application using SharpDX and on one of my machines the call
_swapChain = new SwapChain(factory, _device, desc);

fails with the error message

HRESULT: [0x887A0001], Module: [SharpDX.DXGI], ApiCode: [DXGI_ERROR_INVALID_CALL/InvalidCall], Message: Unknown

When I googled the error I found this where it states:

DXGI_ERROR_INVALID_CALL (0x887A0001)
The application provided invalid parameter data; this must be debugged and fixed before the application is released.

But how?
The error message does not give me any indication whatsoever to why the creation failed.
I checked the debug layer output but that only shows Info. No Warning, no Error, nothing. The factory and the device are created just fine and I tried several combinations of parameters in my SwapChainDescription but the error always remains the same.
How am I supposed to find out what triggers the error?
Just to be clear: I am not so much looking for a solution for my specific problem as I am wondering how I would go about debugging such a problem in general.
This is the boiled down code:
const int MAXFPS = 60;
const Format PIXELFORMAT = Format.R8G8B8A8_UNorm;

// Create device
_device = new Device(DriverType.Hardware, DeviceCreationFlags.None); // Or DeviceCreationFlags.Debug

// SwapChain description
var desc = new SwapChainDescription()
{
    BufferCount = 2, // I tried 1 too
    ModeDescription = new ModeDescription(_renderSize.Width, _renderSize.Height,
                                          new Rational(MAXFPS, 1), PIXELFORMAT),
    IsWindowed = true,
    OutputHandle = _hwnd,
    SampleDescription = _samples,
    SwapEffect = SwapEffect.Discard,
    Usage = Usage.RenderTargetOutput
};

// Create SwapChain
var factory = new SharpDX.DXGI.Factory();
_swapChain = new SwapChain(factory, _device, desc);

I confirmed the sample description is valid using
_device.CheckMultisampleQualityLevels(PIXELFORMAT, _samples.Count) > _samples.Quality

(though, those are 1 and 0 anyway), that the format is supported using
_device.CheckFormatSupport(PIXELFORMAT).HasFlag(FormatSupport.RenderTarget)

and also checked that
_hwnd != IntPtr.Zero
_renderSize.Width > 0
_renderSize.Height > 0

What else to check?

Update: I was able to fix the problem following the advice from here:
I changed this
Device device = new Device(DriverType.Hardware, DeviceCreationFlags.None);
Factory factory = new Factory();
SwapChain swapChain = new SwapChain(factory, device, desc);

to
Factory factory = new Factory();
var adapter = factory.GetAdapter(0);
Device device = new Device(adapter, DeviceCreationFlags.None);
SwapChain swapChain = new SwapChain(factory, device, desc);


texts: How to transfer a luabind::object between two lua states

texts:
I store an object by a function call from Lua to C++ in first script in my application and after that I'll try to pass that object to other scripts and vice versa.

A part of script class in C++:

void script::set_property(lua_State* L, luabind::argument const& value)
{
  this->property_field = luabind::object(L, value);
}

luabind::object script::get_property(lua_State* L)
{
  return this->property_field;
}

Then in my script which is Script1.lua I do this:

script1:set_property(a table or a userdata or a string)
print(type(script1:get_property()))

The problem is, values sent by scripts are distinct in different Lua states because every script in my application has its own lua_State. The above code works fine when I call script::get_property from Script1.lua.

Since all of my scripts have access to other scripts in their contexts when I try to do this in other scripts like Script2.lua or Script3.lua or others:

print(type(script1:get_property()))

It won't print data type here properly and it'll return a number instead, which is a wrong result and the reason is script1:get_property() is returning a value that is only understood by script1 and not in other scripts.

I understand values that have been registered in script1 are only registered into that script's stack and registry table particularly and no one else, but my question is, is there any way to transfer these values between different Lua states?

Thanks.


texts: How to store the updated score in mysql databse from android?

texts:
I want to store the updated score in mysql database. So, what i do for that?

private void updateScore() {
    if (winner.equalsIgnoreCase("You")) {
        tally = 100 - computer.getId();
        MainActivity.userScore += tally;
        if (MainActivity.userScore >= MainActivity.maxEnd) {
            MainActivity.   stat++;
            MainActivity.totTurn++;
            MainActivity.userScore = 0;
            MainActivity.computerScore = 0;

        }

    }
    if (winner.equalsIgnoreCase("computer")) {
        tally = 100 - buddy.getId();
        MainActivity.computerScore += tally;
        if (MainActivity.computerScore >= MainActivity.maxEnd) {

            MainActivity.totTurn++;
            MainActivity.userScore = 0;
            MainActivity.computerScore = 0;
        }
    }
    MainActivity.saveConfig();
}


texts:
For my Voxel like game I need to generate terrain meshes from an array of ids. Because of that I have no idea how big the final vertex array will be.

Currently I'm doing like this: generate mesh and save to arrayList, then in a few lines of code I convert the arrayList to a primitive array. This is working fine, but it's just really SLOW.

So now my question is is there a way I can use a primitive array, without knowing it's final size? If not is there a fast way I can take an array with a lot of empty elements, and then shrink it?

Edit: Heres how I convert it:

List <Float> vertices = new ArrayList <Float> ();

//Generating mesh

float[] doneVertices = new float[vertices.size()];
for(int i = 0; i < vertices.size(); i++) doneVertices[i] = vertices.get(i);


texts:
I'm attempting my first 2D vertical scroller and can't seem to get the background size to work. For some reason, it stays small. I think in the beginning of the parallax scrolling class, I was told to initialize variables and I know which ones I have to change.

public Texture2D picture;
public Vector2 position = Vector2.Zero;
public Vector2 offset = Vector2.Zero;
public float depth = 0.0f;
public float moveRate = 0.0f;
public Vector2 pictureSize = Vector2.Zero;
public Color color = Color.White;

I think I must change pictureSize to make it bigger, as the current sizing I get this:

Finally, how can I remove the whitespace from the ship image?

EDIT: Here is the code for the rendering of the actual ship:

public void Render(SpriteBatch batch)
{
    batch.Begin();
    batch.Draw(shipSprite, position, null, Color.White, 0.0f, spriteOrigin, 1.0f,
    SpriteEffects.None, 0.0f);
    batch.End();
}

The whitespace seems to be provided by XNA as I've tried clearing it using Photoshop. Because I can't directly upload to the site, I have put it here

This renders the background:

public void Draw()
{
layerList.Sort(CompareDepth);
batch.Begin();
for (int i = 0; i < layerList.Count; i++)
{
   if (!moveLeftRight)
   {
       if (layerList[i].position.Y < windowSize.Y)
       {
           batch.Draw(layerList[i].picture, new Vector2(0.0f,
           layerList[i].position.Y), layerList[i].color);
       }
       if (layerList[i].position.Y > 0.0f)
           batch.Draw(layerList[i].picture, new Vector2(0.0f,
           layerList[i].position.Y - layerList[i].pictureSize.Y),
           layerList[i].color);
       else
           batch.Draw(layerList[i].picture, new Vector2(0.0f,
           layerList[i].position.Y + layerList[i].pictureSize.Y),
           layerList[i].color);
   }
   else
   {
       if (layerList[i].position.X < windowSize.X)
       {
           batch.Draw(layerList[i].picture, new Vector2(layerList[i].position.X,
           0.0f), layerList[i].color);
       }
       if (layerList[i].position.X > 0.0f)
           batch.Draw(layerList[i].picture, new Vector2(layerList[i].position.X -
           layerList[i].pictureSize.X, 0.0f), layerList[i].color);
       else
           batch.Draw(layerList[i].picture, new Vector2(layerList[i].position.X +
       layerList[i].pictureSize.X, 0.0f), layerList[i].color);
       }
   }
   batch.End();
}

(It's from a XNA tutorial book I'm reading.)


texts: How to slow down a Sphere smoothly in a world controlled by force and stop it (Unity 5)?

texts:
I am a beginner and I started to use Unity 5. I play with tutorials on the site and documentation. I was basically testing springs, physics materials etc.

I have a problem understanding probably a very basic thing:

I have a Sphere (Collider + Rigidbody) and a Ground (Mesh Collider).
I add force to Sphere on FixedUpdate with GetAxis method.
I added Physics material to both sphere and the ground to create a friction.
Ball slows down when I do not touch the keys (no new forces) but it never stops while moving on the ground.
I know that as only 1 point is touching the gorund friction may not be good enough, but it almost does not affect the ball after a certain period. (I print the speed of the ball (Sphere) on a GUIText so I can numerically check it there too.)
I am aware of default Sleep treshold value but it will effect everything as it is a global variable, so I can't use that.
So, ball never sleeps.
I am aware of drag and angular drag (like the friction of Air) of Rigidbody component and they for sure work, BUT it feels like the ground is sticky and ball stops very quickly. It doesn't look smooth and natural.

Is there something that I am missing? The only way to do this is checking the speed of the ball and making it sleep manually when it's speed is low? Isn't there any other method? I don't want to do this as the world itself must live itself: I don't want to check movement of every single object..

This is probably one of the most basic things, but I cannot understand why it doesn't work..


texts: How to convert game object world position to hex grid cell coordinates?

texts: I have a hex grid and a game object, let's say it's the player. What I want to do is know on which cell the player is on based on his world position, this would be easy on a simple grid but on a hex grid it's giving me a headache.


texts: Would Raycast suffice for a game clock based on sun position?

texts:
I need help with some logic in my script. I created a dynamic day/night cycle that works fine in itself, but I want to add a game clock that works off the initial position of the sun (Directional Light).

I was thinking that it could be achieved by Shooting a ray from the directional light to the terrain and computing an angle which i would use to estimate the time.

Would ray casting be the best/ most efficient way to do this?
Is it even possible to achieve what I'm asking for, if not is there a method that better suits what I need?

So to go over.. I want the user to be able to place the sun anywhere along the x axis that would rotate around the terrain, when the user is satisfied with the position they chose, on startup of the game I would like my script to calculate the current position of the sun and then estimate the current time.

I can take care of the actual clock after that point but is ray casting from the sun to the terrain the way to go about something like this or should I be looking at this in totally different way?


texts: Getting the Right Vector from the Forward Vector

texts:
I'm currently working on a small Camera (ArcBall) and I finally am starting to understand how it will work.

I will first create a basic View Matrix using a LookAt function.

Then, I will send the Camera Position and the Camera Target to a function which will:

1: Calculate the Vector of (Camera Position - Camera Target)

2: Rotate this vector by X Pitch
3: Rotate the same vector by Y Yaw

This will determine the new Camera position. Now I need to find the Up Vector to be able to use LookAt() so I need to do the cross product of the forward and the right vector to find the Up Vector.

4: I will do (Camera Target - Camera Position) and normalize it so this will be my new Forward vector

5: ??? I need to find the right vector. How can I find the Right vector if I do not have the Up vector?

If you see flaws with my ArcBall camera, tell me, I am new to OpenGl and I'm trying to learn.


texts: How can I correct an unwanted fisheye effect when drawing a scene with raycasting?

texts:
Hello I have a game using raycasting for the TI Nspire in Lua, and when the player faces a wall so that their degree they are facing is perpendicular to the length of the wall, I am having what is described as the fishbowl/fisheye effect.

How can I fix this? I have already looked here, and none of that makes sense to me. Here is my code:

map = {{0, 0, 50, 0},{50, 0, 50, 50},{50, 50, 0, 50},{0, 50, 0, 0}}

facing = 45 --"player rotation"
rays = {}
x, y = 25, 25

function raycast()
    for i,v in pairs(rays) do
        rays[i] = nil
    end

    rayf = facing + 30

    for i = 1, 320, 1 do --64, 5
        x_ray, y_ray = x, y
        ray()
        table.insert(rays, radius)
        rayf = rayf - (60/320)
    end
    platform.window:invalidate()
end

function ray()
    radius = 1
    for n = 1, 50, 1 do -- increase of testdot
        x_ray = math.floor(x + (radius * math.cos(rayf * 3.141592653/180)))
        y_ray = math.floor(y - (radius * math.sin(rayf * 3.141592653/180)))
        for k,v in pairs(map) do
            if (
                math.min(v[1],v[3]) <= x_ray and x_ray <= math.max(v[1],v[3])
            ) and (
                math.min(v[2],v[4]) <= y_ray and y_ray <= math.max(v[2],v[4])
            ) then
                --print("Collision")
                return true
            end
        end
        radius = n
    end
end

function on.paint(gc)
    gc:setColorRGB(0,200,255)
    gc:fillRect(0, 0, 320, 108)
    gc:setColorRGB(100,100,100)
    gc:fillRect(0, 109, 320, 109)
    gc:setColorRGB(100,0,100)
    for i,v in ipairs(rays) do
        gc:drawLine(i, 108.5 - ((100/v * 20)/2), i, 108.5 + ((100/v * 20)/2))
    end
end

function on.arrowKey(key)
    if key == 'left' then
        facing = facing + 3
    elseif key == 'right' then
        facing = facing - 3
    end
    if key == 'up' then
        y = y - 1
    elseif key == 'down' then
        y = y + 1
    end
    raycast()
end

I have also tried it like this:

map = {{0, 0, 50, 0},{50, 0, 50, 50},{50, 50, 0, 50},{0, 50, 0, 0}}

facing = 45 --"player rotation"
rays = {}
x, y = 25, 25

function raycast()
    for i,v in pairs(rays) do
        rays[i] = nil
    end

    rayf = facing + 30

    for i = 1, 320, 1 do --64, 5
        x_ray, y_ray = x, y
        ray()
        ----------------
        fisheyeradius = radius / (math.cos(rayf - facing))
        table.insert(rays, fisheyeradius)
        ----------------
        rayf = rayf - (60/320)
    end
    platform.window:invalidate()
end

function ray()
    radius = 1
    for n = 1, 50, 1 do -- increase of testdot
        x_ray = math.floor(x + (radius * math.cos(rayf * 3.141592653/180)))
        y_ray = math.floor(y - (radius * math.sin(rayf * 3.141592653/180)))
        for k,v in pairs(map) do
            if (
                math.min(v[1],v[3]) <= x_ray and x_ray <= math.max(v[1],v[3])
            ) and (
                math.min(v[2],v[4]) <= y_ray and y_ray <= math.max(v[2],v[4])
            ) then
                --print("Collision")
                return true
            end
        end
        radius = n
    end
end

function on.paint(gc)
    gc:setColorRGB(0,200,255)
    gc:fillRect(0, 0, 320, 106)
    gc:setColorRGB(100,100,100)
    gc:fillRect(0, 106, 320, 106)
    gc:setColorRGB(100,0,100)
    for i,v in ipairs(rays) do
        gc:drawLine(i, 108.5 - ((100/v * 20)/2), i, 108.5 + ((100/v * 20)/2))
    end
end

function on.arrowKey(key)
    if key == 'left' then
        facing = facing + 3
    elseif key == 'right' then
        facing = facing - 3
    end
    if key == 'up' then
        y = y - 1
    elseif key == 'down' then
        y = y + 1
    end
    raycast()
end

The wall originally looked like this:

But I have made changes around the ---------------, and now the wall looks like this:

I this supposed to occur?


texts:
I would like to intersect a thick ray (actually a cylinder) with an AABB.
The current code to perform intersection with the ray is the following.

template <class RealT>
bool CAABB<RealT>::Pick(const CPoint3T & base, const CVector3T & dir) const
{
    // SLAB based optimized ray/AABB intersection routine
    // Idea taken from http://ompf.org/ray/

    RealT l1 = (_minPnt.x - base.x) / dir.x;
    RealT l2 = (_maxPnt.x - base.x) / dir.x;
    RealT lmin = minT( l1, l2 );
    RealT lmax = maxT( l1, l2 );

    l1 = (_minPnt.y - base.y) / dir.y;
    l2 = (_maxPnt.y - base.y) / dir.y;
    lmin = maxT( minT( l1, l2 ), lmin );
    lmax = minT( maxT( l1, l2 ), lmax );

    l1 = (_minPnt.z - base.z) / dir.z;
    l2 = (_maxPnt.z - base.z) / dir.z;
    lmin = maxT( minT( l1, l2 ), lmin );
    lmax = minT( maxT( l1, l2 ), lmax );

    if( (lmax >= 0.0f) & (lmax >= lmin) )
    {
        // Consider length
        const CVector3T rayDest = base + dir;
        CPoint3T rayMins( minT( rayDest.x, base.x), minT( rayDest.y, base.y ), minT( rayDest.z, base.z ) );
        CPoint3T rayMaxs( maxT( rayDest.x, base.x), maxT( rayDest.y, base.y ), maxT( rayDest.z, base.z ) );
        return
            (rayMins.x < _maxPnt.x) && (rayMaxs.x > _minPnt.x) &&
            (rayMins.y < _maxPnt.y) && (rayMaxs.y > _minPnt.y) &&
            (rayMins.z < _maxPnt.z) && (rayMaxs.z > _minPnt.z);
    }
    else
        return false;
}

I would like to write a routine that takes an additional parameter for ray_thickness (diameter of the cylinder) and compute the intersection.