texts: Isometric ball moving in unity 3d. Ball moving in opposite direction

texts:
I am making a game in unity 3d. It is a 2.5d game which mean it is in isometric. The game is quite simple. Player drags mouse and a trajectory will be shown just like in angry bird and when player release the mouse the ball will move to the direction. However I am having issue here that once mouse is released the ball moves in exact opposite direction. I am not able to understand what the real issue is. My code is as follows:
For Ball:
public class BallScript : MonoBehaviour

{
    public Rigidbody2D rbg;
    public CircleCollider2D col;

    public Vector3 BallPos{
        get {return transform.position;}
    }

    void Awake(){
        rbg = GetComponent<Rigidbody2D>();
        col = GetComponent<CircleCollider2D>();
    }

    public void PushBall(Vector2 force){
        rbg.AddForce(force,ForceMode2D.Impulse);
    }

    //to enable rigidbody so we can use projectile again
    public void ActivateRb(){
        rbg.isKinematic = false;
    }

    public void DeActivateRb(){
        rbg.velocity = Vector3.zero;
        rbg.angularVelocity = 0f;
        rbg.isKinematic = true;
    }
}

The code for my game manager is as follows:
public class Trajectory : MonoBehaviour
{
    [SerializeField] int dotsNumbers;
    [SerializeField] GameObject dotsParent;

    [SerializeField] GameObject DotsPrefab;
    [SerializeField] float dotSpacing;
    Vector2 pos;
    float timeStamp;
    Transform[] dotsList;

    void Start(){
        //hide trajectory in the start
        Hide();

        PrepareDots();
    }

    void PrepareDots(){
        dotsList = new Transform[dotsNumbers];
        for(int i=0;i<dotsNumbers;i++){
            dotsList[i] = Instantiate(DotsPrefab,null).transform;
            dotsList[i].parent = dotsParent.transform;
        }
    }
    public void UpdateDots(Vector3 ballPos,Vector2 forceApplied){
        timeStamp = dotSpacing;
        for(int i=0;i<dotsNumbers;i++){
            pos.x = (ballPos.x + forceApplied.x * timeStamp);
            pos.y = (ballPos.y + forceApplied.y * timeStamp)-(Physics2D.gravity.magnitude * timeStamp * timeStamp)/2f;
            dotsList[i].position = pos;
            timeStamp += dotSpacing;
        }
    }

    public void Show(){
        dotsParent.SetActive(true);
    }
    public void Hide(){
        dotsParent.SetActive(false);
    }
}

Here is the code for gamemanager
// using singleton pattern
Camera cam;
public BallScript ball;
public Trajectory trajectory;
public static GameManagerScript Instance;
void Awake(){
    if(Instance==null){
        Instance = this;
    }
}

[SerializeField] float pushForce = 4f;
bool isDragging = false;

Vector2 startPoint;
Vector2 endPoint;
Vector2 direction;
 Vector2 force;
float distance;

void Start(){
    cam = Camera.main;
    ball.DeActivateRb();
}

void Update(){
    if(Input.GetMouseButtonDown(0)){
        isDragging = true;
        OnDragStart();
    }
    if(Input.GetMouseButtonUp(0)){
        isDragging = false;
        OnDragEnd();
    }
    if(isDragging){
        OnDrag();
    }
}

void OnDragStart(){
    ball.DeActivateRb();
    startPoint = cam.ScreenToWorldPoint(Input.mousePosition);
    trajectory.Show();
}

void OnDrag(){
    endPoint = cam.ScreenToWorldPoint(Input.mousePosition);
    distance = Vector2.Distance(startPoint,endPoint);
    direction = (endPoint-startPoint).normalized;
    force = direction* distance * pushForce;

    trajectory.UpdateDots(ball.BallPos,force);

}

void OnDragEnd(){
    ball.ActivateRb();
    ball.PushBall(force);
    trajectory.Hide();
}

The ball moves in exact opposite direction where I wish to send it by dragging. Is it because of the isometric issue or I am missing something?P.S: have applied negative force as well as in case and have also made change in direction formula
rbg.AddForce(-force,ForceMode2D.Impulse);
direction = (startPoint-endPoint).normalized;


texts: How do I smooth out latency jitter in my netcode?

texts:
I'm developing a multiplayer game and I'm following some articles I've found online to create an authoritative client-server model.

Reading this article, Valve says that every time a message is received, the client assumes the "current" time is the time in the latest packet, in the article they state it:

  It is assumed in this paper that the client clock is directly synchronized to the server clock modulo the latency of the connection. In other words, the server sends the client, in each update, the value of the server's clock and the client adopts that value as its clock. Thus, the server and client clocks will always be matched, with the client running the same timing somewhat in the past (the amount in the past is equal to the client's current latency). Smoothing out discrepancies in the client clock can be solved in various ways.

And interpolation of remote entities:

  Each update contains the server time stamp for when it was generated
  From the current client time, the client computes a target time by subtracting the interpolation time delta (100 ms)
  If the target time is in between the timestamp of the last update and the one before that, then those timestamps determine what fraction of the time gap has passed.
  This fraction is used to interpolate any values (e.g., position and angles).

Now obviously due to jitter, my interpolation looks terrible as I will receive time + latency jitter. So my question is, is on this part: "Smoothing out discrepancies in the client clock can be solved in various ways."

What would be a good way to smooth out any discrepancies?


texts: Scale adaption based on distance to object

texts:
I have situation illustrated on image above, name displayed over the player. Text is rendered as 3d rectangle and rotated to face camera as billboard. (I am using this article http://blogs.msdn.com/b/shawnhar/archive/2011/01/12/spritebatch-billboards-in-a-3d-world.aspx) I just want to have size of the text always the same.
Are there any common approach to adaptively scale object based on distance?


texts:
I can put the HTML and JavaScript together in the same .html file, but the images need to be separate files. The only solution that comes to my mind is to give to the user a .zip folder.

This is not pretty though... How else can I do this?


texts:
I am trying to render G-Code generated for a 3d-printer as the printed product by reading the file as line segments and the drawing cylinders with the diameter of the filament around the segment. I think I have managed to do this part right because the vertex I am sending to the graphics device appear to have been processed correctly. My problem I think lies somewhere in the rendering. What basically happens is that when I start rotating my model in the X or Y axis then it renders perfectly for half of the rotation but then for the other half it has this weird effect where you start seeing through the outer filament into some of the shapes inside. This effect is the strongest with X rotations though.

Here is a picture of the part of the rotation that looks correct:

And here is one that looks horrible:

I am still quite new to XNA and/Monogame and 3d programming as a whole. I have no idea what could possibly be causing this and even less of an idea of what this type of behavior is called. I am guessing this has something to do with rendering so have added the code for that part:

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.Black);

        basicEffect.World = world;
        basicEffect.View = view;
        basicEffect.Projection = projection;
        basicEffect.VertexColorEnabled = true;
        basicEffect.EnableDefaultLighting();

        GraphicsDevice.SetVertexBuffer(vertexBuffer);

        RasterizerState rasterizerState = new RasterizerState();
        rasterizerState.CullMode = CullMode.CullClockwiseFace;
        rasterizerState.ScissorTestEnable = true;
        GraphicsDevice.RasterizerState = rasterizerState;

        foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
        {
            pass.Apply();
            GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, vertexBuffer.VertexCount);
        }

        base.Draw(gameTime);
    }

I don't know if it could be because I am shading something that does not really have a texture. I am using this custom vertex declaration I found on some tutorial that allows me to store a vertex with a position, color and normal:

    public struct VertexPositionColorNormal
    {
        public Vector3 Position;
        public Color Color;
        public Vector3 Normal;

        public readonly static VertexDeclaration VertexDeclaration = new VertexDeclaration
        (
            new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0),
            new VertexElement(sizeof(float) * 3, VertexElementFormat.Color, VertexElementUsage.Color, 0),
            new VertexElement(sizeof(float) * 3 + 4, VertexElementFormat.Vector3, VertexElementUsage.Normal, 0)
        );
    }

If any of you have ever seen this type of thing please help. Also, if you think that the problem might lay somewhere else in my code then please just request what part you would like to see in the comments section.


texts: Do I need to add an anti-piracy system to my game if I publish on Itch.io?

texts: Do I need to add an anti-piracy system to my game if I decide to publish it on itch.io or a similar marketplace? The investment to add that system is small, because it's a simple serial code generator.


texts: How to add or increase speed on every 500m distance of player?

texts:
I'm a a beginner, creating an endless runner game.

I want to increase speed as the player completed the distance and  on every 500 meter speed should be increased.
Anyone have an idea of how to implement this kind of logic?

speed=10;
//as soon as player reach 500 m distance
//speed should be incremented
//it should be continuous process on every 500m

My code:

public class Score : MonoBehaviour
{
    [SerializeField]
    GameObject ground;
    [SerializeField]
    AudioClip clip;
    [SerializeField]
    Transform player;
    [SerializeField]
    public Text LiveScore;
    [SerializeField]
    public GameObject gameOver;
    [SerializeField]
    public bool runningScore = true;
    public Text finalScore;
    public Text Highscore, bestScore;
    float distance;
    ball Ball;
    // Start is called before the first frame update
    private void Start()
    {

        Ball = GetComponent<ball>();
        //  PlayerPrefs.DeleteKey("HighScore");
        Highscore.text = "Best :" + ((int)PlayerPrefs.GetFloat("HighScore", 0)).ToString();
        bestScore.text = "Best :" + ((int)PlayerPrefs.GetFloat("HighScore", 0)).ToString();
    }
    // Update is called once per frame
    void Update()
    {

        distance = player.position.z + 500;
        if (runningScore)
        {
            LiveScore.text = distance.ToString("0");

            //  Highscore.text = LiveScore.text;
        }
        if (runningScore == false)
        {
            float score = float.Parse(LiveScore.text);
            finalScore.text = "Score:" + LiveScore.text;
            if (PlayerPrefs.GetFloat("HighScore", 0) < score)
            {

                PlayerPrefs.SetFloat("HighScore", score);
                Highscore.text = "Best :" + score.ToString();

                bestScore.text = Highscore.text;
                AudioSource.PlayClipAtPoint(clip, Camera.main.transform.position);
            }
            else if (score < PlayerPrefs.GetFloat("HighScore", 0))
            {

                bestScore.text = Highscore.text;
            }

        }

        while (distance > 500)
        {
            Ball.speed += 5;
        }

    }

}


texts: LibGDX - Draw multiple textures with different positions with one shader?

