texts: Path solving for a game with a similiar pathing mechanic to Anno

texts:
I cant quite wrap my head around how to solve pathing in my game. The basic premise is you will place buildings and roads on a 2d field and then you will be able to create routes from one building to another where the pathing alghorithm should figure out the shortest path between them (if there is one).
Something to keep in mind is that the game is going to be quazi infinite scale (think factorio) and i cant think of a performant enough solution.
Currently what i am working with is that i have every straight Path segment saved as two (startPoint, endPoint) Vector2Int points in a list. And everytime a new road gets added or some road segment deleted i update this list depending on what happened, example situation:
I have this road
-----|
     |
     |
     |-----
This would be represented in my Roads list as:
0 = startPoint(0, 0) -> endPoint(5, 0)
1 = startPoint(5, 0) -> endPoint(5, 3)
2 = startPoint(5, 3) -> endPoint(10, 3)

I now add another road so we have something like this
-----|
     |
 ----|
     |-----
Which would change the road list to something like:
0 = startPoint(0, 0) -> endPoint(5, 0)
1 = startPoint(5, 0) -> endPoint(5, 2)
2 = startPoint(5, 2) -> endPoint(5, 3)
3 = startPoint(1, 2) -> endPoint(5, 2)
4 = startPoint(5, 3) -> endPoint(10, 3)

What i am doing currently when a new route is to be calculated is that i create a 2d bool array which i am feeding into a A* solver to get the shortest path so the above road gets transformed into:
1 1 1 1 1 1 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0
0 1 1 1 1 1 0 0 0 0 0
0 0 0 0 0 1 1 1 1 1 1

With some starting and endpoint.
This works fine for now but when the player will build on a huge size 10kx10k, i cant imagine generating 10kx10k bool array everytime will be a good solution.
Anybody knows how to optimize this?


texts: 3D line segment AABB collision, with hit normal?

texts:
I'm embarrassed I can't find this, but I'm wanting to detect intersection with a 3D line segment (not an infinite ray) with a 3D AABB, the AABB being defined as two Vec3f's which represent the Min and Max extents.  So the AABB can be arbitrarily-sized.  I also need the surface normal of the AABB, if there was a hit.

From looking at similar algorithms I at least know it seems good to calculate the inverse direction of the line beforehand, at least, if you're needing to check against multiple AABBs per frame.

I have

struct AABB
{
    VEC3F min;
    VEC3F max;
};

// a and b representing start/end points of the line segment
// returns true if intersects, also fills out "normal" if true
bool LineIntersectsAABB(const VEC3F& a, const VEC3F& b,
    const VEC3F& inv_dir, const AABB& aabb,
    VEC3F* normal);

The implementations I've found either do not find the hit normal, and/or they're intended for boxes/cubes where the three dimensions of the box are always equal length, which doesn't work for me.  Implementations seem to vary greatly, which is confusing for me (since I'm still trying to learn it), and, considering that I need the hit normal, I'd imagine that that may rule out certain implementations.


texts:
Are there common, tried and tested techniques for making sure that when displaying very large and very small objects, in a 3D environment, those objects don't display in front or behind each other?

The scenario I am thinking of is a small person object being closer to the camera than a single, large (for the sake of argument) wind mill arm. As the wind mill turns, the centre of the arm would pass in front and behind the person object's centre. However, depending on the position of the camera, the arm should only be shown as passing either behind or in front of the person object.


texts:
I'm fairly new to gamedev and have encountered a problem with the collision detection system.

The collision is essentially worked out like this:

for (int x = 0; x < playerprojectiles.Count; x++)
        {

            for (int i = 0; i < enemyships.Count; i++)
            {
                Vector2 projectilepos = new Vector2(playerprojectiles[x].position.X, playerprojectiles[x].position.Y);
                Vector2 enemypos = new Vector2(enemyships[i].position.X, enemyships[i].position.Y);

                Console.WriteLine("I=" + i + "  ,  " + "x=" + x);
                if (Vector2.Distance(enemypos, projectilepos) < 20)
                {
                    playerprojectiles.RemoveAt(x);
                    x--;
                    break;
                }

            }

        }

I can see the problem; it is having to iterate through too many items. However, I can't think of a way to overcome this.

Any help? To specify, can someone direct me to a method that would allow me to detect collision without impeding performance so severely.


texts:
I have this code:

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

public class Control : MonoBehaviour {

public int speed;
public Transform tf;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    if (Input.GetMouseButton(1))
    {
        tf.eulerAngles = tf.eulerAngles + new Vector3 (0,
Input.GetAxis("Mouse X") * speed, 0);
    }
}
}

I would like to know how to use this so that when I move my mouse and hole right click the character will turn but the mouse will not move from the center of the screen


texts: Strange behavior for "make x face y" algorithm (with video)

texts:
I know, I know, on the internet there are a lot of tutorial on how to get the angle between the center of two objects or "make x face y".

I have this code:

//  (180 / PI = 57.3065)
float AngleBetweenVectors(sf::Vector2f, sf::Vector2f);
float AngleBetweenVectors(sf::Vector2f a, sf::Vector2f b){
   return 57.3065f * atan2(b.y - a.y, b.x - a.x);
}

that get the angle, and then this code that I use to set the rotation:

float angle = AngleBetweenVectors(player_p, cursor.getPosition());
player.setRotation(angle);

where player_p is the player center position (a 50x50 square sprite), cursor is the cursor sf::Sprite I use and player is the player sf::Sprite.

But when I run it it gets this kind of problems: video here

As you can see on the border of the terrain it gets a little bit tricky. Why is that? I'm using two views, and this is the code of the main loop regarding views and drawing:

window.clear(sf::Color(0, 0, 0, 255));
window.setView(camera); // camera view
// start drawing
    terrain.draw(); // terrain blocks
    window.draw(player); // player sprite
    window.setView(cursor_camera); // cursor view
        window.draw(cursor); // cursor sprite (the circular one)
// end drawing logic
window.display();
window.setMouseCursorVisible(false); // no mouse pointer please

The player sprite in the video is the orange one, the black circle is the cursor sprite. The player sprite is moved via WASD and the cursor sprite via mouse movement.
Thanks.


texts: Developing interesting game mechanics when not an avid gamer

texts:
I've realized that though I like playing videogames, I find it much more entertaining to actually make them. This makes me wonder, if I'm planning to develop an [X]* game, do I need to be an avid [X] gamer? How can I develop interesting mechanics if I play that genre sparingly?

In order to get empirical answers, I'm more interested in listening to the opinion of those who have worked/are working in the game industry.  Are you and your co-workers avid gameplayers or "casual" gamers?  What about the Schafers, Carmacks, McGees and Gilberts of the industry (should anyone know any of them :) )?

*being [X] any game genre: Platformer, RPG, RTS, FPS, etc.

PS: I'm trying to make this question as subjective-less as possible, so feel free to point any improvements.


texts: How do I plot individual pixels using the XNA APIs?

texts:
If I wanted to fill my game screen with individually coloured pixels, how would I do this?

For example, if I wanted to write a 'game of life'-type game where each pixel was a cell, how would I achieve this using XNA?

I've tried just calling SetData() on a Texture2D object using a screen-sized array of Color values, but it complains with:

You may not call SetData on a resource while
it is actively set on the GraphicsDevice.
Unset it from the device before calling SetData.

How do I do as it asks? Or better still... is there an alternative, better, efficient way to fill a screen with arbitrary pixels?


texts: When should I use a fixed or variable time step?

texts:
Should a game loop be based on fixed or variable time steps?  Is one always superior, or does the right choice vary by game?

Variable time step

Physics updates are passed a "time elapsed since last update" argument and are hence framerate-dependent.  This may mean doing calculations as position += distancePerSecond * timeElapsed.

Pros: smooth, easier to to code

Cons: non-deterministic, unpredictable at very small or large steps

deWiTTERS example:

while( game_is_running ) {
    prev_frame_tick = curr_frame_tick;
    curr_frame_tick = GetTickCount();
    update( curr_frame_tick - prev_frame_tick );
    render();
}

Fixed time step

Updates might not even accept a "time elapsed", as they assume each update is for a fixed time period.  Calculations may be done as position += distancePerUpdate.  The example includes an interpolation during render.

Pros: predictable, deterministic (easier to network sync?), clearer calculation code

Cons: not synced to monitor v-sync (causes jittery graphics unless you interpolate), limited max frame rate (unless you interpolate), hard to work within frameworks that assume variable time steps (like Pyglet or Flixel)

deWiTTERS example:

while( game_is_running ) {
    while( GetTickCount() > next_game_tick ) {
        update();
        next_game_tick += SKIP_TICKS;
    }
    interpolation = float( GetTickCount() + SKIP_TICKS - next_game_tick )
                    / float( SKIP_TICKS );
    render( interpolation );
}

Some resources

Gaffer on games: Fix your timestep!
deWitter's game loop article
Quake 3's FPS affects jump physics—allegedly a reason Doom 3 is frame-locked to 60fps?
Flixel requires a variable timestep (I think this is determined by Flash) whereas Flashpunk allows both types.
Box2D's manual § Simulating the World of Box2D suggests it uses constant time steps.


texts:
Bit of a complex and lengthy question that, I'll admit, I don't quite understand very well yet so I will try and explain as best as I can.

Short Version: Is there a general c++/physx formula out there to calculate inertia tensors based off an objects shape?