texts: currently I'm optimizing my render calls by drawing multiple textures with one shader. The background textures who all share the same position are no problem. But now I want to draw some Textures with different positions with one shader. I think it isn't possible, because the textures don't have the same geometry. But maybe there is a possible way to do this? I never worked with the geometry shader for example. For example, draw a 512x512 texture to position (100, 50), draw a 256x256 texture to position (500, 300)... , like in this picture:


texts: transform.position returning wrong value (UNITY 2D)

texts:
I am trying to place the ball on the paddle until a key is pressed, also there is box collider that triggers if the ball falls down. For some reason the transform.position.y of the ball gameObject is going below zero while the ball is still stuck to the paddle in the game and therefore triggering the collider unnecessarily . Attaching code of paddle and ball bellow .

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

public class ballScript : MonoBehaviour
{
    [SerializeField] GameObject myPaddle;
    Vector3 paddleToBallVector;
    void Start()
    {
        paddleToBallVector = transform.position - myPaddle.transform.position;
        lockToPaddle();
    }
    void Update()
    {
        lockToPaddle();
    }

    private void lockToPaddle()
    {
        transform.position = myPaddle.transform.position + paddleToBallVector;
    }
}

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

public class paddleScript : MonoBehaviour
{
    [SerializeField] float screenWidthUnits = 16f;
    [SerializeField] float paddleLeftLimit = 1.07f;
    [SerializeField] float paddleRightLimit = 14.928f;

    void Update()
    {
        float screenWidthPercentage = Input.mousePosition.x / Screen.width;
        Vector2 curPaddlePos = new Vector2(screenWidthPercentage * screenWidthUnits, transform.position.y);
        curPaddlePos.x = Mathf.Clamp(curPaddlePos.x, paddleLeftLimit, paddleRightLimit);
        transform.position = curPaddlePos;
    }
}

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

public class bottomCollisionScript : MonoBehaviour
{
    private void OnTriggerEnter2D(Collider2D collision)
    {
        Debug.Log(collision.gameObject);
        Debug.Log("Game Over");
    }
}


texts: How to "swing" bounding box and update collision for sprite swinging a weapon?

texts:
I have a simple question about sprite swinging weapons. I am making an RPG and would like something other than stabby-swords, so why not swinging swords?

I have a bounding rectangle for them, and the player equips them. Great, but I cannot grasp around my head how to swing both the sprite AND the bounding box (in XNA).

The sprite is easy, I specify it's origin and rotate by a specified amount over a certain amount of time (the swing time), but the bounding rectangle poses another issue for me.

Edit: A bit of clarity on my swinging animation. It's basically the player holding out their arm and the weapon swings in a curve from about +45 degree angle to a -45 degree angle.


texts: LWJGL/Java - Implementing a writeable text box?

texts:
I would like to create a writeable text box where a user can input text into it. A nice "send" button that the person could click to send the text to the server would also be nice.

I currently haven no idea how to do this and I do not see any tutorials on how to do this.

I am using LWJGL and Java, and also I am using the Slick2D library.

Thanks!


texts: NavMeshAgent.CalculatePath produces a PathInvalid result

texts:
Anyone know what can cause NavMeshAgent.CalculatePath to return false and give a path with PathInvalid status?

I have two characters; each character has a NavMeshAgent.  Character x is a standard Humanoid, character Y is a vehicle with a custom agent type.
Characters start out in scene A, which has two NavMeshes, one for each type, and both are able to navigate just fine.
Characters get moved to DontDestroyOnLoad so that scene A can be unloaded and scene B can be loaded.
Scene B has two NavMeshes, one for each type.
Characters are placed on the ground, on a valid NavMesh location.
NavMeshAgent is asked to path to another valid location on the NavMesh.  Character Y (the weird one) paths just fine, but for character X, the call to CalculatePath fails and the NavMeshPath object's status is PathInvalid.

I honestly have no idea what's going on here.  If anything, I'd expect pathing to work for X and fail for Y, due to it being a nonstandard (and larger) agent.  Not sure if the scene change is relevant or not; including it just in case it is, and to show that the basic setup is working for 3/4 scenarios here.
Anyone know how to go about debugging this?


texts: DX11 How to guarantee rendering order using Deferred Context?

texts:
What techniques are used to guarantee rendering order (back to front) when you have more than one deferred context?

My original idea was to manually remap the Command Lists, but it seems like this is not possible.

Do games just render all Alpha objects using the immediate context (to guarantee order)?

Thanks!


texts: How to program an attack that I control with the arrow keys?

texts:
I'm making a 2D game prototype in Unity and I want to have the player attack be a sword that hovers around the player with its direction being fixed to the direction you indicate with the arrow keys. So if the sword is in the upward position and you press the left button, you can see the arc it takes and an enemy in the way of that arc takes damage.

The game is not a platformer. It's on a flat surface.

edit: I want to know how to have the sword hover in a radius to the player and point the direction i press the arrow keys. I want to get the action of moving the sword to these positions to do damage to an enemy. But if the sword is in a upwards position and the player presses down, I want it to do an action that attacks the whole radius around the player, on a cooldown.

How would I go about programming this? I'm new to programming so I would greatly appreciate some helpful pointers.

Edit2:

So this is how far I have gotten:
public class SwordSwing : MonoBehaviour {

public Transform swordHolder;

// Update is called once per frame
void Update ()
{
    if (Input.GetKeyDown(KeyCode.LeftArrow))
    {
        swordHolder.transform.Rotate(0, 0, -90);
    }

    if (Input.GetKeyDown(KeyCode.RightArrow))
    {
        swordHolder.transform.Rotate(0, 0, 90);
    }

    if (Input.GetKeyDown(KeyCode.UpArrow))
    {
        swordHolder.transform.Rotate(0, 0, 90);
    }

    if (Input.GetKeyDown(KeyCode.DownArrow))
    {
        swordHolder.transform.Rotate(0, 0, -90);
    }

}

I don't know if this is right, because when I use the arrow keys it just turns the sword 90 degrees and not to the specified position I want it to move to.

So Candid Moon said that I have to use Mathf.Lerp() and StartCoroutine() but I have no idea how to use them. I'm not really sure how to animate this either, I have done some animations in Unity but have a hard time implementing them into anything.

The hierarchy is now:

Player > SwordHolder > Sword

Now I also have this script:

if (GetComponent<Rigidbody2D>().velocity.x > 0)
        transform.localScale = new Vector3(1f, 1f, 1f);
    else if (GetComponent<Rigidbody2D>().velocity.x < 0)
        transform.localScale = new Vector3(-1f,1f,1f);

That flips the player sprite when i move left. This also flips the sword, I don't really want this. How do I stop it?

Let me know if there is anything I missed, I'm trying to learn.


texts:
I'm wirting my first OpenGL Application for Android at the moment and now I get stuck on the ObjectLoader for obj files. I have some qestions to this file format and I can't an answer on the internet for this. Maybe it is easier if we go throught all these questions with an example file:

#Cube file - has no texture
mtllib dice_material.mtl

v 0.475013 0.999999 -0.066651    # 1
v 0.457026 0.999999 -0.067220    # 2
v 0.439582 0.999999 -0.067505    # 3
...
vn 0.000000 1.000000 0.000000    # 1
vn 0.000000 0.999969 0.000000
vn 0.000000 0.778466 0.627674
...
f 1//1 11//1 14//1 2//1          # the first 1 references to the first v right?
f 2//1 14//1 15//1 3//1          # the first 2 references to the second v right?
f 3//1 15//1 16//1 4//1

Can I assume that allways the verticies v are on the head of the document (after some comments) followed by the texture coordinates (tv) and the normales (vn)?
If an object has a texture does the obj file allways have the texture coordinates? If not how can I calculate them on my own?
If the object has a texture is it required that the object has a material too or can an object have a texture without a material?
If the file contains the texture coordinates do the polygons (f) must contain the texture coordinates? Or is f 1//1 a valid polygon too if the file contains the texture coordinates?


texts: How to instantiate prefab outside Resources folder?

texts:
I'm trying to developing a tool to help me "remember" all my prefabs / fbx assets.

My assets are almost in a subFolder (for instnace) "3d models" .

I've developed a routine to get all ".prefab" or ".fbx" files and store it in a List / Array.

Now, in a test scenem, i want to instantiate them (using 2 buttons: previous prefab and next prefab).

Using :

_currentPrefab = Instantiate ( Resources.Load (prefabs [currentPrefabIndex].ToString(), typeof(GameObject)), SpawnGameObject.transform.position, new Quaternion(0,0,0,0)) as GameObject;

Give me an error because (i'm pretty sure) my prefab is outside Resource folder.

So my question is: how can i Instantiate my prefab outside that folder ? Is there a way ?

Thanks


texts:
I am making a small FPS in unity 5. I made a cursor animation that I want to play only for a brief moment. I tried to do this using some code:

using System.Collections;

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

public class CrossAnimate : MonoBehaviour {

public GameObject UpCurs;
public GameObject DownCurs;
public GameObject LeftCurs;
public GameObject RightCurs;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    if (Input.GetMouseButtonDown(0))
    {
        UpCurs.GetComponent<Animator>().enabled = true;
        DownCurs.GetComponent<Animator>().enabled = true;
        LeftCurs.GetComponent<Animator>().enabled = true;
        RightCurs.GetComponent<Animator>().enabled = true;
        WaitingAnim();
    }
}

IEnumerator WaitingAnim()
{
    yield return new WaitForSeconds(0.1f);

    UpCurs.GetComponent<Animator>().enabled = false;
    DownCurs.GetComponent<Animator>().enabled = false;
    LeftCurs.GetComponent<Animator>().enabled = false;
    RightCurs.GetComponent<Animator>().enabled = false;
}

}

All of the four animators on the four gameobjects (UpCurs, DownCurs, etc) are not enabled by default. When clicking the mousebutton they should be enabled so it plays the animation and then after a brief time, they should disable again. The problem is that they don't disable.

Any help would be appreciated!


texts: How can i make that when pressing F fast many time it will scale the object down/up smooth without waiting?

texts:
The first script is for the F pressing and calling the ScaleChange:

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

public class DroidMove : MonoBehaviour
{
    public GameObject droid;
    public ChangeScale changeScale;

    private bool toDisplay = false;

    private void Start()
    {
        droid.transform.localScale = new Vector3(0, 0, 0);
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.F))
        {
            toDisplay = !toDisplay;
            changeScale.Scale(toDisplay);
        }
    }
}

The second script make the scaling:

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

public class ChangeScale : MonoBehaviour
{
    public GameObject objectToScale;

    private float _currentScale = InitScale;
    private const float TargetScale = 0.7f;
    private const float InitScale = 0f;
    private const int FramesCount = 10;
    private const float AnimationTimeSeconds = 0.1f;
    private float _deltaTime = AnimationTimeSeconds / FramesCount;
    private float _dx = (TargetScale - InitScale) / FramesCount;

    private IEnumerator ScaleUp()
    {
        bool upscaling = true;
        while (upscaling)
        {
            _currentScale += _dx;
            if (_currentScale > TargetScale)
            {
                upscaling = false;
                _currentScale = TargetScale;
            }
            objectToScale.transform.localScale = Vector3.one * _currentScale;
            yield return new WaitForSeconds(_deltaTime);
        }
    }

    private IEnumerator ScaleDown()
    {
        bool downscaling = true;
        while (downscaling)
        {
            _currentScale -= _dx;
            if (_currentScale < InitScale)
            {
                downscaling = false;
                _currentScale = InitScale;
            }
            objectToScale.transform.localScale = Vector3.one * _currentScale;
            yield return new WaitForSeconds(_deltaTime);
        }
    }

    public void Scale(bool scaleUp)
    {
        if (scaleUp)
        {
            StartCoroutine(ScaleUp());
        }
        else
        {
            StartCoroutine(ScaleDown());
        }
    }
}

The problem is if i press on F and it start scaling up and not finished yet the scaling and i press F again instead start scaling down it's like pausing and if i keep pressing F it will keep scaling up each time a bit.

What i want is if i press F and it start scaling to one direction up.down in the middle while it's scaling then change the scaling direction.

The variable TargetScale is like max scale and InitScale is like a min.
I want to keep it with the max and min but to make that if in the middle when it's scaling i press F change the scaling direction and not to pause it.


texts: How can I change the script so it will not be with a while loop inside Update or using coroutine instead?

texts:
The script is working fine as it is and I don't fell any performance problems and yet I wonder if it's a good idea to run a while loop inside the Update function ?
The idea is to be able to move an object over a curved lines with a lot of positions in any speed.
So I'm calculating how much positions there is next each time and it's working fine I just wonder about the while in the update.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.AI;

public class MoveOnCurvedLines : MonoBehaviour
{
    public LineRenderer lineRenderer;
    public float speed;
    public bool go = false;
    public bool moveToFirstPositionOnStart = false;

    private Vector3[] positions;
    private Vector3[] pos;
    private int index = 0;
    private bool goForward = true;
    private List<GameObject> objectsToMoveCopy = new List<GameObject>();

    // Start is called before the first frame update
    void Start()
    {
        pos = GetLinePointsInWorldSpace();

        if (moveToFirstPositionOnStart == true)
        {
            transform.position = pos[index];
        }
    }

    Vector3[] GetLinePointsInWorldSpace()
    {
        positions = new Vector3[lineRenderer.positionCount];
        //Get the positions which are shown in the inspector
        lineRenderer.GetPositions(positions);

        //the points returned are in world space
        return positions;
    }

    // Update is called once per frame
    void Update()
    {
        if (go == true)
        {
            Move();
        }
    }

    void Move()
    {
        Vector3 newPos = transform.position;
        float distanceToTravel = speed * Time.deltaTime;

        bool stillTraveling = true;
        while (stillTraveling)
        {
            Vector3 oldPos = newPos;
            newPos = Vector3.MoveTowards(oldPos, pos[index], distanceToTravel);
            distanceToTravel -= Vector3.Distance(newPos, oldPos);
            if (newPos == pos[index]) // Vector3 comparison is approximate so this is ok
            {
                // when you hit a waypoint:
                if (goForward)
                {
                    bool atLastOne = index >= pos.Length - 1;
                    if (!atLastOne) index++;
                    else { index--; goForward = false; }
                }
                else
                { // going backwards:
                    bool atFirstOne = index <= 0;
                    if (!atFirstOne) index--;
                    else { index++; goForward = true; }
                }
            }
            else
            {
                stillTraveling = false;
            }
        }

        transform.position = newPos;
    }
}


texts: How do I keep Text[] values alive and reuse in the script

texts:
I'm building a bowling game in which I am trying to save the number of pins fallen on every turn to a UI text box, taken as an array (public Text[] Count). I'm able to get the first score in the text box, but unable to save it while switching to other scenes.

There are two scenes; one has the ball, pins and alley, and the other scene has the score card, which is displayed in additive mode. The UI text is a child of the canvas. I've used DontDestroyOnLoad for the canvas, but it doesn't work at all.
I'm actually trying to reuse these values to display the score in the series.

Below is the code

public GameObject rootCanvas;
    public Text[] Count;
    public static int counter=0;
    public static int i;
    public static int co = 0;

    MovingBall ball = new MovingBall();

    public void Start()
    {
        ball.countText = GameObject.FindWithTag("Counttext").GetComponent<Text>();

        for (i=co;i<=29;i++)
        {
            if (counter < 1)
                {
                    Count[i].text = ball.countText.text;
                }
                else if (counter == 1)
                {
                    Count[i].text = ball.countText.text;
                    Count[i+1].text = (Convert.ToInt16(Count[i-1].text) + Convert.ToInt16(Count[i].text)).ToString();
                }

            counter++;

            co++;

            DontDestroyOnLoad(gameObject.transform);

            return;

        }

    }

    void Awake()
    {

        rootCanvas = GetComponent<GameObject>();

    }


texts: How image.ImageGrid() works? How to fix it?

texts: I understood what this method do (it cuts one spritesheet into a list of images), but I don't understood how it cuts. What height and weight for an image, it takes? I tried with few spritesheets png, and each time it cuts an image with part of the next image. Not correct.


texts: Do I need to implement IPv6 support for my game?

texts: I'm going to implement network features for the game I'm currently working on, now I'm wondering if I need to implement IPv6 support or just having support for IPv4 is enough?


texts: How can i call a thing a lot of times (game: dodger)

texts:
Hey I am new to coding and i want to know how to get the same thing to hapen until i "say" stop.

The game is that you need to dodge stuff that is falling, i was thinking that i could use a while loop and Push the object in the list like the following:

Var i = 0;
Var theObjects = [ ];
While ( i < 100)
{
    theObjects.push();
    i ++;
}

But that would be 1. Spawn them at the same time and the it would be 2. This only works for x amount of time.

How can i make the object spawn til i say stop and spawn at difrent times

Sorry for my bad english.


texts: I am somewhat new to the whole game programming thing. I was wondering if I could develop a game for IOS and Android with using openGLES. if so how can I run the code on the devices and what are some good resources to continue learning from. I am only targeting mobile devices so information for PC/Mac is irrelevant to me. Thank you for your help :)


texts: How do I get data from a WWW object without freezing my game?

texts:
I am using Unity 3d to create a real time multiplayer game. I have a database set up that keeps track of player statistics and what in app purchases they have purchased. I have written a Database class that is used to access my database via php scripts. It all works pretty well, but I run into problems when I try to get values from the database and it doesn't return quick enough. My assumption is that I need to use a coroutine in order keep letting it run so that I can eventually get the value. How exactly would I do that though?

This is the code I currently have:

public string GetValue(string id, string valid)
{
    string hash = Md5Sum(string.Format("{0}{1}{2}", id, valid, secretKey));
    string url = string.Format("{0}id={1}&vid={2}&hash={3}", getValue, id, valid, hash);
    WWW www = new WWW(url);
    while (!www.isDone) { }
    return www.text;
}

I figured that by adding the while loop in the middle it would always return a value but it doesn't seem to work that way. Should this be in a coroutine? And if so how would I get my value back from it compared to how I currently do it where it just returns the string value I wanted.


texts: How to deal with corner collisions in 2D?

texts:
I'm writing a top down 2d XNA game. Since its my first I'm trying to write the physics and collision stuff myself to learn it.

Whenever my player sprite character attempts to move into a position where its bounds intersect with the edge of a wall, I figure out a bounce angle (angle of incidence = angle of reflection) and I make the player bounce off the wall and avoid the collision.

I'm having trouble figuring out how to deal with the situation of my sprite intersecting with two wall edges simultaneously though e.g. it hits a corner.

My code currently tells me that two wall edges have been intersected but not which edge it would have hit first and therefore which edge to bounce off.

What is the mathematical test to pick which edge to bounce off? It's plain to see when looking at it but I'm struggling to figure out the math test for it.


texts: Replace each white spot of image to radial gradient

texts:
Recently, I read an article about a sun shader (XNA Sun Shader) and decided to implement it using OpenGL ES 2.0, but I encountered a problem with the shader:

I have two textures, one of them is the fire gradient texture:

The other one is a texture which will have each white part filled using the gradient;

So, I'm going to have a result similar to the image below (do not pay attention to the texture being rendered on a sphere mesh):

I really hope that somebody knows how to implement this shader.

As an alternative, how do I make it in photoshop?


texts: How can I implement a camera like the one in RotMG?

texts:
RotMG, an MMO top-down shooter, takes on a unique 2d-3d style, and has an intriguing camera;

The game is obviously 3d, not simply isometric, and if you play the game and turn on camera rotation you will notice the effect the game produces, like so.

RotMG is made using flash, and I am currently experimenting with libgdx (which uses lwjgl/opengl). How should I go about implementing a RotMG-like camera?


texts: OpenGL 2D Rasterization Sub-Pixel Translations

texts:
I have a tile based 2D engine where the projection matrix is an orthographic view of the world without any scaling applied.  Thus: one pixel texture is drawn on the screen in the same size.

That all works well and looks nice but if the camera makes a sub-pixel movement small lines appear between the tiles.  I can tell you in advance what does not fix the problem:

GL_NEAREST texture interpolation
GL_CLAMP_TO_EDGE

What does “fix” the problem is anchoring the camera to the nearest pixel instead of doing a sub-pixel translation.  I can live with that, but the camera movement becomes jerky.  Any ideas how to fix that problem without resorting to the rounding trick I do currently?


texts: How do I render only part of a texture to a point sprite in OpenGL ES for Android?

texts:
Using the libgdx framework, I've figured out how to render a texture to a point sprite. The problem is, it renders the entire texture to the point sprite, where I only want a small part of it (since it's an isometric tile image).

Here's a snippet from some demo code I wrote...