Long Version:
For our physics, we need to specify x, y and z inertia tensors. Currently the way we do it is pretty much just a ratio based off of mass. So if an object is long on the X axis and thin on Y and Z, and the mass is 10000, we will set Z and Y to 7000 and X to 3000. (This isn't exact, but just to give an idea)

This works relatively well but our biggest problem is when there is joint instability somewhere, we have to keep guessing at tensors until we figure out what works best. This can become very time consuming if we have a very big physics simulation and one out of 20+ joints is causing all the others to lose stability.

What I am working on is a function that will take the bounding box of an object and hopefully calculate relatively accurate tensors. I have taken some of the math from http://en.wikipedia.org/wiki/List_of_moment_of_inertia_tensors and made a function that basically works like the following for similar rotations below.

Or if the rotation is on an end, like this:

So, this seems to give me results that are similar to the way we have been doing it, but I dont want to switch to this way without making sure that it will work for general use. Below is the code for my function based on the first image with a cube and center pivot.

NxVec3 CalculateInertiaTensor( VisBoundingBox_cl boundingBox, float m )
{
    float width = boundingBox.GetSizeX();
    float height = boundingBox.GetSizeZ();
    float depth = boundingBox.GetSizeY();

    float xTensor = 0.083f * m*(height*height + depth*depth);
    float yTensor = 0.083f * m*(width*width + depth*depth);
    float zTensor = 0.083f * m*(width*width + height*height);

    return NxVec3(xTensor, yTensor, zTensor);
}

I can't guarantee that this is the right way to do it (as the most accurate way is to use the actual shape instead of a bounding box) and i am not very familiar with inertia tensors and the math but it seems to return numbers fairly similar to what we were using. Anyone here happen to know if there is a better way to do this?


texts: Switching from Arcade to P2 physics in Phaser

texts:
so i just started using phaser for test

i've followed the tutorial in the phaser website  (making-your-first-phaser-game) everything is clear no problem .

but since i've making a pool game i need rotation on collision so i've switched to P2 ... suddenly everything moves and collides!

here is the live code

http://199.26.84.223/

i have 2 groups

sides ( sides of table ) and  balls

1 - i want sides to be immovable so i 've added

side.body.immovable = true;

to each object like in arcade ... it doesn't work ... how can i make objects immovable in p2 ?

    game.physics.startSystem(Phaser.Physics.P2JS);

    sides = game.add.physicsGroup(Phaser.Physics.P2JS);
    side = sides.create(0,0 , 'sideA');
    side.body.immovable = true;

2 - i dont want my player to collide with red balls only with white ball

so in arcade we had to define each collision otherwise they wouldn't collide

game.physics.arcade.collide(player , wball );

but here there is no defining everything collides with everything !

how can i make exception in ocllision so my player wouldn't collides with anything other then white ball (Wball) ?

3 - what happend to overlap ? or collide call back functions ? i need to add some holes to my table and make the balls dissapir on collide or overlap ... in the arcade i had it like this

game.physics.arcade.overlap( balls , holes ,  killBall  , null, this);
function killBall  ( b , h  ){ b.kill() ; }


texts: How can I avoid player see through the avatar?

texts:
I'm creating a SteamVR/HTC Vive game with Unity3D. I have a rigged avatar performing animations. Currently, if the player goes forward, it will see the moving eye balls and others inside the head. Since it's a small space, I can't allow him to step back to avoid the see-through caused by the collision.

What are other options to avoid it?

I'm thinking about setting up two colliders, one on the animated model and the other on the head of the player, so it can trigger a 360 dark screen to warn the player. How should I create the dark screen for the warning?


texts:
On the game I'm working on I wanted the singleplayer mode to use an integrated server to make adding more players via networking easier. The way I have it right now is I open a server and connects the client to my local address which works fine. But the problem is that if I play the game Singleplayer I don't want to leave anything exposed to the internet while only playing locally. Is there any way to limit the "range" of the server to only let communication happen via LAN?

Thanks in advance!

EDIT: I am using kryonet for networking. The game is written with LibGDX.


texts: Visual script editing software tool for creating game behavior logic

texts: Is there a visual script editing software tool in any game engine similar to Visual3d for  creating game behavior logic by non-programmers like designers?


texts:
The user clicks a unit to select it for a move.
Its going to move to wherever they click next.

It's centre c is point cf
They then click a point it is to move to.
This is to be where the unit centre moves to ct.

It is simple to work out the bearing between f and t and I know how to work out the delta.
What I would like to simulate is a unit wheeling.
Think in terms of a napoleonic battalion of a thousand men in 2 or 3 lines.
They don't just spin to face the new place they will move to.
Turning is handled by wheeling.
The unit rotates around the nearest corner until it faces in the direction of ct giving a rotated point rcf and then moves in a straight line finishing with a facing based on the bearing between rcf and ct.

I need to somehow calculate that wheel to get rcf.

My question is: how do I do that?

My first thought was calculate the delta offset from the unit facing and then rotate cf in relation to the nearest corner.

That cannot be right though.

If the unit starts facing directly north and you click west then that delta would be 90 degrees.
If you rotate the unit by the left corner by 90 degrees the facing would be out though.
The left corner would end up where I want the centre to be.

This is rather like the user is dragging a rectangle projected from the front of the unit around.
It rotates around either corner of the unit ending up with it's centre wherever the user clicks.

I'm  not using any gaming engine so I'll be writing any c# to do the trig.

Edit.

I don't think my drawing skills are really up to this but I'll see what I can come up with.

The unit must rotate around one corner such that it would move directly forward and end up with it's centre where the user clicks.

One way to work this out would be to calculate the rotated point degree by degree of rotation. Then project out at 90 degrees and see if that hits the required point.

If you imagine opening a door.

There's a stick attached to the centre.

A spot on the floor represents where the unit moves to.

As you open the door the stick moves and will eventually come to that point.

Here's an attempt at a drawing.

Bear in mind units can ( could ) only move straight forward but they can also wheel.

The unit starts off in blue position.

The user clicks at a point where the red arrow head is.

This is not on that blue line which projects at 90 degrees to it's centre which is it's original facing (or bearing).

That means it must wheel.

The delta is to the left so it's going to wheel (hinge) around the left corner.

Those guys on the left of the unit stay where they are. Those on the far end do the most movement.

When a line projected from it's centre crosses that point it needs to go to then it's got the right rotation.

This is represented by the red line.

So the unit starts it's move by wheeling from blue to red state.

That point it wants to get to is now straight ahead of it's centre.

So it can then move straight forward to it.

The dotted line is to exaggerate the fact I'm looking to somehow calculate where that central point has to be after it's wheeled and is ready to move directly forward.

Any ideas?


texts:
So I'm currently developing a 2D top down view java game. I have a mob called "Mutant" that currently does nothing. It generates a random number and depending on that number moves a few pixels in that direction. I"m trying to figure out how to make the mutant follow the player's x & y coordinates when the player comes near.

Here is what my mutant does currently:

    int xa = 0;
    int ya = 0;
    move = generator.nextInt(50) + 1;

    if(move == (50))
        ya = (random.nextInt(3) - 1) * random.nextInt(2);
        if (!hasCollided(xa, ya))

    if(move == 40)
        ya = (random.nextInt(3) - 1) * random.nextInt(2);
        if (!hasCollided(xa, ya))

    if(move == 30)
        xa = (random.nextInt(3) - 1) * random.nextInt(2);
        if (!hasCollided(xa, ya))

    if(move == 20)
        xa = (random.nextInt(3) - 1) * random.nextInt(2);
        if (!hasCollided(xa, ya))

    if(xa != 0 || ya != 0) {
        move(xa, ya);
        isMoving = true;
    } else {
        isMoving = false;
    }

Does anyone know how to make the mob simulate hostility towards the player? I haven't implemented a health system yet, I've only worked on the mob's A.I.


texts: Import FBX with multiple meshes into UDK

texts: I used this script to generate a few buildings that I was hoping to import into UDK. Each building is made of about 1000 separate objects. When I export a building as FBX and import the file into UDK it breaks it up into its individual objects again, so I was wondering how I would avoid this. Whether there was a tool to combine all of the objects into one mesh automatically before exporting or if I could prevent UDK from breaking them upon import.


texts: Using L-Systems to procedurally generate cities

texts: I'm currently making an app that focuses a lot on procedurally generated content. So far, I've successfully implemented the procedural generation of the terrain and shape of a map using simplex noise. I'm really pleased with how it looks. Now I'm trying to do the same for cities. I just need to generate a 2D layout of the streets and buildings. I've looked into it and it seems most people suggest using L-Systems. However I can't seem to wrap my head around them. I get the concept, but not the implementation into code. Does anyone have any code examples of L-Systems for procedurally generated cities, or suggestions on other ways to handle the cities?


texts:
How do I make walls in JOGL 2.0 in Eclipse?
So far, I've tried it with listing vertices, until I realised that was a C method while I need to work it in java.


texts: Calculating vertex normals to be able to have both sharp edges and smooth gradients

texts:
I'm computing area-weighted vertex normals, but lighting looks bad on meshes containing sharp edges and corners (e.g. cubes look 'blobby' as the light leaks onto the dark sides).

Is there a way of calculating/using vertex normals to preserve sharp edges and still have smooth regions? Ideally, without the need to create extra geometry (e.g. splitting faces adjacent to a sharp edge and creating new vertices).

Most sources talk about having different 'smoothing groups' which influence geometry generation.

Could someone explain what are "per-corner" normals?
From Libigl tutorial:
"Storing normals per-corner is an efficient and convenient way of supporting both smooth and sharp (e.g. creases and corners) rendering."


texts: background animation algorithm for single screen

texts: I’m writing simple strategy game (in xna), and would like to have an animated background. In my game all the actions happens inside one screen and thus standard parallax effect does not look appropriate. However, I found a video of a game with suitable background animation for my game http://www.youtube.com/watch?v=Vcxdbjulf90&feature=share&list=PLEEF9ABAB913946E6 (from 3 to 6s, while main character stays at the same place). What is the algorithm to do this stuff? It would be nice if someone can provide a reference for a similar example (language is not important).


texts: Is it always necessary to synchronize rendering in a game loop?

texts:
When writing a game loop from scratch in java for an android game applications, it is very common in many tutorials I have read that the keyword synchronized is used to synchronize update and rendering methods of the SurfaceHolder of the SurfaceView that manages the game objects.

I understand the basics of synchronization and the importance of synchronizing i.e. a method which should be called n times, and is called inside multiple threads. But what I want to know is if the synchronization block, that synchronizes around a SurfaceHolder, and contains the SurfaceHolder's draw (rendering) and update methods, needs the synchronization if the plan is to ONLY call the update and draw methods inside one single thread (the game loop).

To conclude, the main concerns I have are:

1)
Can the draw method inside the SurfaceView class be called by some inherrited, or just hidden method that I'm not aware of, so that I always have to synchronize the method?

2)
Is there any reason to NOT use the synchronization if it's not needed; i.e., is the functionality computationally heavy?

Please let me know if anything in my question is unclear :)


texts: How can I "glue" more objects to each other so I get one object? (It is for resizing models), couldn't find anything about it on the internet, but I'm dutch, so maybe that's why. Thank you very much!


texts:
I'm trying to calculate the speed of my sprites in Cocos2d but I'm having some difficulties. I'm not sure which units of time/speed cocos2d uses.

My background sprite moves 2 positions to left each .004 seconds.
I have a sprite that is generate each 3 seconds at position X0. The sprite moves until X1.
I would like that his speed would be the same as the background.

This is how I'm scheduling the background movement and the other sprite generation:

this.schedule(this.gameLogic, 3);
this.schedule(this.moveBg,.004);

this is how I'm changing the position of the background

var X = bg.getPositionX();
      var X1 = bg1.getPositionX();
      //alert(X);
      //alert(bg.getBoundingBox().width);
      bg.setPosition(X-2, 0);
      bg1.setPosition(X1-2, 0);

      if ( X < -bg.getBoundingBox().width) {
        bg.setPosition(bg1.getPositionX() + bg1.getBoundingBox().width, bg.getPositionY() );
      }

      if ( X1 < -bg1.getBoundingBox().width) {
        bg1.setPosition(bg.getPositionX() + bg.getBoundingBox().width, bg1.getPositionY() );
      }

And this is how I'm determining the X0, X1 and speed of sprite.