create()
{
    renderer = new ImmediateModeRenderer();

    tiles = Gdx.graphics.newTexture(
        Gdx.files.internal("data/tiles2.png"),
        TextureFilter.MipMap,
        TextureFilter.Linear,
        TextureWrap.ClampToEdge,
        TextureWrap.ClampToEdge);

    Gdx.gl.glClearColor(0.6f, 0.7f, 0.9f, 1);

    Gdx.gl.glEnable(GL10.GL_TEXTURE_2D);
    Gdx.gl.glEnable(GL11.GL_POINT_SPRITE_OES);

    Gdx.gl11.glTexEnvi(
        GL11.GL_POINT_SPRITE_OES,
        GL11.GL_COORD_REPLACE_OES,
        GL11.GL_TRUE);

    Gdx.gl10.glPointSize(s);

    tiles.bind();
}

render()
{
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

    renderer.begin(GL10.GL_POINTS);

    // render 3 point sprites at various 3d points
    renderer.vertex(-.1f, 0, -.1f);
    renderer.vertex(0, 0, 0);
    renderer.vertex(.1f, 0, .1f);

    // ... more vertices here if needed (one for each sprite) ...

    renderer.end();
}


texts: Can a Game Engine be built into a Game Engine?

texts:
This confuses me as the title says "Mostly Civilized: A Hex-Based 4x Game Engine for Unity - Part 1"

Unity is a Game Engine, and he is building a game engine for a game engine.

Did he word this incorrectly, or is building a game engine into a game engine a real thing?


texts: I prefer C/C++ over Unity and other tools: is it such a big downer for a game developer?

texts:
We have a big game project using Unity at school. There are 12 of us working on it. My teacher seems to be convinced it's an important tool to teach students, since it makes students look from the high level to the lower level.

I can understand his view, and I'm wondering: Is unity such an important engine in game development companies? Are there a lot of companies using it because they can't afford to use something else? He is talking like Unity is a big player in game making, but I only see it fit small indie game companies who want to do a game as fast as possible.

Do you think Unity is of that much importance in the industry?
Does it endanger the value of C++ skills?

It's not that I don't like Unity, it's just that I don't learn anything with it, I prefer to achieve little steps with Ogre or SFML instead.

Also, we also have C++ practice exercises, but those are just practice with theory, nothing much.


texts: Increasing friction or Adding force relative to transform position in Unity 2D?

texts:
Back again with a quick question! I have a few basic platforming mechanics going on in this scene. I have a prefab platform with an animation that loops back and forth between two different x positions, but does not begin looping until OnCollisionStay2D activates with my player object with the tag "Red cube".

But once the animation starts the red cube has very little friction with the platform and falls off. I have attempted to fix this AddRelativeForce  in this script. Is there any way to increase the friction to where my player cube isn't slipping off? Or is there anyway to script my platform to add constant force to my player where I will move with platform seamlessly? Thank you so much for your time! You guys are a great help :)

using UnityEngine;
using System.Collections;

public class PlatformMovement : MonoBehaviour {

    public Rigidbody2D rb;
    public float speed;

    void Start()
    {
        rb = GameObject.FindGameObjectWithTag ("Red Cube").GetComponent<Rigidbody2D> ();
    }

    void OnCollisionEnter2D(Collision2D coll)
    {
        if (coll.gameObject.tag == "Red Cube")
        {
            Debug.Log ("Something has entered this zone.");
            GetComponent<Animation> ().Play ("Side To Side");
        }
    }

    void OnCollisionStay2D(Collision2D coll)
    {
        if (coll.gameObject.tag == "Red Cube")
        {
            rb.AddRelativeForce(new Vector2(speed, 0), ForceMode2D.Force);
        }

    }

    }


texts: Shadow mapping: what is the light looking at?

texts: I'm all set to set up shadow mapping in my 3d engine but there is one thing I am struggling to understand. The scene needs to be rendered from the light's point of view so I simply first move my camera to the light's position but then I need to find out which direction the light is looking. Since its a point light its not shining in any particular direction. How do I figure out what the orientation for the light point of view is?


texts: Do associative array data structures have a place in game development?

texts:
Is it a bad idea to use a map data structure (an associative array or dictionary) in game development?

According to this flowchart, the ideal container for storing game object's container would actually be a map for many games. But I've heard anecdotal claims that maps are a very bad choice for games.

Is this true?


texts: How do I convert a DWG floor plan to 3D for use in Unity or PlayCanvas

texts:
I wish to take DWG floor plans and make 3D models of them which I can then use in Unity or PlayCanvas.

PlayCanvas accepts FBX 3D models from tools such as Blender, Sketchup, 3DSMax, Maya, etc.

There are a lot of YouTube videos about creating 3D models from DWG in Sketchup but it seems quite manual work. Is there anything better or more automated?

Would it be better to use something like Blender, 3DSMax, Maya to create the 3D model?

How about AutoCAD - would this be better?

Is there are tool that is tailored for designing 3D floor plans that can export a model? I found Autodesk Homestyler which makes it easy to create floor plans, and see them in 3D, but only exports DWG.

The goal is to use these real life floor plans in a game engine because I want to simulate audio sources in the environment.


texts:
I'm using Unity to develop a game. Basically i want the player/rocket to follow a point on the screen where user touches. But It's based on physics. Force must be added when user touches somewhere and the rocket has to reach that point. Gravity is there too. If the rocket passes the point then it has to come by using forces. This is the game
http://www.flashyland.com/219-jeux-flash-vol-Space-Oil.html   (click the red button on the bottom left side and then green button. Arrow keys to play).

The rocket rotates too. I'm not good in physics at all.


texts:
Here's my problem: I need to fit rectangles in a polygon but in "certain way".
I have few rectangular shapes (of different sizes) and I need to put them on a polygon.

My first idea was to always try to put them on the top right of the previously placed shape, and if it is not possible, on the bottom left angle of the previously placed shape. It works but it does not looks great, since it does not take into account the placement of the previously placed shape (sometimes the last placed shape is not the most logical).

From this, I imagine we could have a kind of "navmesh": when a shape is placed, it says that nothing more can be placed here and that it needs to find a better place.

Here is how it should look:

Imagine I have the above case, and I want to add one rectangular shape... it shoud go like this:

... with enough space to welcome a new rectangular shape that could possible fit on the blank space.

So... what I want is to place my shapes on the far top and then on the far left.

Do you guys have any ideas how to do this? Maybe this kind of algorithm already exists and I don't know the name?

Thanks !


texts: How to apply a script to multiple Objects in Unity?

texts:
In Unity, I've almost 200 or more objects. I wish to apply single script to all those objects.

I'm a beginner & learning scripts in Unity.

Edit: At the time of editing the scene itself.


texts:
assuming I want my game to have a Cel-shaded look. There are plenty of tutorials how to implement Cel-shading in hlsl f.e.
But what is the point? If I am creating my assets with Blender or 3d-max I have a lot of possibilities to add materials and shaders in the modeling software.

So why write shaders?


texts:
I have been experimenting with HTML5/JS, trying to create a simple game when I hit a wall. My choice of game loop is too choppy to be actually of any use in a game.

I'm trying for a fixed time step loop, rendering only when required. I simply use a requestAnimationFrame to run Game.update which finds the elapsed time since the last update, and calls State.update to update and render the current state.

State.prototype.update = function(ms) {
    this.ticks += ms;

    var updates = 0;
    while(this.ticks >= State.DELTA_TIME && updates < State.MAX_UPDATES) {
          this.updateState();

          this.updateFrameTicks += State.DELTA_TIME;
          this.updateFrames++;

          if(this.updateFrameTicks >= 1000) {
              this.ups = this.updateFrames;
              this.updateFrames = 0;
              this.updateFrameTicks -= 1000;
          }

          this.ticks -= State.DELTA_TIME;
          updates++;
    }

    if(updates > 0) {
          this.renderFrameTicks += updates*State.DELTA_TIME;
          this.renderFrames++;

          if(this.renderFrameTicks >= 1000) {
              this.rps = this.renderFrames;
              this.renderFrames = 0;
              this.renderFrameTicks -= 1000;
          }

          this.renderState(updates*State.DELTA_TIME);
    }

};

But this strategy does not work very well. This is the result: http://jsbin.com/ukosuc/25 (Edit).

As it is apparent, the 'game' has fits of lag, and when you tab out for a long period and come back, the 'game' behaves unexpectedly - updates faster than intended. (EDIT) Thanks to dreta and Vincent Piel, I was able to fix the issue with tabbing out and finding the game to be updating very fast. The problem with the whole thing constantly stuttering and being choppy still persists.

This is either a problem due to something about game loops that I don't quite understand yet, or a problem due to implementation which I can't pinpoint. I haven't been able to solve this problem despite attempting several variations using setTimeout and requestAnimationFrame. (One such example is http://jsbin.com/eyarod/1/edit).

Some help and insight would really be appreciated!


texts:
First of all, hello everyone,

I'm currently making a program to read Minecraft region files (r.#.#.mca) for a server.
The problem I have is that I can't decompress them, I tried GZip and ZLib decompression but none of them worked. I already searched for solutions but there is little to no information online. It's really important that I find a solution to that issue.

Thanks in advance.


texts:
I'm hoping someone can help me understand the GLViewport and what happens when we resize it

This will illustrate my confusion....

So, here I have a quad stuck in the middle of the screen.  If I have my GLViewport match the device's width and height, I get what is on the first (left hand) picture.  Exactly what I would expect.

Device resolution, 2560 x 1600
Viewport resolution 2560 x 1600
Quad size 200 x 200 (Note, the image above is not to scale!!! :-))
Quad shape, appears as square

Now, for the 2nd (right hand) picture...

Device resolution, 2560 x 1600
Viewport resolution 2560 x 1200 (and centered vertically)
Quad size (200, 200)
Quad shape, appears as rectangle

My question is, why is the quad displaying as a rectangle now and not a square?  I've confirmed by logging that my quad is 200 x 200 pixes - surely the size of the physical pixels stays the same?  They can't change.  So what is going on here?

I thought (clearly incorrectly) that when I scaled the viewport, it literraly just chopped off pixels.

Would appreciate if someone could explain how this works.

Edit

Currently, I'm setting my viewport like this:

width = (int) Math.min(deviceWidth, deviceHeight * 1.702127659574468);
height = (int) Math.min(deviceHeight, deviceWidth / 1.702127659574468);

ratio = width / height;
GLES20.glViewport(offsetX, offsetY, width, height);

Matrix.orthoM(mProjMatrix, 0, -ratio, ratio, -1, 1, 3, 7);

offsetX and offsetY are just so that when there are letterboxes, the viewport is centered.


texts: Why is it difficult to port games from consoles to PC?

texts:
PC ports of console games often come out a month or two later. Why is this?

Games are written in languages that compile on PCs too, so the game logic should compile without issue. What's holding them back then? Is it rendering code or what?


texts: What's a code-efficient way to go about DB objects, DTO objects and actual objects?

texts:
Currently I have 3 different classes for the same type of entity. One is the main class that contains logic and everything the entity needs. Then I have a DB object, that has the same structure as the entity inside the database. The third is a data transfer object (DTO) that only contains the values the client is supposed to know about.
Now whenever I add a variable, I have to add the variable in all 3 classes and copy the DTO class over to the client too. Also, I have to add the variable to each converter method, that creates the DTO and DB objects from the main object and need to add a check to the DTO converter, so that I can differentiate which variables actually need to be updated to lessen the network usage. It's a huge mess and the bigger those classes become, the more I hate my current approach.
What's a smarter approach to this? Maybe there is a way to use C# attributes, but before I try to learn about how to make my own and implement it, I'd love to know if it's even a good choice.
edit 1:
following method checks which values have been updated and not sent to the client yet and returns a new DTO object to send, if the client is not up-to-date. The DTO object is serialized to json and sent as a string. Then its deserialized on the client and the client checks for valid values to know which one to update:
public CharacterDTO GetNetworkDTOValues()
{
    bool shouldUpdate = false;
    CharacterDTO returnDTO = new CharacterDTO();

    if (_clientInstance == null)
    {
       _clientInstance = new CharacterDTO();
    }
    if (_clientInstance.Level != Level)
    {
       returnDTO.Level = Level;
       shouldUpdate = true;
    }
    if (_clientInstance.Experience != Experience)
    {
       returnDTO.Experience = Experience;
       shouldUpdate = true;
    }
    if (_clientInstance.Life != Life)
    {
       returnDTO.Life = Life;
       shouldUpdate = true;
    }

    [...] (there are around 30 more variables)

    if (shouldUpdate)
    {
       _clientInstance = CreateDTO(this);
       return returnDTO;
    }

    return null;
}


texts: Problem with SAT collision detection overlap checking code

texts:
I'm trying to implement a script that detects whether two rotated rectangles collide for my game, using SAT (Separating Axis Theorem). I used the method explained in the following article for my implementation in Google Dart.

2D Rotated Rectangle Collision

I tried to implement this code into my game. Basically from what I understood was that I have two rectangles, these two rectangles can produce four axis (two per rectangle) by subtracting adjacent corner coordinates.

Then all the corners from both rectangles need to be projected onto each axis, then multiplying the coordinates of the projection by the axis coordinates (point.x*axis.x+point.y*axis.y) to make a scalar value and checking whether the range of both the rectangle's projections overlap. When all the axis have overlapping projections, there's a collision.

First of all, I'm wondering whether my comprehension about this algorithm is correct. If so I'd like to get some pointers in where my implementation (written in Dart, which is very readable for people comfortable with C-syntax) goes wrong.

Thanks!

EDIT:
The question has been solved. For those interested in the working implementation: Click here


texts: Problem with moving player through a secript by a set distance

texts:
I am currently trying to add a sort of "dash"-ability to my sidescroller.

What I try to do, is to let the player press a key where a simple key-press causes the player to move quickly into one direction by a predefined distance. During that dash, the character controller is disabled so the player is not able to cancle the dash itself. after the dash, the character controller is enabled again and the dash ability is disabled, so to say on cooldown.
Though the "predefined distance" is what isn't working.

The code for it I have so far is as following.
I have a script for choosing the animations and reacting to key Input, this script includes the following in it's Update method ("a" and "d" are set for the Dash). pstats is my object for the variables in the Player-script.

        float dashing = Input.GetAxis ("Dash");

    if (Input.GetKey ("a") && pstats.dashUsable)
    {
        pstats.DashLeft();
    }
    if (Input.GetKey ("d") && pstats.dashUsable)
    {
        pstats.DashRight();
    }
    if (!pstats.dashUsable)
    {
        dashing = 0.0f;
    }

My Playerscript contains:

    public bool dashUsable = true;
public bool dashUsing = false;
public bool attacking = false;

private IEnumerator WaitForNextDash() {
    yield return new WaitForSeconds(1.0f);
    dashUsable = true;
    Debug.Log("WaitForNextDash Done");
}

private IEnumerator WaitForDashToEnd() {
    yield return new WaitForSeconds(1.0f);
    Debug.Log ("dashUsable being changed");
    dashUsable = false;
    dashUsing = false;
    attacking = false;
    controller.enabled = true;
    StartCoroutine (WaitForNextDash ());
    Debug.Log("WaitForDashToEnd Done");
}

// The two lines below are to create the proper facing-direction for the player
Quaternion targetf = Quaternion.Euler(0, 270, 0);
Quaternion targetb = Quaternion.Euler(0, 90, 0);

public void DashLeft()
{
    attacking = true;
    dashUsing = true;
    controller.enabled = false;
    Debug.Log ("Dash-Left-Skill in use");
    transform.rotation = Quaternion.Slerp (transform.rotation, targetf, Time.deltaTime * 5000.0f);
    transform.position = Vector3.MoveTowards (transform.position, Vector3.right * -100f, 20 * Time.deltaTime);
    StartCoroutine (WaitForDashToEnd ());
}

public void DashRight()
{
    attacking = true;
    dashUsing = true;
    controller.enabled = false;
    Debug.Log ("Dash-Right-Skill in use");
    transform.rotation = Quaternion.Slerp(transform.rotation, targetb, Time.deltaTime * 5000.0f);
    transform.position = Vector3.MoveTowards (transform.position, Vector3.right * 100f, 20 * Time.deltaTime);
    StartCoroutine (WaitForDashToEnd ());
}

(Sorry for the large blocks of Code, but I thought to better include both)

The problem now is that instead of one button press causing a movement by a set distance... like 100 on the x-axis, the player moves as long as the key is hold. Also, the cooldown for some reason is direction dependant, meaning, if I dash to the right, the cooldown works for the right side, though I can dash to the left directily after without cooldown.

What I am trying to get is to have the WaitForDashToEnd to have a duration that fits the duration of the dash movement itself, I can fix that up as soon as I have the actual dash working. Since the dash movement doesn't work as intented yet, the "stun" during the dash isn't fully functional yet either, but that should more or less fix itself once the dash works.

So... how can I manage to have the dash work as a movement over a predefined distance, no matter how long the key is held?

edit: on a sidenote, during dash, the player is oddly lifted a bit above the ground, is there a way to fix that too? In either case, the dash itself has priority.


texts: It is possible to process data on relay servers?

texts:
I have a small game engine done in Java, and re-creating it on C++. While re-creating it i've decided on adding basic p2p online multiplayer. However, after reading more about networking, there are multiple models, and the Client-server host with relay model seems attractive, since it overcomes most of NAT issues of port fowarding and does not expose players public IP.
My point is - can a relay server be used to do some minimal data processing? The goal is not to use a dedicated, full featured server application, but just do minimal calculations on the data to detect some basic cheats.
For example: Preventing internal speed hacks by sending the system timestamp every 60 cycles, and then the relay would store the previous time stamp and compare the next one, if the time difference is less than 1000ms, disconnect the player.


texts:
I have encountered a problem during my first game development:
I thought of a Array<Ground> groundArray that does groundArray.add when a new ground will appear on the screen, and removes oldest ground when it will no longer be seen, if player only moves to the right, like in flappy bird.

The perfect structure would be a queue for such a mechanic, but libgdx doesnt have one. Using libgdx's Array is not intuitive too - i have to reverse the order of elements. It has a method pop() that removes the last element, but no such method to use on the first element.

What are my options here?

extend Array class and add something?
writing my own queue-like class?

UPDATE 18/8/2014

i actually found a way to do it with the default Array:

private void checkGround() {
    for (Ground ground : groundArray){
        if (ground.x  + 500 < camera.position.x){
            groundArray.removeValue(ground, true);
        }
    }

    if (groundArray.peek().x < camera.position.x + 500){
        groundArray.add(new Ground(groundX, -150));
        groundX +=50; //my ground texture is 50 pixels wide
    }
}

Only question left now - will it affect performance when there will be 10000 empty elements before the 10 actual ground elements? In my render method i use:

for (Ground ground : groundArray){
        batch.draw(ground.getTextureRegion(), ground.x, ground.y);
    }

If yes - i will have to make a re-sort method that shifts all the grounds to the beginning of the array.

Will doing so improve this?:

for (Ground ground : groundArray){
        if (ground != null) {
            batch.draw(ground.getTextureRegion(), ground.x, ground.y);
        }
    }

After checking apparently the array size doesnt boost , it size is always equals the number of actual ground objects in it, but i thought that it will count also the null values that were ground objects before. But then surely there would be nullpointers when i tried to draw those null's, so the problem looks fully resolved.


texts: Using binary space partition to lay out scenes in game

texts:
Q: How can I randomly lay out these house scenes in the larger scene such that they don't overlap?

I'm using the Godot Engine to create a little 2D RPG kind of game. I'm laying out a village in a procedural fashion where the largest house is first put down, then the smaller house, and so on. These houses are set in a tilemap, and that itself is set in a larger tilemap scene. I've tried randomly setting them up by using a random value in a Vector2 object, but they may overlap one another. After a lot of experimentation, I happened upon an article about binary space partitions and sought to find an example of this made in the Godot Engine. I found this video on YouTube and used that code to make a small function:

func bsp(map_size_width, map_size_height):
    var rec1
    var rec2
    var back = []
    var contents = [[0, 0, map_size_width, map_size_height]]
    for i in range(0, 4):
        back.clear()
        for rec in contents:
            randomize()
            if rec[2] > rec[3]:
                var width = round(rand_range(0.3,0.7) * rec[2])
                rec1 = [rec[0], rec[1], width, rec[3]]
                rec2 = [rec[0]+width, rec[1], rec[2]-width, rec[3]]
            else:
                var height = round(rand_range(0.3,0.7) * rec[3])
                rec1 = [rec[0], rec[1], rec[2], height]
                rec2 = [rec[0], rec[1] + height, rec[2], rec[3] - height]
            back.append(rec1)
            back.append(rec2)
        contents.clear()
        for r in back: contents.append(r)
    return contents

To use it, I pass the size of the scene (in units of tiles) in the tilemap and it spits out an array which holds the origin of each rectangle, as well as its width and height. An example output looks like this:

[[0, 0, 7, 7], [7, 0, 13, 7], [0, 7, 6, 14], [6, 7, 14, 14], [20, 0, 10, 4], [20, 4, 10, 7], [20, 11, 10, 4], [20, 15, 10, 6], [0, 21, 8, 4], [0, 25, 8, 5], [8, 21, 4, 5], [8, 26, 4, 4], [12, 21, 5, 5], [12, 26, 5, 4], [17, 21, 6, 9], [23, 21, 7, 9]]

And a more visual example that could use this function looks like this:

Now all I need to do is figure out how to assign one house to one fitting rectangle. I have tried first matching the size of the house scene to a matching element in the array. However, this, too, can lead to overlapping houses. Then I thought of taking out the element when it's matched with a house element. But this can lead to house scenes which don't even get counted.

FWIW, here's the current code that I'm using:

# House 1
var h1 = get_node("House1").get_used_rect().size
# House2
var h2 = get_node("House2").get_used_rect().size
# House 3
var h3 = get_node("House3").get_used_rect().size
# Our function in action.
var binary_things = bsp(world_tile_width, world_tile_height)
# Holds the data for the house scenes
var coor = []
# Set the largest house, "h3", first.
for i in [h3,h2,h1]:
    # Go through and compare the sizes of the houses.
    for g in range( binary_things.size() ):
         # If there is a match, append it to the "coor" array.
         if binary_things[g][2] > i.width and binary_things[g][3] > i.height:
             coor.append(binary_things[g])
             # Remove it from circulation.
             binary_things.remove(g)
             break
# Create the Vector2 objects for the houses.
var w = Vector2( coor[0][0], coor[0][1] )
var v = Vector2( coor[1][0], coor[1][1] )
# In tests, it is found that the third element in the "coor" array is not filled.
var q = Vector2( coor[2][0], coor[2][1] )

# Convert the tile coordinates to pixel coordinates.
var translated1 = map_to_world(w)
var translated2 = map_to_world(v)
var translated3 = map_to_world(q)

# Set the scenes in the larger scenes.
scene_1.set_pos(translated1)
scene_2.set_pos(translated2)
scene_3.set_pos(translated3)


texts: What's wrong with my normal map implementation?

texts:
I'm trying to write my own 3D engine from scratch in C, and right now it can render spheres, but I wasn't able to perfectly implement norl maps.

All of the resources I've found online about normal maps are about applying them to meshes and talk about making sure yso I just kind of guessed the right way to do it for a sphere. The basic algorithm I'm using to perturb the normal vector is:

struct _Vec3 {
    double x;
    double y;
    double z;
};

struct _Rgb {
    unsigned char r;
    unsigned char g;
    unsigned char b;
};

void adjustNormal(Sphere* sphere, Vec3* point, Vec3* normal) {
    double* arr = getSphereCoordinates(sphere, point); // get coordinates of point, where 0 < x, y < 1
    double x = arr[0];
    double y = arr[1];
    Rgb* color = getPixel(sphere -> normalMap, x, y); // get the data from normal map
    x = (color -> r) / 255.0;
    y = (color -> g) / 255.0;
    double z = (color -> b) / 255.0;
    Vec3** ortho = getOrthogonalVectors(normal); // basis of tangent space
    Vec3* tangent = ortho[0];
    Vec3* bitangent = ortho[1];
    scaleVec3(normal, z);    // scale normal vector by z
    scaleVec3(tangent, y);   // scale tangent vector by y
    scaleVec3(bitangent, x); // scale bitangent vector by x
    normal = add3(normal, tangent, bitangent); // add together three vectors
    normalize(normal);
}

Now, I feel pretty confident that getSphereCoordinates and getPixel works because applying a regular texture (not normal map) to a sphere works fine. I'm less confident about getOrthogonalVectors because even if I change that, I still have an issue with the normal map. Just in case, here it is:

Vec3** getOrthogonalVectors(Vec3* vec) {
    Vec3 temp;
    copyVec3(&temp, vec);
    temp.x += 10; // no matter how I change
    temp.y += 1;  // this to get a nonparallel vector,
    temp.z += 1;  // the normal map isn't correct

    Vec3* v1 = cross(vec, &temp);
    Vec3* v2 = cross(vec, v1);
    scaleVec3(v2, -1); // necessary for orientation

    normalize(v1);
    normalize(v2);

    Vec3** ans = malloc(sizeof(Vec3*) * 2);
    ans[1] = v1;
    ans[0] = v2;
    return ans;
}

Below is the normal map being used and what the sphere looks like after the map is applied.

This picture is with the light source being at the same location as the camera, so in theory the entire front of the sphere should be lit. Is there something I'm doing wrong?


texts: How to edit key-value pairs (like a Dictionary) in Unity's inspector?

texts:
I have a spell system I am creating, the principle is as follows:

Each spell is an autonomous prefab. It contains a script with some properties (base damage, duration...) that can be modified in the inspector.
I have a Spell enum listing all possible spells in the code, which is used in the game logic
When I want to cast a spell, I need to be able to get this spell's prefab to instantiate it and read its informations
Each actor (be it players or enemies) needs to have a list of possible animations for the spells

The problems with how I am trying to implement are:

For listing each actor's animations I could use a Dictionary<Spell, Animation>, but dictionaries aren't supported by the inspector which makes it hard to easily edit multiple actors type.
I need some way to easily access a spell prefab from the corresponding enum. Here too I could use a dictionary but I can only reference to prefabs in the inspector, not in code, meaning I wouldn't be able to fill this dictionary

I am looking for a way to easily associate my spells enums to the corresponding prefabs and animations


texts: Tips / pitfalls in selecting and working with publishers?

texts:
I am thinking about working with a publisher for an iPhone game that I have developed.  I have been independent until now, but want to look into the publishing route because I just don't have the resources to market the game myself, and I would rather not take outside investment.

So, those of you who have gone this route, what should I be looking for in a publisher?  What should I avoid?


texts: How do I detect a line collison in LIBGDX?

texts: I am drawing a continuous line using Pixmap. I want to check for a collision / intersection of my line with the already drawn line.


texts: Process Purchase Event get called on each App launch - iOS

texts:
At present when I launch the app, each time ProcessPurchase event get called in iPhone device. Though upto now I have not pressed any purchase related buttons.

Yes I have setup subscription purchase within my app and before I have purchased subscription in sandbox environment two to three times but now their time period is expired.

Here you have debug log for actual event happening:

As per my past experience, ProcessPurchase event require to call only two times when a user purchase something or at restore purchase time.

So why its get called each application launch that I can't able to understand!!!

Please give some help in this so I can complete my Unity IAP related thing.

Source Code :
https://pastebin.com/bNpXsjHg


texts: Procedurally generated terrain map. Blend Transitions between terrain types

texts:
The question isn't the greatest wording ever sorry.

I have been learning about and prototyping some texture and terrain generation stuff and have run into something perhaps you can help me with.

How it works:
I am procedurally generating a terrain height map. It can scroll endlessly in any direction. (image 1)
I clamp and mix the colors depending on the value of the height map (image 2)

This is working very well and runs very fast currently, it is after all very simplistic at the moment.

What I need to find is a good way to blur/distort between the terrain transitions. As you can see currently it has very ridged lines and doesn't look all that natural. Given that this is whole thing is procedurally generated I obviously need to find an algo for the blending that can run on the fly. I attempted a bit of pixel jittering and it just looked bad. Also what ever I use has to be able to be seeded so that it maintains consistency (though I doubt that will be a problem since they will most likely all run on randoms).

Any insight would be much appreciated.
If I managed to leave out any needed info in my rush to post this just let me know.


texts: Strange behavior of RigidBody with gravity and impulse applied

texts:
I'm doing some experiments trying to figure out how physics works in Unity.

I created a cube mesh with a BoxCollider and a RigidBody. The cuve is laying on a mesh plane with a BoxCollider.

I'm trying to update the object position applying a force on its RigidBody.
Inside script FixedUpdate function I'm doing the following:

public void FixedUpdate()
{
    if (leftButtonPressed())
        this.rigidbody.AddForce( this.transform.forward * this.forceStrength, ForceMode.Impulse);
}

Despite the object is aligned with the world axis and the force is applied along Z axis, it performs a quite big rotation movement around its y axis.
Since I didn't modify the center of mass and the BoxCollider position and dimension, all values should be fine.

Removing gravity and letting the object flying without touching the plane, the problem doesn't show. So I suppose it's related to the friction between objects, but I can't understand exactly which is the problem.

Why this? What's my mistake? How can I fix this, or what's the right way to do such a moving an object on a plane through a force impulse?


texts: How to choose cell to put entity in in an uniform grid used for broad phase collision detection?

texts:
I'm trying to implement the broad phase of my collision detection algorithm. My game is an arcade game with lot of moving entities in an open space with relatively equivalent sizes.

Regarding the above specifications, i decided to use an uniform grid for space partitioning. The problem i have right know is how to efficiently choose in which cells an entity should be added. ATM i'm doing something like this:

for (int x = 0; x < gridSize; x++) {
    for (int y = 0; y < gridSize; y++) {
        GridCell cell = grid[x][y];
        cell.clear(); //remove the previously added entities
        for (int i = 0; i < entities.size(); i++) {
            Entity e = entities.get(i);
            if (cell.isEntityOverlap(e)) {
                cell.add(e);
            }
        }
   }
}

The isEntityOverlap is a simple method i added my GridCell class.

public boolean isEntityOverlap(Shape s) {
    return cellArea.intersects(s);
}

Where cellArea is a Rectangle.

cellArea = new Rectangle(x, y, CollisionGrid.CELL_SIZE, CollisionGrid.CELL_SIZE);

It works but it's damn slow. What would be a fast way to know all the cells an entity overlaps?

Note: by "it works" i mean, the entities are contained in the good cells over the time after movements etc.


texts: How can I resize a game object using single drag handle?

texts:
Really need your help. I'm trying to create a custom controller for my app to allow users to resize and rotate game objects using a single drag object.
I was able to create the code to create the visuals and to rotate it but I'm stuck on how to resize the game object. To position the drag handle at the start, I'm getting the bounds of the target object and taking the bounds.extents.magnitude to determine the y position.
So I was hoping the behavior would be such that when you drag the handle closer to the center of the target object it shrinks the bounds.extents.magnitude based on the new handle position and then becomes bigger if you go further away from the center of the target object.