star.setPosition(winSize.width + star.getContentSize().width/2, Y);
        this.addChild(star);
        var from = winSize.width + star.getContentSize().width/2;
        var to = -(winSize.width+ star.getContentSize().width/2);

        // Create the actions
        //var actionMove = cc.MoveTo.create(2, cc.p(-star.getContentSize().width/2, Y)); // 3
        var actionMove = cc.MoveTo.create(14, cc.p(to, Y));

How can I determine the speed of star to be the same as bg?


texts: Implementing a large scale (planet-like) level in XNA 4.0

texts: What is the best way to implement continuous level throughout the game, using XNA? Imagine that I have a level with the size of a whole city (like in MMORPGs) however, the game will currently be mainly single-player. I'd like to be able to split this huge planet into parts which load asynchronously as I enter them. However, I also have other questions, such as, what happens with the part that I've come from. Its state should be stored on the disk, right? Then, what if I need to make some changes to that part, when the player comes back. Obviously, other characters should have done something rather than standing still. What's the best way to grab the state as I stored it, and modify it a bit, based on certain parameters, before I load it and let my player return.


texts:
I'm trying making my enemy goes to the nearest player to him but what i get is kind of hesitated or shaking. I think is from the first line on Update but i don't know how to solve it. Here is my script

private Animator enemy_anim;
private NavMeshAgent mAgent;
private GameObject[] player;
public GameObject[] dead_point;
public int farPoint, dead_point_number,player_number;
public float dist;
public bool enemt_run, enemy_atack = false;

void Start()
{
    mAgent = GetComponent<NavMeshAgent>();
    enemy_anim = GetComponent<Animator>();
    player = GameObject.FindGameObjectsWithTag("Player");
    dead_point = GameObject.FindGameObjectsWithTag("dead_point"); // 3 points
    enemy_dirction();

}

void Update()
{
    player_number = Random.Range(0,player.Length);
    dead_point_number = dead_point.Length;
    dist = Vector3.Distance(transform.position, player[player_number].transform.position);

    if (player != null && dist <= 5.1f)
    {
        mAgent.destination = player[player_number].transform.position;
        if (dist < 1.2f)
        {
            enemy_atack = true;
        }
        else
        {
            enemy_atack = false;
        }
    }
    else
    {
        if (dead_point_number > 0)
        {
            mAgent.destination = dead_point[farPoint].transform.position;
        }
        else
        {
            mAgent.destination = player[player_number].transform.position;

        }
        if (mAgent.remainingDistance <= 1.5f)
        {
            enemy_atack = true;
        }
        else
        {
            enemy_atack = false;
            enemt_run = true;

        }
    }

    mAgent.speed = 1.0f;

    enemy_anim.SetBool("run", enemt_run);
    enemy_anim.SetBool("attack", enemy_atack);
}// end update

void enemy_dirction()
{
    if (dead_point_number > 0)
    {
        farPoint = Random.Range(0, dead_point.Length);
        mAgent.destination = dead_point[farPoint].transform.position;
    }
    else
    {

    }
}


texts:
I am fairly new to openGL( 3 months ) and am asking for assistance in understanding the fundamentals behind gluLookAt().

Currently I have spent most of my time with openGL modeling scenes with fixed views, and I wanted to begin using gluLookAt combined with keyboard and mouse callbacks to "explore" my scenes. I created a simple program to play around with the functionality of gluLookAt when I first realized I may not understand fully what is happening.

My program creates a world using glOrtho(-4,4, -4,4, -4,4) confining my area somewhat around the origin (0,0,0) upon which I place the standard glutSolidTeapot(0.5). Then in an attempt to create a "camera" revolve around the teapot, in an idle callback function I write this

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt( cos(business), 0, sin(business), 0.0,0.0,0.0, 0.0,1.0,0.0 /*up vector*/ );
glutPostRedisplay();

Turns out, this worked. The view shows a revolving teapot. So I take another step and attempt to create an elliptical path around the teapot, multiplying either cos() or sin() (not both) by 2. This works as well but does not have the same effect I was expecting. The view rotates around the teapot, but I imagined along the path the teapot would "appear" to be closer at points, a zooming in effect of sorts. This leads to my question.

What exactly do I not understand about this?
  or..
Why is this not doing what I am expecting?


texts: How to build a turn-based multiplayer "real time" server

texts:
I want to build a TCG for mobile devices that is multiplayer over the web (not local wifi or bluetooth).  As a player plays cards I want the second player to see what is being played in "real time" (within a few seconds).  Only one player can play at a time.

Server requirements:
1) Continuously listens for input from Player 1
2) As it receives input from Player 1, sends the message to Player 2

I know some PHP, but it seems like unless I had a loop that continued until I broke it (seems like a bad idea) the script would just receive one input and quit.

On the mobile side I know I can open sockets using various frameworks, but what language allows a "stream-like" behavior that continuously listens/sends messages on the server?

Or if I'm missing something, what would be the best practice here?

EDIT: I might have not made it clear before, but the mobile apps are native not web-based.

I guess I'm asking for specific suggestions on what some of the best tools or platforms for this scenario could be used i.e., PHP sockets, etc.


texts: Is there a book describing how old-school 2D games were programmed?

texts:
This fellow over on Stack Overflow has many questions on how 8/16-bit era games were programmed. I'd like to point him at a basic primer on how game loops worked, static entity arrays and rendering loops and the like; but I don't know of any such book. (And it's been so long since I was there that I've totally forgotten how I learned in the first place.)

Is there any book describing how those old cartridge games were built; or in general any single resource I can point people at for native game programming basics?


texts: Why do my point lights have red X's on them in the Unreal editor?

texts: I've noticed through the first two tutorials I've done that Point Lights begin entering the viewport with red x's on them. When I build those don't turn on. It seems to be implying some limit to the number of Point Lights in a given space. Is that space the lightmass importance volume, or a given scene? I checked the Point Light tutorial explanation to no avail.


texts:
I have this shader:

   texture tex;
   sampler2D s = sampler_state {
      texture = <tex>;
   };

   int tWidth = 1;
   int tHeight = 1;
   int blurLength = 3;

   float4 ps_main(VS_OUTPUT Input) : COLOR0
   {
      float weight = 1.0 / (blurLength * blurLength);
      float2 pxSz = float2(1.0 / tWidth,1.0 / tHeight);
      float4 color = Input.Color * tex2D(s, Input.TexCoord.xy);
      float4 outC = 0;
      int x = 0;
      int y = 0;
        int numSubtr = (blurLength - 1) / 2;
        x -= numSubtr;
        y -= numSubtr;
        int count = 0;
        for(int i = x; i < x + blurLength; ++i)
        {
            for(int j = y; j < y + blurLength; ++j)
            {
                outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(i * pxSz.x,j * pxSz.y)) * weight;
            }
        }
      return outC;
   }

When I load it I get:

What could be wrong? (using hlsl ps 2.0 I think)

Thanks


texts: How to add global variables to a global list and then call the elements in a second scene in Unity, c#

texts:
I have the following problem with my app. I have a scene where the player is adding products with prices, by using strings. They are added to a Global Control file, which saves the data. Then, in this GlobalControl file, I want to add each of this strings in a list, so this way in the next scene I can call them and add them to a ScrollView, similar to order preview. Unfortunately, I can't manage to make it the right way and to add more than one item to the Order Preview.

My code is the following:
Scene one:

public void addToOrder()
{

    if (m_currentSelectedModel <= 33)

    {
       GlobalControl.orderContent =
       menuItemNamesString[m_currentSelectedModel];
       GlobalControl.priceContent =
       menuItemPriceString[m_currentSelectedModel];
    }

}

My GlobalControl is the following:

public class GlobalControl : MonoBehaviour
{
    public static GlobalControl control;

    //the global variables

    static public string orderContent;
    static public string priceContent;

    //global lists
    static public List<string> orderItemsList = new List <string>();
    static public List<string> orderPricesList = new List <string>();

    void Awake()
    {
        if (control == null)
        {
            DontDestroyOnLoad(gameObject);
            control = this;
        }

        else if (control != null)

        {
            Destroy(gameObject);
        }

    }

    private void Start()
    {

        //adding the current selection to the respective list
        if (orderContent != null)
        {
            orderItemsList.Add(orderContent);
        }

        if (priceContent != null)
        {
            orderPricesList.Add(priceContent);
        }

    }

And last my OrderPreviewManager, which is in scene 2, is:

void Start ()
{
    //my current solution, which does not retrieve a variable from a list

    curOrderContent = GlobalControl.orderContent;
    curPricetContent = GlobalControl.priceContent;

    AddSelectedItemToOrder();
    AddSelectedItemPriceToOrder();
}

//the two methods for adding the string to text components into a scroll
  view

void AddSelectedItemToOrder()
{
    GameObject gameObject = new GameObject("Child");
    gameObject.transform.SetParent(orderContentView.transform);

    gameObject.AddComponent<Text>().text = curOrderContent;
    gameObject.GetComponent<Text>().font =
    Resources.GetBuiltinResource(typeof(Font), "Arial.ttf") as Font;
    gameObject.GetComponent<Text>().color = Color.black;
    gameObject.GetComponent<Text>().fontSize = 20;
}

  //similar to the previous method but for the prices

void AddSelectedItemPriceToOrder()
{
    GameObject gameObject = new GameObject("Child");
    gameObject.transform.SetParent(pricetContentView.transform);

    gameObject.AddComponent<Text>().text = curPricetContent;
    gameObject.GetComponent<Text>().font =
    Resources.GetBuiltinResource(typeof(Font), "Arial.ttf") as Font;
    gameObject.GetComponent<Text>().color = Color.black;
    gameObject.GetComponent<Text>().fontSize = 20;
}

My question is: why does this only insert one item in scene 2?


texts: Should I call SDL_ConvertSurface right before SDL_CreateTextureFromSurface?

texts:
Is there a significant benefit (or any benefit at all), when I convert SDL surface and create a texture from optimized surface?

Here is example of what I mean:

loadedSurface = IMG_Load(path);
optimSurface = SDL_ConvertSurface(loadedSurface, SURFACE_FORMAT, 0);
loadedTexture = SDL_CreateTextureFromSurface(renderer, optimSurface);
//return loadedTexture and destroy the rest

/*  VS  */

loadedSurface = IMG_Load(path);
loadedTexture = SDL_CreateTextureFromSurface(renderer, loadedSurface);
//return loadedTexture and destroy the rest

According to SDL2 documentation