Here is where I am now:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CircleMaker : MonoBehaviour
{
    public float lineWidth = .1f;
    private int segments=360;
    private LineRenderer line;
    private float radius;
    private Renderer boundsSource;
    private Bounds bounds;
    public GameObject dragHandle;
    public GameObject target;
    private int pointCount;
    private Vector3[] points;
    public int angle = 0;
    public float zPosition = -8.0f;
    public bool isDraggingHandle = false;

    void Start()
    {
        line = GetComponent<LineRenderer>();
        boundsSource = target.GetComponent<Renderer>();
        bounds = boundsSource.bounds;
        line.useWorldSpace = true;
        line.startWidth = lineWidth;
        line.endWidth = lineWidth;
        line.positionCount = segments + 1;
        line.receiveShadows = false;
        line.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;

        pointCount = segments + 1;
        points = new Vector3[pointCount];

        float r = bounds.extents.magnitude;
        float d2r = Mathf.Deg2Rad * (target.transform.localEulerAngles.x * 360f / segments);
        dragHandle.transform.position = new Vector3(Mathf.Sin(d2r) * r, Mathf.Cos(d2r) * r, zPosition) + target.transform.position;

        DrawCircle();

    }

    void Update()
    {
        if (isDraggingHandle)
        {
            //rotate object based on drag handle location
            Vector3 direction = target.transform.position - dragHandle.transform.position;
            int sign = (direction.x >= 0) ? 1 : -1;
            float offset = (sign >= 0) ? 0 : 360;
            float angle = Vector2.Angle(Vector2.down, direction)*sign+offset;
            target.transform.rotation = Quaternion.Euler(0, 0, angle);

        }

        if (target.GetComponent<DragAndDrop>().isDragging == true)
        {
            dragHandle.transform.parent = target.transform;
        }
        else
        {
            dragHandle.transform.parent = null;
        }

        DrawCircle();
    }

    //draw circle around target gameobject based on bounds.extents
    void DrawCircle()
    {
        radius = bounds.extents.magnitude*target.transform.localScale.x;
        for (int i = 0; i < pointCount; i++)
        {
            float rad = Mathf.Deg2Rad * (i * 360f / segments);
            points[i] = new Vector3(Mathf.Sin(rad) * radius, Mathf.Cos(rad) * radius, zPosition) + target.transform.position;
        }

        line.SetPositions(points);
    }
}


texts: Proper setup for Mecanim standing jump animation

texts:
I have a character standing jump animation with that the character at start prepares for the jump (flexing downwards) and then jumps up in the air and i'm wondering how to get it working properly with Mecanim in Unity.

The difficulty is that the jumping in my code isn't just an on/off trigger but is triggered by a Y velocity that determines how high the character can jump.

With my current approach, when jumping the character lifts instantly off the ground and then executes the starting part of the animation which of course looks wrong.

Is there any way to configure single jump animations with Mecanim to work with a Y velocity or do I have to split the animation into three parts (prepare/jump/landing) for this?


texts:
I have built a few mazes and are familiar with maze algorithms however all examples I have learnt from are square or rectangular.

In these mazes the code structure usally has a 2d array of maze cells and it is easy to navigate or test to adjacent cells.

How do you structure the code for a say a Y or circular shaped maze to know what the avaliable joints between cells/nodes in the maze are?


texts: How to draw or translate into world space?

texts:
I've been hacking around with OpenGL, but there's a few concepts which I can not find the answer on.

I want to draw three GL_QUADS next to eachoter like so:
1[2][3]

I know GL_QUADS are deprecated, but for this question i'd like to use them nonetheless.
Each quad will have its own color, the first being red, second green and the third blue.
[r][g][b]

my code:

void display()
{
  glClear(GL_COLOR_BUFFER_BIT);

  GLfloat vertices[] = {
    -1, -1,  1, -1,  1, 1,  -1, 1,
     1, -1,  3, -1,  3, 1,   1, 1,
     3, -1,  5, -1,  5, 1,   3, 1
   };

   GLfloat colors[] = {
    1, 0, 0,  1, 0, 0,  1, 0, 0,  1, 0, 0,
    0, 1, 0,  0, 1, 0,  0, 1, 0,  0, 1, 0,
    0, 0, 1,  0, 0, 1,  0, 0, 1,  0, 0, 1
  };

  glLoadIdentity();
  glEnableClientState(GL_VERTEX_ARRAY);
  glEnableClientState(GL_COLOR_ARRAY);

  glVertexPointer(2, GL_FLOAT, 0, vertices);
  glColorPointer(3, GL_FLOAT, 0, colors);

  glMatrixMode(GL_PROJECTION);
  glTranslatef(-1, 0, 0);

  glDrawArrays(GL_QUADS, 0, 12);

  glDisableClientState(GL_COLOR_ARRAY);
  glDisableClientState(GL_VERTEX_ARRAY);

  glFlush();
}

result being:

I'm confused as which to which matrix I should apply the translation matrix and in which order.
I'm almost certain I should not use glMatrixMode(GL_PROJECTION)
What are the initial values of a matrix?
I'm not certain which coords to pass in the vertex array at this point, model space or world space?

I hope you can shed some light in my confusion.


texts: Solutions for maintaining importers and exporters when chaning file formats

texts:
After having a very short discussion with Delix on youtube (see link below) on custom data storage formats, I started thinking. What are some useful ways of maintaining importers / exporters when you change your file format during the development of your game?

The most obvious solution would be to write different functions for file formats like exporterV1(), importerV1(), exporterV2(), importerV2(), etc. Then call the correct function based on some sort of header in your file. Like using the first byte(s) to store the version of the file format. However, this seems incredibly inefficient. Especially since you'll have to writer converter functions to translate between the file formats. I.e. v1tov2converter().

Usually when writing this kind of thing, a voice in the back of my head screams "there must be a better way of doing this", but I'm drawing a blank so far.

Naughty Dog seems to use scheme for describing both the data and how it should be read. However, my knowledge of scheme is non-existent so I have no clue how that would work. This would however, solve my problem, as the data would describe itself see reference.

What are, in your opinion, some of the clever ways you know of, to solve this issue?

Edits

[EDIT 1]: As a response to a question asked by @DMGregory: I'm mostly talking about changes during development of the game(engine). Changing file formats in production seems like a can of worms I would not like to open. Especially if your dealing with importer / exporters of safe game data.


texts: How to achieve smooth gameplay in a physics based multiplayer game? (2d)

texts:
I'm using cocos2d 2.0 and Gamekit for networking. I've got a server/client model. It works over wifi (local) and bluetooth. (Xcode 4.3, Objective C)

Basically, there's a ball and 2 or more players. What I wanted to do is:

The physics is completely simulated on the server. The clients send their inputs to the server and the server sends the position (only the position and rotation that's it) to the clients. The clients than set the position of the objects to the given position datas.
The ball is also simulated on the server.

Problem: There can be a high latency and the gameplay would be not smooth on the client side. The players can freely move around and interact with the ball (just pusing it and such things).

I read about prediction but how should it be possible to guess the movement of the player? The player can move completely free (360°).
I also read about Servertime and clienttime but I didn't get it very well :/

How could I reduce lag? Please explain your solution because I don't want to just copy and paste it, I want to understand it.

PS: Probably I will have very low ping (1-5 ms) on wifi (local, both devices on the same network), I guess but I want to implement Gamecenter too and than I would need to handle the lag. But handling the lag on wifi/bluetooth would be great to, to achieve smoother gameplay.


texts:
A log of game events (as opposed to error / debug logs) for an entire cluster/shard is very useful for a commercial MMO that is in a live production environment, providing vital support for customer service, and the means for historical analytics.

The project that I am currently working on uses a relational database to store all of the game event logs, and while that method works fine it seems to me that the read-only, chronological nature of the logs would allow for a more efficient storage format.

I'm not sure where to begin learning about building custom binary log formats, however. What are your experiences with creating custom log formats, or any recommended papers / articles on the subject?


texts: I want to have a plane that shows an animated Gif as it's texture, so essentially it will be a movie. Can I apply an animated Gif as a texture? If so, does it apply like a normal texture? Note: I know about Movie Textures, but don't want to use them


texts: How do I launch a ballistic projectile to hit a moving target, given: launch position & angle, target position & velocity?

texts:
This problem is in 3D space. My question is: How do you find the initial velocity of a projectile that flies under constant gravity, so that it hits a target moving with constant velocity, given the parameters:

Launch Position
Launch Angle
Target Position
Target Velocity
Acceleration due to Gravity

Most of the answers I find solve the problem using Launch Speed instead of Launch Angle.

The reason why I want to use Launch Angle, rather than Launch Speed, is because the arc of the projectile doesn't look good when solving with Launch Speed. The low angle is too low, and the high angle is too high.

My goal is to be able to adjust the arc of the projectile to be more visually pleasing, while still being able to hit the moving target 100% of the time.


texts:
I am designing a simple "Plant vs Zombies"-like game, but without graphics (just polygons) for class homework.

I came to the point where I need to calculate damage to different entities. Por example, the zombie can kill the shooting turret in 3 bites, but would instantly kill the "engineer" that puts the towers if it touches him.

I was thinking on a List approach, where the Engineer always takes damage, from turret, zombie, land mine, etc, but he knows how much damage takes from any of those entities. It is not really realistic though, and if new entities are added, if I forget to add them to the engi or other entity's damage list, it would not get damaged at all.

Any help would be very appreciated.


texts: Two 2D objects in Unity aren't colliding together

texts:
In Unity 5, I have a player shooting a projectile in aim to hit a boss, and inflict damage upon contact with the projectile. Though for some reason, the projectile and boss aren't colliding with each other.

I've done the following;

Made sure that both the projectile and boss have a BoxCollider 2D and Rigidbody 2D
Made sure that they're on the same Z-Index and on the same layer
Tried to Debug.Log() if there's any collision (there isn't)
Made sure I'm using OnCollisionEnter2D on the boss' health script
Compared the syntax I use with another collision (where the player collides with an object and dies - this works perfectly fine).

However, none of these seem to be working.
This is the boss' health script:

void OnCollisionEnter2D (Collision2D coll)
{
    Debug.Log("COLLIDED");
    bosshealth -= 1;
}

Here is the projectile prefab:

And the boss prefab:

Does anyone have a clue as to why they're not colliding? the projectile just glides over the boss

EDIT: I found a temporary fix! Disabling the Kinematics of the boss allows for both objects to collide, and successfully display a debug message!
Just a problem though; I don't want the boss to freely float around in space. I use the kinematic to ensure it stays put at all times until told to by scripts.

Is there a way to get around not having to disable the kinematics?

EDIT 2: Then again, I am removing the projectiles on impact anyway, so the actual boss doesn't move, but that seems dirty :/


texts: How can I achieve smooth shading / glow from one tile to another?

texts:
I've been working on a tile-based game in which some areas may be lit (currently seen), some may be black (never seen) and some may be dark (previously seen, but not currently seen).

Looking at the absolutely wonderful Pixel Dungeon that has a similar scheme, it has an effect where the dark/black tiles sort of "bleed" into lighter  tiles (image from the game's Tumblr):

Look at 1 above - the area beyond the wall is dark, the wall itself it lit, but the darkness "glows" and creates a nice transition to light. There's also a slightly different "glow" from black tiles to light tiles, as seen at 2 - it's darker (you can't even see the edge of the wall).

I'd be delighted to implement something similar, and if I just want the effect as seen at 1 and 2 I can just create appropriate overlays, something like:  for shade-from-dark and  for shade-from-black.

It's not that simple, however:

For locations such as 3 I need black-to-dark shading.
For locations such as 4 I need shading from 2 dark sides and two lit sides.
For locations such as 5 I need shading from 2 black sides, 1 dark side and one lit side.
For locations such as 6 I need shading from 1 black  corner, 1 dark... hold on a minute, this gets insane!

So I'm looking for some saner solution to achieve this lovely effect.

So far I've had these ideas:

Generating textures at run-time given the "light status" of the 9 surrounding tile of the tile (and cache these textures).
Applying a shader when drawing these tiles to interpolate the shading required at each pixel from the surrounding tiles, using either bilinear or bicubic interpolation.
Changing the "dark" and "black" textures to actually be larger than a tile - containing the texture + bleed into adjacent tiles, something like:

And then let these textures overlay each other (but that's a lot of blending).
Byte56 suggests suggests setting the color per vertex for the underlying tile and it will blend with the texture, but that does not seem accurate enough - for example a dark tile surrounded by black tiles will be completely black, which isn't good. And what if in all the corners are black tiles and on all the sides are lit sides? I guess I could model this accurately by having 9 vertices for each tile instead of 4.

I'd be happy for some input about these proposals as well as any other ideas for achieving this.

I'm using Libgdx and Java, but I have a feeling an answer will not really depend on the framework being used.


texts: Good resources for learning about game architecture?

texts:
Are there any good resources for learning about game architectures? I am looking for high level overviews of different architectures. I tend to find information about the various pieces of a game such as entities, physics engines, scripting, etc but not about how to bring all of the pieces together.

As a bonus, how does the type of game influence this? For example, a platformer and an MMO would have differences.


texts: Efficient player state architecture in Google App Engine

texts:
I am investigating Google App Engine for use in a browser based MMO. The player will make a server request when ever they build, buy or do any other action that the server needs to process. Therefore I am estimating a server request no faster than once per 10 seconds.

I want to store all my player data in one data structure (entity), because I have heard this is the most efficient way -- if not please correct me. So I figure that when a player causes a server request, I need to load/access the player's state data, carry out the action the player wanted to do and then store the result.

However, from an efficiency point-of-view, what is the best way to access the player data? I thought about using the datastore and maybe memcaching the result in memory for fast lookup. But don't I still need to write the data back out to the data store if it's cached? Should I write it out every time data changes? I looked at write behind caching but this seems to eat through your task queue quota.

Any ideas on the best approach? Best being defined as the most efficient method using the Google App Engine.


texts:
So the game i'm making will have items with different functionality such as ammo boxes, med-packs, guns, food, water ect. My problem is i don't know where to put the code for the specific functionality e.g code for eating food.

My item system works by having a database (dictionary with a string and item stats) and an inventory list of strings. When using a item i look up the stats of that item using the string in the inventory list.

One idea i had was to have scrips on the player something like heal, ammo, gun ect, and have methods in those scrips for the functionality. Is this a good way of doing it?


texts: What does Mecanim's "loop pose" parameter do?

texts:
What exactly does the loop pose parameter do?

What's the difference between enabling or disabling it on animation clips?


texts: How to deal with large depth buffer values due to extreme distances

texts:
Alright, this is semi-related to my last question here

So I've got an really big coordinate system and need to handle rendering large astral bodies from extreme distances. My current approach involves different rendering passes based on the distance of the object. The extremely far objects are simply rendered first without writing to the depth buffer using a painters algorithm, while the closer objects are ran through my standard pipeline.

This works however, it isn't ideal for me. The problem isn't when the planet is far enough to fit on the screen. The billboard technique Nicol mentioned below works fine in this case. However, it's when the player is in a fairly low orbit from the surface. I can't use a billboard and would like the terrain to be able to run through my standard pipeline to make it nice and properly lit. With my limited depth buffer though, this isn't possible without z-fighting or letting it clip past the far plane.

My question is are there any other approaches I can take? I'm looking into using a linear depth buffer but this doesn't sound too easy since DX11 only supports a floating point depth buffer and I would have to implement all the z culling functionality and what not myself with a standard render target.


texts:
I'm making a game for Android with AndEngine.

It's going quite well, but now I'm stuck on something.
My main character has a elasticity set in its fixturedef so it bounces around throughout the game.
Now i want the user to be able to not let the player bounce when he does a control.

So my question: how can I modify the elasticity of my character? Because I saw you can adjust the setDensity and setFriction, but I cant see the setElasticity....

Thanks in advance!


texts: LIBGDX: Shoot a bullet using mouse position

texts:
I want to shoot a bullet towards my mouse position but I think that my math is probably wrong since the position the bullets travel to isn't the right one.
Here's my code
Vector2 bulletDirection = new Vector2(screenX - player.getX(), Gdx.graphics.getHeight() - (player.getY() - screenY)).nor();
bullet.setPosiion(player.getX(), player.getY());
bullet.translate(bulletDirection.x * flightSpeed, bulletDirection.y * flightSpeed);

Can you tell me what I'm doing wrong? The "bullet" object is my current bullet sprite


texts: How to stop movement when an action key is pressed even if movement key is pressed

texts:
I'm making a 2d side-scrolling fighting game in game maker:studio and I want to make a code that when the player attacks he stops moving.
I've tried some options:

keyboard_check(ord("D"));

both this and

keyboard_check_pressed(ord("D"));
x += 0

I also tried

hspeed = 0

I also tried adding these to my left and right key events:

if (sprite_index = spr_atk_right)
 {
 x -=4 for right key event or x += 4 for left key event
 }

I have a right key and left key event with the simple code
x += 4 for the right key and x -= 4 for the left key. I was hoping the second set of codes would cancel it out but neither worked.


texts: How to handle entity path-finding and movement in a large networked world?

texts:
Considering the image above with tiles split into 32x32 boxes, I have an entity which is marked to 'aggro' nearby players that come close to it. I'd like this monster to ideally chase the player (and continue to chase the player for a while). Currently, my only movement is done my a simple interpolator for remote entities and this works because the gaps between movement updates are rather small.

I can't successfully just tell the client that the monster wants to move to the position he/she is at, as that will cause the entity move much faster than it should (this can probably be solved with using some math for the interpolation co-efficent) but more importantly it does not look realistic and may clip walls! I don't want to simulate the entire movement on the server if it can be avoided... although I guess I could but that still wouldn't solve the clipping issue. I suspect the solution involves some path-finding and sending the client periodic node updates and letting them simulate the movement but I'm unsure.

Thanks!


texts: Is it possible to get a Vector3 from a single Input Action in Unity's Input System?

texts:
I'm trying to implement moving up/down (R/F), left/right (A/D), forwards/backwards (W/S) all at the same time using Unity's new Input System. There is an Action type for Vector3, but there doesn't seem to be a corresponding type for it.

The way movement works right now means that it would be a lot better to get the whole vector at the same time for it to work smoothly. Is there a way to do this with a single Input Action, or will I just need multiple?


texts: Make an object rotate from 0 to 360 degrees by using the trigger button on the htc vive controller

texts:
Hello I would like to be able to make a sphere that is attached to a cube rotate  from 0 to 360 degrees by pressing the trigger on the vive controller. As the sphere rotates I want it to be able to stop at any of the degrees in rotation. For example I press the trigger and the sphere starts rotating but I can stop the rotating at 190 degrees or 10 degrees or 359 degrees etc... I would appreciate any suggestions.
Best Regards,
Rafman27


texts:
I'm making a paint program using applets in Java, and I want to create some sort of color palette where the colors blend into each other, similar to this:

However, I'm having trouble understanding the correlation between the R, G, B, values and the X, Y coordinates for both the outer circular color palette, and the inner hue selecting palette.

Representation:


texts: Attaching objects on collision in Unity?

texts:
I'm trying to make a game where the player can connect objects Lego style with objects becoming children of any object they come into contact with, so if the parent object is moved the child is moved too, but the child object can be dragged away to disconnect it.

What is the best way to go about doing this?


texts: Smoothness slider is not active. Why and how to make it active?


texts: Trying to implement bounding box collision

texts:
I've been trying to do collision detection using the Intersects() function with two rectangles.

I've got a player and multiple enemy's. When the player intersects with an enemy a bool var is set to true and the enemy is removed, the next time the player intersects with an enemy I wan't some thing else to happen.

Here is the code:

private void HandleCollision()
        {
            bool hasBlock = false;

            List<int> bulletsToRemove = new List<int> ();
            List<int> enemysToRemove = new List<int> ();

            for (int i = 0; i < Enemys.Count; i++)
            {
                if ( hasBlock == false && Enemys [i].EnemyBounds.Intersects (Player.PlayerBounds))
                {
                    enemysToRemove.Add (i);
                    Bullets.Add (new BulletEntity(EnemyBox, Player.Position));
                    hasBlock = true;
                    Console.WriteLine ("has block == false");
                }
                else if ( hasBlock == true && Enemys [i].EnemyBounds.Intersects (Player.PlayerBounds))
                {
                    Console.WriteLine ("has block == true");
                }
            }

            for (int i = 0; i < bulletsToRemove.Count; ++i)
            {
                Bullets.RemoveAt (bulletsToRemove[i]);
                i++;
            }
            for (int i = 0; i < enemysToRemove.Count; i++)
            {
                Enemys.RemoveAt (enemysToRemove [i]);
                i++;
            }
        }

My problem is  the every time the player intersects with the enemy the code after "if ( hasBlock == false && Enemys [i].EnemyBounds.Intersects (Player.PlayerBounds))" get executed. I can't for the life of me figure out what I am doing wrong. I would love some help.

In my mind when hasBlock is set to false the next enemy should pass through the player and not be removed.