  This function is used to optimize images for faster repeat blitting. This is accomplished by converting the original and storing the result as a new surface. The new, optimized surface can then be used as the source for future blits, making them faster.

Its tied with surface blitting, but I can't say its effect "within" texture.

Thank you


texts: Mods for Minecraft Server - how does it work?

texts:
Minecraft server comes as a single jar. How are mods developed? How do they interact with the original jar? What is there under the hood?

What technologies are involved there? I'm mostly a C++/Python guy, but I'd like to learn something about mods development.


texts:
I am a beginner with PyGame and am currently making a simple game using but I am having difficulty with the collision detection. When the game runs, the response to the collision detection (printing the score and removing the sprite) is very slow. The two responses occur at the same time but much later than when the sprites actually collide. I was wondering how I could change my code to fix this?

My code is here: http://pastebin.com/9t2hcAxH and I think the issue is in the game loop at the bottom.


texts:
Is there a simple way to change the speed* of unity's physics engine like in the game SuperHot?

Any script language is ok but javascript is preferred.

*I am not sure if speed is the correct term.


texts:
I often develop 2D games. I would like to know if there's a program like EvalDraw out there, that makes it easy to quickly make (for example) a square, out of a black quad, and then write some shader code, and see how that shader code modifies the square in realtime.

That would be really great for my future development processes.

Edit:
The shader tool must work with HLSL.


texts: Why has my refractive water shader become reflective

texts:
So I was making a water shader in unity and well it looked fine in the scene view but as soon as I went into the game view the refraction texture basically flipped up 180 degrees and made it look like the water was reflective. The problem with this is that it breaks the transparency of the shader.

Scene View (how it should look):

Game View (how it does look):

Shader: (I can't post more than 2 images)

Part of the shader:

float4 Lerp2=lerp(Tex2D2,float4( 0.0, 0.0, 0.0, 0.0 ),_Refraction.xxxx);
float4 Subtract0=Lerp2 - _RefractionCorrection.xxxx;
float4 Add2=((IN.screenPos.xy/IN.screenPos.w).xyxy) + Subtract0;
float4 Tex2D0=tex2D(_GrabTexture,Add2.xy);


texts: Using two shaders instead of one with IF statements

texts:
I've been working on porting a relatively large opengl ES 1.1 source to ES 2.0.

In OpenGL ES 2.0 (which means, everything uses shaders), I want to draw a teapot three times.

The first one, with a uniform color (ala the old glColor4f).
The second one, with a per-vertex color (the teapot has its array of
vertex color as well)
The third one, with per-vertex texture
And maybe a fourth one, with both per-vertex texture and color. And
then maybe a 5th one, with normals as well..

There are two choices I have with implementation, as far as I know. The first is to make a shader that supports all of the above, with a uniform that is set to change the behavior (e.g use the singular color uniform, or the per-vertex color uniform).

The second choice is to create a different shader for each situation. With some custom shader preprocessing, it's not that complicated to do, but the concern is the performance cost in switching shaders between drawing objects. I've read that it's not trivially small.

I mean, the best way to go about this is to build both and measure, but it'd be good to hear any inputs.


texts: More Efficient Data Structure for Large Layered Tile Map

texts:
It seems like the popular method is to break the map up into regions and load them as needed, my problem is that in my game there are many AI entities other than the player out performing actions in virtually all the regions of the map. Let's just say I have a 5000x5000 map, when I use a 2D array of byte's to render it my game uses around 17 MB of memory, as soon as I change that data structure to a my own defined MapCell class (which only contains a single field: byte terrain) my game's memory consumption rockets up to 400+ MB. I plan on adding layering, so an array of byte's won't cut it and I figure I'd need to add a List of some sort to the MapCell class to provide objects in the layers. I'm only rendering tiles that are on screen, but I need the rest of the map to be represented in memory since it is constantly used in Update.

So my question is, how can I reduce the memory consumption of my map while still maintaining the above requirements? Thank you for your time!

Here's a few snippets my C# code in XNA4:

public static void LoadMapData()
    {
        // Test map generations
        int xSize = 5000;
        int ySize = 5000;
        MapCell[,] map = new MapCell[xSize,ySize];
        //byte[,] map = new byte[xSize, ySize];

        Terrain[] terrains = new Terrain[4];
        terrains[0] = grass;
        terrains[1] = dirt;
        terrains[2] = rock;
        terrains[3] = water;

        Random random = new Random();

        for(int x = 0; x < xSize; x++)
        {
            for(int y = 0; y < ySize; y++)
            {
                //map[x,y] = new MapCell(terrains[random.Next(4)]);
                map[x,y] = new MapCell((byte)random.Next(4));
                //map[x, y] = (byte)random.Next(4);
            }
        }

        testMap = new TileMap(map, xSize, ySize);
        // End test map setup

        currentMap = testMap;
    }

public class MapCell
{
    //public TerrainType terrain;
    public byte terrain;

    public MapCell(byte itsTerrain)
    {
        terrain = itsTerrain;
    }

    // the type of terrain this cell is treated as
    /*public Terrain terrain { get; set; }

    public MapCell(Terrain itsTerrain)
    {
        terrain = itsTerrain;
    }*/
}


texts: Collision detection against specific sprite shape using XNA with Farseer Physics?

texts:
I am making a 2D XNA Game, using Farseer Physics for collisions.

I need collisions to be resolved against the actual shape of the sprite image, ignoring transparent pixels, rather than against the edge of the bounding rectangle.


texts: How to make game playable in all mobile screen resolution using Unity Cinemachine with perspective mode?

texts:
I want my 2D game to be playable (auto scale) in all screen resolution. I'm using Cinemachine & under "perspective" mode. I found tutorial to change the screen in "orthographic" mode but there is no answer for "perspective" mode using Cinemachine. Please help on what setting must be done in Cinemachine or if there is any scripting that I can use. Thanks a lot.

NB: I tried to add a script as in  below link. But it doesn't work. Perhaps it's because I'm using Cinemachine instead of normal main camera. Link: Scale camera to fit screen size unity

Edit: Added picture of the "perfect" view I want below.

Image "expanded" to left & right when I change to "free aspect"


texts: Minecraft Optifine - where is the zoom class?

texts: I'm working on a mod where I want to have a zoom feature like Optifine. To start out, I want to try messing around with the zoom in the actual Optifine mod. There are a lot of .class files, and I don't want to decompile all of them one by one, so if anyone knows which one(s) have the zoom that would be super helpful.


texts: Re scaling an object from its current scale to a scale of 0

texts:
I want to have an animation which starts at a starting scale of whatever the current gameObject's scale (i.e 1, 1, 1 or 2, 3, 2) is which then end at a scale of 0, 0, 0.

The problem is that Unity's animator has fixed values and so, I cannot make one animation that would easily apply to every object.

I'm fine with using C# code to do this but I haven't been able to find anything that works yet. Thanks for your help!


texts: Libgdx: scrolling background for preview screen

texts:
Good day, I have been coding for quite a while now and I'm at a certain point where I am having difficulties on solving something. I've been creating a preview screen which contains the following:

reads .txt file and stores them in an array which will be displayed on the screen.
the text will have an animation which will be moving upwards like a Star Wars type of intro.
the background of the screen will also move upwards.

The problems that I have encountered are the following:

my text did not fit on the screen, but I did try to change the font and the font size and also did change the spacing in the .txt file.
the text always starts in the middle of the screen which it should start at the bottom of the screen.
the background is buggy, tried to debug it but still can find a solution for a parallaxbackground(scrolling background)

and here is the code.

public class PreviewScreen implements Screen {

    private static DugManMainClass game;
    private SpriteBatch batch;
    private OrthographicCamera camera;
    private Texture tx1 = Assets.bgmenu;
    private BitmapFont font = Assets.menufont2;
    private final static List<String> lines = new ArrayList<String>();
    private static int time = 0;
    private float temp = 0;
    private Sprite s;

    public PreviewScreen(DugManMainClass game) {

        this.game = game;

        //reads .txt file and stores them in an array

        try
        {
            BufferedReader br = new BufferedReader(new InputStreamReader(Gdx.files.internal("previewtext.txt").read()));
            String line = "";
            while ((line = br.readLine()) != null) {
                lines.add(line);
            }
            br.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    @Override
    public void render(float delta) {

        float w = s.getHeight();

        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        //temp is a timer which will do the animation effect for the text and background
        temp += Gdx.graphics.getDeltaTime();

        while(temp>1.0f/60.0f)
        {
            PreviewScreen.tick();
            temp -=1.0f/60.0f;

            //here is my problem for the background

            s.setU(temp+1f);
            s.setU2(temp+1f);

        }

        batch.setProjectionMatrix(camera.combined);
        batch.begin();
        s.draw(batch);

// i commented this out because i waited to draw my sprite which is the background text(parallaxbackground)
//      batch.draw(s, 0, -(temp / 10 % w));
//      batch.draw(s, 0, -(temp / 10 % w) + w);

        int yo = time / 4;

        //this is where the the text problem is
        for (int y = 0; y <= 420 / 12; y++)
        {
            int yl = yo / 12 + 420 / 12 - y;
            if (yl >= 0 && yl < lines.size())
            {
                font.draw(batch,lines.get(yl), (800 - 30 * 12) / 2,  y * 12 + yo % 12);
            }
        }

        batch.end();

    }

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

    @Override
    public void show() {

        batch = new SpriteBatch();

        float w = 800;
        float h = 420;

        camera = new OrthographicCamera();
        camera.setToOrtho(false, w, h);

        tx1.setWrap(TextureWrap.Repeat, TextureWrap.Repeat);

        s = new Sprite(tx1);
        s.setPosition(0, 0);

        Assets.bgsound3.play(1f);

    }

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

    public static void tick() {
        time++;

        if (Gdx.input.isKeyPressed(Keys.ENTER) || Gdx.input.isTouched()) {
            game.setScreen(new MainMenuScreen(game));
            Assets.bgsound3.stop();
        }

        if (time / 4 > lines.size() * 10 + 250) {

            game.setScreen(new MainMenuScreen(game));
            Assets.bgsound3.stop();
        }
    }

}


texts:
Edit 2 - clarification

Just to clarify, the issue I have at the moment is how I specify a time (in seconds) for a complete revolution to occur.  My delta is fixed and is 1/ticks per second (1/60).  As you can see with my linear sprite movement, I have a 'time' variable which is where I specify (in seconds) how long the sprite should take to travel the length (or height) of the screen. I'm looking at how I do this for circular movement.

Edit 1 - Results from suggestions

See at end of question.

Background

When moving my sprites along a straight path, I'm using delta so I can get the same rate of relative motion on all devices like so:

spriteGridX = 240/480;  //I start out with a virtual 'Grid' so I can scale position to all resolutions etc so 240/480 would place the sprite at the center of the screen (X)

spriteScreenX = spriteGridX * width;  //Scale to physical screen where width is the width of the current devices screen (viewport)

spriteXTime = 8f; //8 being the amount of time in seconds that this sprite will take to traverse the entire width of the screen

spriteXVel = 1/spriteXTime; //Velocity that will be used to move the sprite along the virtual grid position

So, when I need to move the sprite, I simply do the following:

spriteXGrid+= (spriteXVel * Delta) //+= for right -=for left. I'm using a fixed delta time
spriteScreenX = spriteGridX * width; //And again, convert to usable screen position for current device
drawsprite(spriteScreenX, SpriteScreenY); //Draw the sprite (drawSprite is just a method I've written to draw openGL quads and it takes the screen X and Y as coordinates - spriteScreenY not shown here but essentially same as X with height instead of width.

Now, I need to have a sprite move along a circular path. So far, I have a test up and running which directly acts on the 'screen' coordinates of the sprite directly like so:

Java Code

int rad = 25;
float angle = 50;

spriteScreenX-=Math.round(rad*Math.cos(angle));
spriteScreenY+=Math.round(rad*Math.sin(angle));
angle+=.1;

The Problem

Now, the above does work, but the sprite completes it's circular path way too quickly (it's doing approximately 1 revolution per second).

So my question is:

Am I doing this correctly and if so..........
How do I slow this down?  I won't particularly need to keep changing the speed, I just want to be able to set it initially.

Would really appreciate some pointers.

Edit 1

When I put the following the code above I get the following result:

If I put the following:

spriteScreenX-=Math.round(rad*Math.cos(angle*Math.PI/180*delta));
spriteScreenY+=Math.round(rad*Math.sin(angle*Math.PI/180*delta));
angle+=.1;

Or:

spriteScreenX-=Math.round(rad*Math.cos(angle*delta));
spriteScreenY+=Math.round(rad*Math.sin(angle*delta));
angle+=.1;

Something like this happens:


texts:
I'm beginner here, I'm trying to instantiate a single object every specific duration, either form the left of the screen or from the the right, at the same time I want this object to move to the other side of the screen

So the troubles I'm facing here are:

sometimes 2 objects are being instantiated at the same time.
the objects move in the direction that are defined in the first if statement (both objects on the left and the right move in one direction)

the part where I instantiate objects is in the script(smallFishes) that's attached to an empty gameobject is :

void Start () {
    timer = gameObject.AddComponent<Timer>();
    width = 2f;
    timer.Duration = 3;
    timer.Run();
    left = Resources.Load("Left") as GameObject;
    right = Resources.Load("Right") as GameObject;

}
void Update () {

    if (timer.Finished)
    {
        lr = Random.Range(1, 3);
        if (lr == 1)
        {
            var generetx = -8.8f - width / 2;
            Instantiate(left, new Vector2(generetx, Random.Range(-4.8f,4.8f)), Quaternion.identity);
        }
        else
        {
            var generetx = +8.8f + width / 2;
            Instantiate(right, new Vector2(generetx, Random.Range(-4.8f, 4.8f)), Quaternion.identity);
        }
        timer.Duration = 3;
        timer.Run();
    }

}
public int state
{
    get { return lr; }
}

the part where I make the object move from the script that's attached to the object prefab:

void Start () {
    small = gameObject.AddComponent<smallFishes>();
    rb2d = gameObject.GetComponent<Rigidbody2D>();
}

void Update()
{
    var fishes = GameObject.FindGameObjectsWithTag("small");
    if (fishes!=null)
    {
        if (small.state == 1)
        {
            moveright = new Vector2(4 * Time.deltaTime, 0);
            rb2d.AddForce(moveright, ForceMode2D.Impulse);
        }
        else
        {
            moveleft = new Vector2(-4 * Time.deltaTime, 0);
            rb2d.AddForce(moveleft, ForceMode2D.Impulse);
        }
    }
}

Thanks in advance.


texts: How can I solve this SAT direct corner intersection edge case?

texts:
I have a working SAT implementation, but I am running into a problem where direct collisions at a corner do not work for tiled surfaces. That is, it clips on the surface when going in a certain direction because it gets hung up on one of the tiles, and so, for example, if I walk across a floor while holding both down and left, the player will stop when meeting the next shape because the player will be colliding with the right side rather than with the top of the floor tile.

This illustration shows what I mean:

The top block will translate right first and then up.

I have checked here and here which are helpful, but this does not address what I should do in a situation where I don't have a tile-based world. My usage of the term "tile" before isn't really accurate since what I'm doing here is manually placing square obstacles next to each other, not assigning them spots on a grid.

What can I do to fix this?


texts: Set a 'chance to spawn' for each GameObject in an array

texts:
I have an array of gameObjects in a spawner. I want to randomly spawn these gameObjects based on a weighted chance. I want to be able to manually set in the Inspector a percentage chance that an object from the array will spawn.

So when I drag my gameobjects into the array, how do I also manually set a percentage chance that it will be selected?


texts: What does the graphics card do with the fourth element of a vector as the final position?

texts:
From this question it appears you would want a four-element position vector, as it is simpler to modify its position with matrix multiplication.

On its own this would imply the fourth element should simply be ignored when considering it as a representation of a 3D point (assuming no transformation), but I know this is not true, as when I supply a vector4 to the GPU, if the fourth element is not one, it is not rendered - why?

What is the significance of the fourth element, once it is in the rasterizer?

EDIT: On review this question was somewhat poorly worded; it would be more accurate for the second paragraph to say: "if the value of the fourth element is not within a certain range, it is not rendered 'correctly'/'as expected'".


texts: Unity - GameObject jumps to wrong point at start

texts:
In Unity, I have this problem where the Game Object this script is attached to jumps to Z position 0 as soon as the game runs. In the Editor, I have the Game Object set as Z position -50. I want startPos to read this position (-50) and use it when newPos is updated.

Why does startPos get updated immediately to 0?

using UnityEngine;

public class MoveOutScript : MonoBehaviour {

    public float speed = 10f;
    float startPos;
    Vector3 newPos;
    float changePerSecond2;

    public void Start()
    {
        startPos = transform.position.z;
        changePerSecond = speed * Time.deltaTime;
    }

    public void Update()
    {
        #region Move sprite away steadily

        newPos.z += changePerSecond;
        newPos.z = Mathf.Clamp(newPos.z, startPos, 15f);
        transform.localPosition = newPos;

        #endregion
    }
}


texts: How to do collision detection on marching cubes terrain?

texts:
I'm writing the physics part of my game engine. The world uses the marching cubes algorithm  on a 3d perlin noise to make the terrain.

How do I do collision detection on the resulting mesh? I can't use SAT since the terrain is not convex and subdividing it into smaller convex parts seems to be nearly impossible.

What is the best collision detection algorithm for such a mesh? The objects that are supposed to collide with the terrain can be any convex polyhedron.

EDIT: The terrain is not "cubed" (like minecracft). The terrain is smooth with slopes. This is pretty close to what my terrain looks like (this is NOT my video): https://www.youtube.com/watch?v=-4rA3fdKWQA

I am looking for a general collision detection here. I need the point(s) of contact and the normals so that I can put these into my collision resolver.

Example of usage is throwing a box onto the terrain and it should roll and bounce approximately like it would in the real world.


texts: Why does Google keep rejecting my update for my game?

texts:
I'm trying to push an update to my game that is on the Google Play Store. I've submitted the update over 4 times and Google keeps rejecting it due to the type of ads that are being displayed. I'm using Unity Ads and I've disabled all ads that would be inappropriate such as gambling, dating, 18+..etc.

The annoying part is that I have the game already on the store and I never disabled any of the ads or filtered the ads. Unity Ads are an approved service by Google. Is there something that I am missing? I also have a privacy policy in place as well? Is there something that I could do to keep it from getting rejected? How does Google test games or apps for ad content?!

Update So I've tired submitting the update over 8+ times and it's still being rejected. I've disabled the banner ads and I've changed the ads to not show ads rated for 5+. I'm at a loss for why it's being rejected. I've emailed Google over it and they just send me the same information they sent when it was rejected the first time. Still no answer..

(https://i.stack.imgur.com/wDlj1.jpg)!

(https://i.stack.imgur.com/OHGPi.jpg)


texts:
I am trying to implement server-side movement using box2d on libgdx client and planck-js(box2d for javascript)  on nodejs server.
I am running box2d world on both client and server.

Before server i was moving player on client with applying force on input

player.body.applyForce( Vector2(-4.5f, 0f), player.body.worldCenter, true)

Now from client to server i am just sending input data and applying force on server side:

Client if left key pressed:

 var inputData:JSONObject = JSONObject()

            inputData.put("type", "left");
            inputData.put("x", player.body.worldCenter.x);
            inputData.put("y", player.body.worldCenter.y);
            socket.emit("inputFired",inputData)

So server gets this data and applies force code to move player on server side.

    var movePlayer = find_playerid(this.id);
    if (!movePlayer) {
        console.log('player does not exist');
        return;
    }
      console.log(data)
      var positionVector = Vec2(data.x,data.y)
      if(data.type =="left"){
        var impulseVector = Vec2(-4.5,0.0)

      }else if(data.type =="right"){
        var impulseVector = Vec2(4.5,0.0)

      }else if(data.type=="up"){
        var impulseVector = Vec2(0.0,4.5)

      }else if(data.type=="down"){
        var impulseVector = Vec2(0.0,-4.5)

      }
  movePlayer.body.applyForce(impulseVector,positionVector,true)
      movePlayer.x = movePlayer.body.getPosition().x
      movePlayer.y = movePlayer.body.getPosition().y
      console.log("new position")

After this point what is confusing me is what should i really return to client ? If i just return position values of body after applying force,how im gonna position client side body according to this ?


texts: Predict future position of a moving body in Phaser arcade physics

texts:
I am looking for an equation for predicting the future position of a moving arcade physics body in Phaser 3. The body has drag applied and isDamping set to true. Phaser applies the drag using the following run on each update (showing x axis only but same applies to y).
//  Damping based deceleration
dragX = Math.pow(dragX, delta);

velocityX *= dragX;

Given the above, how would I write a kinetic equation to predict the future position?
I am currently using the method below, where I am iterating over frames to calculate the position accumulatively. But this is inefficient and inelegant so would prefer a solution which estimates the position without any looping.
public futurePosition(timeInSeconds: number): Phaser.Math.Vector2 {
  const DELTA = 1 / 60; // Assume we are running at 60fps
  const DRAG = 0.3; // Drag value
  const position = this.position.clone(); // Current position of body
  const velocity = this.body.velocity.clone(); // Current velocity

  // Inefficiently looping through frames
  for (let i = 0; i < timeInSeconds / (DELTA * 1000); i++) {
    velocity.x *= Math.pow(DRAG, DELTA);
    velocity.y *= Math.pow(DRAG, DELTA);
    position.x += velocity.x * DELTA;
    position.y += velocity.y * DELTA;
  }

  return position;
}

Any help appreciated. Thanks.


texts: Left-handed version of the reversed depth projection with infinite far plane

texts:
Let's say that I have standard left-handed WorldToView and ViewToScreen row-major matrices in the same vein as the DirectX D3DXMatrixPerspectiveLH functions, like so:

EXVector vView = NormalizeVector(LookAt() - m_Position);

float fDotProduct = DotProduct(m_WorldUp, vView);

EXVector vUp = NormalizeVector(m_WorldUp - fDotProduct * vView);

// Generate x basis vector (crossproduct of y&z basis vectors)
EXVector vRight = CrossProduct(vUp, vView);

// Generate the matrix
row0.Set(vRight.x, vUp.x, vView.x, 0);
row1.Set(vRight.y, vUp.y, vView.y, 0);
row2.Set(vRight.z, vUp.z, vView.z, 0);
row3.Set(-DotProduct(m_Position, vRight),
         -DotProduct(m_Position, vUp),
         -DotProduct(m_Position, vView), 1);

EXMatrix mWorldToView(row0, row1, row2, row3);

Here's the left-handed mViewToScreen / projection matrix:

float zNear  =    0.001f;
float zFar   = 1000.000f;
float Aspect = DisplayHeight() / DisplayWidth();

float sinfov, cosfov; qsincosf(VFOV() / 2, sinfov, cosfov);
float cotfov = cosfov / sinfov; // cos(n) / sin(n) = 1/tan(n)

float w = Aspect  * (cotfov);
float h =   1.0f  * (cotfov);
float Q = zFar / (zFar - zNear);
float R = -Q * zNear;

row0.Set(w, 0, 0, 0);
row1.Set(0, h, 0, 0);
row2.Set(0, 0, Q, 1);
row3.Set(0, 0, R, 0);

EXMatrix mViewToScreen(row0, row1, row2, row3);

Many things like map/object culling depend on this fact:

// View to cull matrix
Q = (       zFar + zNear) / (zFar - zNear);
R = (2.0f * zFar * zNear) / (zFar - zNear);

row0.Set(w, 0, 0, 0);
row1.Set(0, h, 0, 0);
row2.Set(0, 0, Q, 1);
row3.Set(0, 0, R, 0);

EXMatrix mViewToCull(row0, row1, row2, row3);

Does anyone know how to derive the infamous "reverse depth with infinite far plane" from the original blog post for mViewToScreen and mViewToCull? Every single reference I have found (nlguillemot and nVidia, for example) is in the right-handed space.

Normally I am able to figure things out visually, but 4D matrices are a headache.


texts:
Currently in my game engine when a user selects a large number of units and commands them to a target each unit finds its own path using Jump Point Search. The performance of this is generally OK. What I dislike is that over longer distances all the paths tend to converge so that the units end up competing to reach the path's nodes.

My solution to this is to group the units together and create a path from the unit closest to the centre of the group. I then use steering behaviours / flocking to sensibly navigate the group along the path to the target.
The problem I am struggling with now is that the user may select many units which aren't physically grouped together. Some may be very far away from each other, others may be close but separated by walls, etc. It is not really possible to create one path for such a group.

What I need is an algorithm that can create discrete physical groups from a larger set of units like in the image above. I'm at a loss as to where to start with this. I had thought of maybe using some sort of brushfire algorithm, adding units to the group as they're discovered and stopping at walls or too much empty space. I'd rather not reinvent the wheel though and would appreciate any help anyone can give me.


texts: Using Unity Post Processing v2, how can I apply processing effects to just the UI?

texts:
I am using Unity 2018.3 with HDRP 4.9, and Post Processing 2.1.3.

I would like to apply post processing effects (i.e bloom) to the UI only.

I tried the 2 camera approach, but still can't get it working correctly.

I have a post processing volume that is global, and also one that is global but for the UI.  Not sure if this is correct.  Basically I don't want the first processing volume to apply to the UI.

I can apply post processing if I ignore all this second camera stuff and set the canvas to screen space camera.  I then get the effects like bloom applied to the UI.  However, I want to have different post processing for the UI, the global bloom is too much.

First image is the UI Camera.

Second image is the main camera.

Third image is the Canvas for the UI.


texts:
I'm currently trying to create an area that would somehow push objects to a specific direction. (and also apply angular drag if possible)

I'm currently new to Unity and Godot. I have already seen this in Unity tutorial and checking if this is also possible in Godot.

I have a RigidBody2D (with gravity) that falls down on an Area2D.

I'm currently stuck at this code..

func _on_Area2D_body_entered(body):
    body.apply_impulse(Vector2(),Vector2(0,-50))

..but it only applied it once after entering the are and not continuously applying force until the object exited the area. I tried using add_force but it gave the object a constant speed and direction and not falling back down.


texts:
I am trying to define an AI behavior where if a conditional (MyCondition) is false, execute the task. I know I can do this as follows:

import myCondition?:"tech.otter.something.MyCondition"
import otherTask:"tech.otter.something.OtherTask"

root
  selector
    myCondition? # i.e. if !myCondition then otherTask
    otherTask

Now I'd like to use the snazzy guard syntax like so:

root
  (myCondition?) otherTask

The problem is that I really need otherTask to fire when the guard (myCondition?) is false. Is there a way to do this shy of defining a "MyInvertedCondition" task?


texts: how to ADD a NEW entity/item/effect to Minecraft Java

texts: In Minecraft Java, I am creating many resource packs by myself (no studio or external resource) so, I want to ADD a new file/entity/element/items/etc. to the game to not replace an old item because EVERY item/effect/entity has SOME use in the game. In conclusion: how I can ADD [not replace] a file in the game and give it custom physical and mental properties?


texts: How to make Unity Layout switch while in Play mode

texts:
I'm looking for a way to auto switch the Unity layout when I go to play mode.

I want to Unity Editor layout automatically changes to my preset layout when I click on Play button and When I stop the game, It goes back to the default layout.


texts:
I found this cool website for game development and it has a list of easing functions:

Although the site contains a description of what they're for, it goes over my head.  What are easing functions and what are they used for?

Update

I found a better example of the functions themselves from Phaser.io's source code.  These functions are much simpler than the answers here would suggest.  They only take one parameter, k.  As part of the answer, I'd like to know how to use these.


texts: Unity 2D Prevent knockback effect from 2D Translation

texts:
I've just started looking into developing with Unity, and read through the tutorials and introductions. For my first project, I decided to try something simple - so a breakout clone. However, when the ball hits the player, the player gets knocked down a few pixels.

The player and ball have BoxCollider2D attached to them, and the player also has a RigidBody2D attached to it. The player is also checked as a "static" object.
The ball moves towards the player using transform.translate().

Here is the balls script:

using UnityEngine;
using System.Collections;

public class BallScript : MonoBehaviour {

    public float speed;
    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        this.transform.Translate (Vector3.down * speed * Time.deltaTime);
    }

    void OnCollisionEnter2D (Collision2D col) {
        this.speed = -speed;
    }

}


texts:
How do I convert a texture coordinate, like 1,0 into a texel form(a single value?). Like in the image below, what is the value of Q22 in texel?

I'm in directx 11.


texts:
I have set particle system of duration 5 seconds.

But, I wouldn't  like particle system to repete but to be frozen in fourth second forever.

How to do that?


texts:
I am not sure if I am missing something but I was thinking about how text entities are drawn on a scene, are they drawn with an offset depending on the length of the text? I notice that when I add a new Text element at say new Text(10, 20,..... and the actual text content is 50 words long the text is drawn far over to the right and when I use the same instance with a smaller text content that text is drawn closer to the actual coordinates I need. Should I always recalculate X and Y vectors with respect to the current portion of the scene being shown on the camera?

Words:
      String words = "Hello, I see that your new here. " +
        "Hello, I see that your new here. " +
        "Hello, I see that your new here. " +
        "Hello, I see that your new here. " +
        "Hello, I see that your new here. " +
        "Hello, I see that your new here. " +
        "Hello, I see that your new here. " +
        "Hello, I see that your new here.";

 //method call
 createSpeech( BodyA.getPosition().x, BodyA.getPosition().y, words );

 //method definition
 private void createSpeech(float xVal, float yVal, String ptext) {

    xVal = xVal * GameConstants.PIXEL_TO_METER_RATIO_DEFAULT;
    yVal = yVal * GameConstants.PIXEL_TO_METER_RATIO_DEFAULT;

    speech = new TickerText( 0, 0, ResourceManager.getInstance().font,
            words, new TickerText.TickerTextOptions( 10 ), ResourceManager.getInstance().vertexManager );

    speech.registerEntityModifier( new AlphaModifier( 5, 0.0f, 1.0f ) );
    speech.setBlendFunction( GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA );
    speech.setScale( 0.5f );
    speech.setHorizontalAlign( HorizontalAlign.CENTER );
    speech.setAutoWrapWidth( 500f );
    speech.setAutoWrap( AutoWrap.WORDS );

    speech.setPosition( xVal, yVal );

Screenshots:
The Red and orange lines indicate where the text is shown currently, the blue region is where I want the text to be shown. The calculations I used to set the text position and the text itself is shown above

I think the text object itself might have something to do with the offset positioning because when i use a smaller string value the position of the text changes as well


texts: Why isn't my sound playing on collision?

texts:
I tried several approaches to get my sound working. This is one of them which most of the online tutorials showed me:

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

public class WallLeftSound : MonoBehaviour
{
    private AudioSource audioSource;
    public AudioClip Scored;

    void OnCollisionEnter2D(Collider2D collider)
    {

        if (collider.tag == "dot")
        {
            audioSource = GetComponent<AudioSource>();
            audioSource.clip = Scored;
            audioSource.Play();
        }
    }

    // Start is called before the first frame update
    void Start()
    {

    }

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

    }
    }

It's not working. Please note that this is work in progress, I tried several other approaches too. Thank you for you help.

Edit Dot:

public class Dot : MonoBehaviour
{
public float speed = 5;
public Transform spawnPoint;
public GameObject dot;
public AudioClip pongSound;
public AudioSource pongSource;

void Start()
{
    // Initial Velocity
    GetComponent<Rigidbody2D>().velocity = Vector2.right * speed;
    pongSource.clip = pongSound;
}

void Update()
{

}

float hitFactor(Vector2 ballPos, Vector2 racketPos,
                float PaddleRight)
{
    // ascii art:
    // ||  1 <- at the top of the racket
    // ||
    // ||  0 <- at the middle of the racket
    // ||
    // || -1 <- at the bottom of the racket
    return (ballPos.y - racketPos.y) / PaddleRight;
}

public void moveDot()
{
    gameObject.GetComponent<Rigidbody2D>().AddForce(Vector2.right * speed);
}
void OnCollisionEnter2D(Collision2D col)
{
    // Note: 'col' holds the collision information. If the
    // Ball collided with a racket, then:
    //   col.gameObject is the racket
    //   col.transform.position is the racket's position
    //   col.collider is the racket's collider

    // Hit the left Racket?
    if (col.gameObject.name == "PaddleLeft")
    {
        // Calculate hit Factor

        float y = hitFactor(transform.position,
                            col.transform.position,
                            col.collider.bounds.size.y);

        // Calculate direction, make length=1 via .normalized
        Vector2 dir = new Vector2(1, y).normalized;

        // Set Velocity with dir * speed
        GetComponent<Rigidbody2D>().velocity = dir * speed;
    }

    // Hit the right Racket?
    if (col.gameObject.name == "PaddleRight")
    {
        // Calculate hit Factor
        playSound();
        float y = hitFactor(transform.position,
                            col.transform.position,
                            col.collider.bounds.size.y);

        // Calculate direction, make length=1 via .normalized
        Vector2 dir = new Vector2(-1, y).normalized;

        // Set Velocity with dir * speed
        GetComponent<Rigidbody2D>().velocity = dir * speed;
    }

    if (col.gameObject.name == "WandRechts")
    {

        RespawnDot();
        GameObject.Destroy(gameObject);
        scoreScript2.scoreValue += 1;

    }

    if (col.gameObject.name == "WandLinks")
    {

        RespawnDot();
        GameObject.Destroy(gameObject);
        scoreScript.scoreValue += 1;
        pongSource.Play();

    }
}

Edit2 PlayerLeft

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

public class PlayerLeft : MonoBehaviour
{
private Rigidbody2D PaddleLeft;
[SerializeField]
private float movementSpeed;
void Start()
{
    PaddleLeft = GetComponent<Rigidbody2D>();
}

// Update is called once per frame
void Update()
{
   if (Input.GetKey(KeyCode.UpArrow))
        {
        PaddleLeft.velocity = new Vector2(0, 1 * movementSpeed);
    }

  else if (Input.GetKey(KeyCode.DownArrow))

    {
        PaddleLeft.velocity = new Vector2(0, 1 *- movementSpeed);
    }

   else if (!Input.anyKeyDown)
    {
        PaddleLeft.velocity = Vector2.zero;
    }
}

private void HandleMovement()
{

}
}

Edit Picture BoxCollider


texts:
Each Entity can have one parent and any number of children. They have a position vector and a quaternion orientation.

I know that I can make objects look like they're in a hierarchy by multiplying parent transforms all the way to the root, but how to I get the canonical coordinates out of those transformations? I need to have the real position of every Entity in the world in order to update their bounding meshes.

I would like to keep my drawing code for everything as just this:

XMMATRIX transform = XMMatrixRotationQuaternion(orientation);
transform = XMMatrixMultiply(transform, XMMatrixTranslation(position));
transform = XMMatrixMultiply(world, transform);
model->Draw(context, *states, transform, view, projection);

Eg. without relying on visual tricks to get the hierarchy looking right, so no multiplications with parent transforms while rendering.

How do I properly change a child's position and orientation with respect to the parent?


texts:
Say i have the following wheel:

Now i wish to use the mouse to select weapon by movement:

So

If mouse is to the left it picks the Sword
if mouse is at the top it selects the bow and arrow
if the mouse is in the bottom then it selects the hand

Since my game is not visually showing the mouse it has to be at any position. i

However, I am not quite sure how to do this? So I am hoping some of you might be able to help. I have looked at getting the mouse position as a vector 2 but I am unsure on how to get the correct position.


texts: Texture atlas vs. array-texture: how differently are they handled by CPU and GPU and how that impacts performance?

texts:
Unity 5.4 (currently in beta), will bring a much awaited feature (since 2013) that is array-textures - in the same vain as OpenGL's ArrayTexture. However, after doing some reading about arrays-textures and texture atlases, I still can't quite understand the technical differences on their usage by CPUs and GPUs.

So, to be more specific, I would like to ask for an explanation on the main differences between how texture atlas and texture arrays are dealt with by CPU and GPU and, most importantly, how such differences can impact on performance and memory handling (e.g. how texture arrays can be more performance than texture atlases, etc).

If technical details on Unity's implementation are lacking due to its unfortunate closed-sourceness, I would be happy enough with an answer regarding OpenGL.s ArrayTexture.


texts:
I want to add a sphere at runtime via script.

I have the following code which compiles fine. At runtime however, no sphere is added to the scene.

I have attached the debugger to the script, and I have set breakpoints at each line.

After the line

Material nMat = new Material(Shader.Find("Lit"));//I'm using the URP

the debugger "blanks" out, it doesn't hit the next line.

What am I doing wrong?

Thank you!

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

public class SphereMaker : MonoBehaviour
{
    private GameObject _Sphere;

    void Start()
    {
        _Sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
        _Sphere.AddComponent<MeshFilter>();

        MeshRenderer nRenderer = _Sphere.AddComponent<MeshRenderer>();
        Material nMat = new Material(Shader.Find("Lit"));//I'm using the URP

        if (nMat == null)
        {
            Debug.LogError("no mat!!\n");
        }
        nMat.color = Color.red;
        nRenderer.material = nMat;

        _Sphere.transform.localScale = new Vector3(0.4f, 0.4f, 0.4f);
        _Sphere.transform.position = new Vector3(0, 0, 0);

    }
}


texts: How do I ensure an appropriate payout ratio for a slot machine?

texts:
I have done a lot of research into random number generators for slot machines, reel stop calculations and how to physically give the user a good chance on winning.

What I can't figure out is how to properly insure that the machine is going to have a payout rating of (lets say) 95%.

So, I have a reel set up wit 22 spaces on it.  Filled with 16 different symbols.

When I get my random number, mod divide it by 64 and get the remainder, I hop over to a loop up table to see how the virtual stop relates to the reel position.

Now that I have how the reels are going to stop, do I make sure the payout ratio is correct?  For every dollar they put in, how to I make sure the machine will pay out .95 cents?

Thanks for the ideas.

I am working in actionscript, if that helps with the language issues, but in general I am just looking for theory.

Edit: There is real money involved only in the fact that they can buy more tokens to play more.  There is not going to be real money paid out to the person, if they were to actually hit the any of the paylines.


texts: Unity3D mesh showing only black triangles

texts:
My mesh in the unity editor won't show the correct texture. Instead I get to see loads of black triangles. Anyone know what's wrong?

thanks :)


texts: Is there something similar to XMFLOAT2 that has its operators overloaded?

texts:
Since XMFLOAT2 is just a structure, I'm sure it does not have operator overloading which is what I need to make things a lot simpler. Is there something like XMFLOAT2 where I can add two (a) + (b). I also need to use the =.

Thanks


texts: How to add emission to texture in shader?

texts:
I want a texture to emit itself by 1, not more. In Standard Shader I enable Emission and set texture to Color and Color to 1. I don't need emission to go beyond the object, I only need the texture to shine.

My shader:

Shader "Mobile/My Bumped Diffuse" {
Properties{
    _MainTex("Base (RGB)", 2D) = "white" {}
    [NoScaleOffset] _BumpMap("Normalmap", 2D) = "bump" {}
    _Color("Color", Color) = (1, 1, 1, 1)
}

    SubShader{
        Tags{ "Queue" = "Transparent" "RenderType" = "Transparency" }
        LOD 250
        ZWrite Off
        Blend SrcAlpha OneMinusSrcAlpha

    CGPROGRAM
    #pragma surface surf Lambert noforwardadd alpha:fade

    sampler2D _MainTex;
    sampler2D _BumpMap;
    fixed4 _Color;
    fixed4 _Emission;

    struct Input {
        float2 uv_MainTex;
    };

    void surf(Input IN, inout SurfaceOutput o) {
        fixed4 c = tex2D(_MainTex, IN.uv_MainTex) * _Color;
        o.Albedo = c.rgb;
        o.Alpha = c.a;
        o.Normal = UnpackNormal(tex2D(_BumpMap, IN.uv_MainTex));
    }
    ENDCG
}

    FallBack "Mobile/Diffuse"

}


texts: OpenGL tile map rendering with 1 quad for all tiles and 1 texture atlas

texts:
I'm using lwjgl to experiment with 2D games.

I made some maps with Tiled (small 30x30 maps) and currently I draw them by loading the tileset image as one texture and extracting from it the texture coordinates for each tile (so a texture atlas).

Every tile is one quad model (vao + 3 vbos: indices, vertices, texCoords) and to render the map I bind the texture atlas, then for each tile I bind the vao and call glDrawElements to draw the model of the tile.

To improve this, I thought I could have one single little quad that represents one tile and move it around changing its texture. This way I'd only have 1 vao+vbos in memory. The problem is that I'm not sure how to handle changing the tex coords.

I could put in the texCoords vbo of this model, all the "regions" of the texture atlas, but then how do I tell the draw call to use some specific 4 coordinates in the long list of coords of the vbo? Maybe I could use the fragment shader in some way?


texts: In Unity, my joystick button only works a few times, why?

texts:
My part of the input code looks like this:

void Update()
{
    y_input = Input.GetButtonUp(StaticStrings.Y);

    delta = Time.fixedDeltaTime;
    states.Tick(delta);
    ResetInputNStates();
}

void GetInput()
{
    vertical = Input.GetAxis(StaticStrings.Vertical);
    horizontal = Input.GetAxis(StaticStrings.Horizontal);
    b_input = Input.GetButton(StaticStrings.B);
    a_input = Input.GetButton(StaticStrings.A);
    y_input = Input.GetButtonUp(StaticStrings.Y);
    x_input = Input.GetButton(StaticStrings.X);
    rt_input = Input.GetButton(StaticStrings.RT);
    rt_axis = Input.GetAxis(StaticStrings.RT);

    if (rt_axis != 0)
        rt_input = true;

    lt_input = Input.GetButton(StaticStrings.LT);
    lt_axis = Input.GetAxis(StaticStrings.LT);

    if (lt_axis != 0)
        lt_input = true;

    rb_input = Input.GetButton(StaticStrings.RB);
    lb_input = Input.GetButton(StaticStrings.LB);

    rightAxis_down = Input.GetButtonUp(StaticStrings.L) || Input.GetKeyUp(KeyCode.T);

    if (b_input)
        b_timer += delta;

    d_x = Input.GetAxis(StaticStrings.Pad_X);
    d_y = Input.GetAxis(StaticStrings.Pad_Y);

    d_up = Input.GetKeyUp(KeyCode.Alpha1) || d_y > 0;
    d_down = Input.GetKeyUp(KeyCode.Alpha2) || d_y < 0;
    d_left = Input.GetKeyUp(KeyCode.Alpha3) || d_x < 0;
    d_right = Input.GetKeyUp(KeyCode.Alpha4) || d_x > 0;
}

The problem is that my Y button is connected with the function of changing from one hand weapon to two hand weapon, but the Y button only works a few times in game!

e.g., I have to press about 3 times then it works.

How do I solve this?


texts: Help to understand positive rotation direction on left/right handed cord spaces

texts: I began to study 3D math and noticed about left/right handed cord spaces and clockwise/counterclockwise rules. I understand that left-handed use clockwise positive rotation and right-handed counterclockwise. But what i don't understand is way this rules exists, on what technical problem this decision is based or this is just an agreement and nothing more?


texts: How to make an Assert.IsNull test pass when the value is reported as ?

texts:
I've just started using unity tests with the built in editor tests. After making my test and finding out that it constantly failed I debugged the code and found that a static object was set to a new game object when running the test while it is set to null when playing in the editor.

Is there a way to force unity to treat the test the in the same way that it treats scripts at run time?

Edit

After changing some code around i get another strange error:

does anyone know why "null" isn't "null". The null objects are stored in an array, but that shouldn't make a difference right?

Edit Edit (Edit 2?)

Here is the code that has the issue

public class StatCollector : MonoBehaviour {

    public static StatCollector running;

    //ensure that there is only one object running at the same time
    public void Awake () {
        if(running == null)
        {
            DontDestroyOnLoad(gameObject);
            running = this;
        }
        else if(running != this)
        {
            DestroyImmediate(gameObject);
        }
    }
}

and here is the test:

[Test]
public void SingleTest()
{
    //create gameobjects
    GameObject[] collect = new GameObject[2];
    collect[0] = new GameObject("one");
    collect[1] = new GameObject("two");
    collect[0].AddComponent<StatCollector>();

    //see if gameobjects were created correctly
    if (collect[0] == null || collect[1] == null) Assert.Fail("failed to create game objects");

    //test what happens when the second stat collector is added to the scene
    collect[1].AddComponent<StatCollector>();
    collect[0].GetComponent<StatCollector>().Awake();
    collect[1].GetComponent<StatCollector>().Awake();
    Assert.IsNull(collect[1]);
}

I'm assuming that there is no way to keep Awake private which is why it is public (just so that the test case has access to it)


texts: Is the 3.x version of the Android SDK compatible with a version 2.1 phone?

texts: i am just starting android app development. I was downloading SDK via the Android Manager. I had to select the SDK versions. I have a phone of android 2.1 So i selected only SDK 2.1 and its samples as to download all it takes too much time. If i download the latest SDK 3.X will it be compatible with my mobile?


texts: Adding -90 degree Y rotation into script

texts:
I'm using the following script to move a spray bottle around a head.

It should looke like in a barber shop.

The code works fine: I have assigned the script to the spray bottle, and I have set the head as the target.

One thing that is wrong is that the spray bottle needs to have a -90 yaw rotation in order to face the head.

I have tried the wildest things to include these -90 degrees, all produced weird results.

Could anybody state how to include this -90 Y rotation into the script?

Thank you very much!

using UnityEngine;
using System.Collections;

[AddComponentMenu("Camera-Control/Mouse Orbit with zoom")]
public class MouseOrbitImproved : MonoBehaviour {

public Transform target;
public float distance = 5.0f;
public float xSpeed = 120.0f;
public float ySpeed = 120.0f;

public float yMinLimit = -20f;
public float yMaxLimit = 80f;

public float distanceMin = .5f;
public float distanceMax = 15f;

private Rigidbody rigidbody;

float x = 0.0f;
float y = 0.0f;

// Use this for initialization
void Start ()
{
    Vector3 angles = transform.eulerAngles;
    x = angles.y;
    y = angles.x;

    rigidbody = GetComponent<Rigidbody>();

    // Make the rigid body not change rotation
    if (rigidbody != null)
    {
        rigidbody.freezeRotation = true;
    }
}

void LateUpdate ()
{
    if (target)
    {
        x += Input.GetAxis("Mouse X") * xSpeed * distance * 0.02f;
        y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;

        y = ClampAngle(y, yMinLimit, yMaxLimit);

        Quaternion rotation = Quaternion.Euler(y, x, 0);

        distance = Mathf.Clamp(distance - Input.GetAxis("Mouse ScrollWheel")*5, distanceMin, distanceMax);

        RaycastHit hit;
        if (Physics.Linecast (target.position, transform.position, out hit))
        {
            distance -=  hit.distance;
        }
        Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);
        Vector3 position = rotation * negDistance + target.position;

        transform.rotation = rotation;
        transform.position = position;
    }
}

public static float ClampAngle(float angle, float min, float max)
{
    if (angle < -360F)
        angle += 360F;
    if (angle > 360F)
        angle -= 360F;
    return Mathf.Clamp(angle, min, max);
}
}


texts:
im trying to figure out how to recall an external file in runtime on iOS device. I've already tried using Application.data+"/Raw/MY_FILE", with Application.streamingAssetsPath+"/MY_FILE", and with Application.persistentData+"/Raw/MY_FILE" (but, if i dont get wrong, persistentData is used for write, i need just of reading).

Please, anyone can help me?


texts: Game engine tool generating game entities

texts:
I'm writing a game engine with an editor that allows you to create individual components like sprites, fonts, and particles. Then you're able to combine these individual components into what I call an "Entity", to create something more complex and whole.

Currently you can only construct an Entity through code. You derive a new class off of an Entity interface and its derived members are the components you wish it to have (sprites, texts, etc). You can then implement whatever new logic this Entity is supposed to do.

I want to be able to create these entities in my editor, so you're able to simply read a file at run time that loads in all the required components and initializes them to specified values.

I can auto generate the c++ derived Entity class file, then deal with either auto importing it into the code project (or relying on the user to do so). I can directly generate the specified initialization code in the constructor. Makes for easiest access to components when implementing custom logic, and can ensure components' memory is contiguous for better cache.
Or simply have the Entity base class read the file and stores all its required components in a std::vector. Initializing the components will require a robust, hefty function for parsing the file and applying the specified values. Accessing the components when implementing your logic will also be a pain, either remembering their indices, or using string names in a map (bleh).

I like the first auto generating solution better, but I'm afraid of the maintenance and upkeeping it may require. Also I can't just keep overwriting their class source file so I'll need them to separate their custom logic in another source file. Would want a clean way to do that, and possibly a clean way to auto import the source code into the project (The tool knows the source directory, and I guess I could put the whole declaration/definition in a header file).

Any insight on which implementation? Have you ever auto generated C++ code before and regretted it? Or is there an entirely better way?


texts: Fixed timestep with interpolation in AS3

texts:
I'm trying to implement Glenn Fiedler's popular fixed timestep system as documented here:

http://gafferongames.com/game-physics/fix-your-timestep/

In Flash. I'm fairly sure that I've got it set up correctly, along with state interpolation.

The result is that if my character is supposed to move at 6 pixels per frame, 35 frames per second = 210 pixels a second, it does exactly that, even if the framerate climbs or falls.

The problem is it looks awful. The movement is very stuttery and just doesn't look good.

I find that the amount of time in between ENTER_FRAME events, which I'm adding on to my accumulator, averages out to 28.5ms (1000/35) just as it should, but individual frame times vary wildly, sometimes an ENTER_FRAME event will come 16ms after the last, sometimes 42ms.

This means that at each graphical redraw the character graphic moves by a different amount, because a different amount of time has passed since the last draw. In theory it should look smooth, but it doesn't at all. In contrast, if I just use the ultra simple system of moving the character 6px every frame, it looks completely smooth, even with these large variances in frame times.

How can this be possible? I'm using getTimer() to measure these time differences, are they even reliable?


texts: Using raycast to detect whether a wall immediately blocks a player in Unity C#

texts:
I am working on a game project of which involves a procedurally generated maze.
Within this maze, there are different types of tiles, such as walls and gates.
I want to program the player so that it cannot move through a tile that is tagged as a "wall", and I am hoping to use ray casting to detect item tags.
Now, you may think it would be simpler to use rigid bodies, but the game is set up so that the player moves 1 unit per movement, instead of being able to move at any randomly input distance, in order to keep the game adhering to a "grid" for the sake of other events that happen within the game.

So, for this reason, i wish to detect if a wall is north of the player (let's call "north" as "up", as I have an "up blocked" boolean to state if a wall is directly "north" of the player)
but, my code doesn't always recognise walls that are immediately north of the player, and instead sometimes the "up blocked" boolean becomes activated as "true" when a wall is left, right, or "below" (down) of the player, irrespective of whether or not there is a wall "above" or down.

here is my code:

Vector2 vUp = new Vector2(transform.position.x, (transform.position.y + 0.05f));

    RaycastHit2D hitUp = Physics2D.Raycast(transform.position, vUp);

    if (hitUp.collider != null && hitUp.collider.tag == "wall")  {
        upBlocked = true;
    } else {
        upBlocked = false;
    }

I have spent many hours looking for a solution for this problem, but most mediums provide information that either didn't work, wasn't applicable or simply was grossly out of date.


texts: How can I sort vertices efficiently in a specific direction (CW/CCW)?

texts:
I am trying to triangulate a set of points using a very simple approach where a base vertex is chosen, and then every other vertex is joined to its neighbouring vertex and then back to the base vertex, to create a triangle-fan structure, which creates a solid surface.

The problem with this approach is that in order to triangulate it there is a lot of iterating, and for each triangulation point, it must iterate over the entire list again to find its nearest CW point which is very slow, but works.

    for (int i = 1; i < triangulationPoints.Count; i++)
        {
//this method iterates over available which is a copy of triangulationPoints
//and finds the closest vertex with no backtracking
            Vector3 vertex = findClosestVertex(currentVertex, available, ordered);
//...
available.Remove(vertex);
        }

Now I'm looking to speed up the algorithm so I get the same effect, but faster.

I implemented a binary insert function that sort each point based on distance from the base vertex as it is inserted into the triangulationPoint list which works nicely and is fast, but produces incorrect results as it doesn't take into account the next CW vertex, but any vertex.

Does anyone have any suggestions as to how I can speed this up, or perhaps another triangulation algorithm that is relatively easy to implement which would achieve fast speeds?

Edit
I have tried Unity's triangulator and that produces results that are worse than my attempt. I have also tried a third-party triangulator (https://github.com/CiaccoDavide/Unity-UI-Polygon) and this seems to be exactly what I need, however it only draws on the UI and not in world space.

An attempt at implementing DMGregory's explanation

   Quaternion toPlaneSpace = Quaternion.Inverse(Quaternion.LookRotation(cutter.normal));

    centroidPosition = centroidPosition / sharedIntersectionPoints.Count;

    foreach (Vector3 v in sharedIntersectionPoints)
    {
        Vector3 offset = toPlaneSpace * (v - centroidPosition);

        IntersectionPoint ip = new IntersectionPoint(v, Mathf.Atan2(offset.y, offset.x));

        int index = binaryInsertAngle(new IntersectionPoint(v, Mathf.Atan2(offset.y, offset.x)), 0, points.Count);

        if (index > orderedTriangulationPoints.Count)
        {
            orderedTriangulationPoints.Add(ip.point);
            points.Add(ip);
        }
        else
        {
            orderedTriangulationPoints.Insert(index, ip.point);
            points.Insert(index, ip);
        }
    }

Both the new ordered list and the old ordered list are the same size so it should be stepping over the vertices correctly without missing any.