texts: LibGDX changing actors parents is resulting in unwanted (x,y) translation

texts:
I have a Rolodex of task item actors I want to drag to an agenda tablet.  My drag and drop functionality is non-native, but came from modifying a book's implementation.  The problem seems to be when I change the parent of a task item, 'a', to the agenda's parent, 'other':
other.getParent().addActor(a);

When I do so the actor's coordinates shift.  I want the actor to remain in the same spot I dropped it down.  It worked as desired previously, possibly because the Rolodex's parent and the agenda's parent shared the same, whole-screen dimensions.  I've since moved away from layout to positioning actors and their groups on the screen with setBounds().  Tracking the (x,y) coordinates of my dragged item I'm getting negative values for x while it remains visible on screen, making me think actor.getX() and actor.getY() return values relative to the parent carousel container class I made, and not the screen/stage nor the agenda's container.
I found a set of methods off of Actor that looked promising, localToXXXX(Vector2), and experimented with a variety of them before settling on the following I think should work:
            Vector2 snapShot = a.localToActorCoordinates(other.getParent(), new Vector2( a.getX(), a.getY()) );
            other.getParent().addActor(a);
            a.setBounds(snapShot.x, snapShot.y, a.getWidth(), a.getHeight());

...but it doesn't.  Converting it to stage or screen coordinates with the other method options shifts it even farther away from desired. What am I misunderstanding?  How can I change an actor's parent without the x,y shifting?


texts: Procedurally Generated Top View 2D RPG Map Generation

texts:
Procedural generation is a fascinating concept and is gaining popularity in the gaming industry.  The thought of playing a game that has new content every-time the game is played is very exciting to me.

My question is how would I go about generating top view 2D maps with the appropriate transition tiles?

I know how to create top view maps with stand alone tiles. For example I can generate a procedural map with grass and trees. However I can not generate forests of different sizes and shapes. How do I know which forest sprite to put where? I'm trying to loop over the map tiles and accessing the surrounding tiles to pick which tile is the appropriate one. However wouldn't this approach lead to error in which forest tile is placed where? The computer would have to know the size of the forest and how the forest is shaped.

The problem seems too complex for me. Any ideas on how to break this problem down would be much appreciated or if you just want to talk about procedural generation I'm game for that too.

So far I've generated a forest but I'm having trouble making it look right. Here is what I have so far. https://76295db93db3812642fa5ba984c042fa81ffc37c.googledrive.com/host/0B6H3TRExU5M9eEkyd2FreHhiNlU/


texts: Algorithm for 2d AI aiming to compensate for gravity

texts:
In a 2d side-view scenario I have two riflemen aiming at each other. By normalizing the x and y difference they know the direct path to the enemy.

However, gravity will pull the projectiles downwards, so aiming straight for the enemy is obviously useless.

Any interesting ideas for AI-logic when it comes to adding a correction based on world.gravity (which is a "force" in y-pixels per physics tick) and enemy.path (libgdx Vector2 with the X and Y difference to the enemy. Weapon.muzzleVelocity could also be factored in (double, speed in pixels after the shot is fired.

I've been thinking of two things:

Option 1 - Magic numbers

The X distance is multiplied by a magic number (such as gravity) to produce a reasonable close result to an aiming offset. Possibly also factoring in Y-distance, but in most cases, the Y distance should be close to 0.

Pros: Simple, easy to implement, quick, low calculation overhead

Cons: Boring, A bit too arcade for my taste with a very static result, Been done before countless times including by me in previous projects

Option 2 - Firing table

AI trial and error, basically. Each time the unit fires, the X (and Y?) distance of that shot is recorded with the offset used, and the result (hit vs too low vs too high) is registered. Each time the unit fires it'll look up for the closest match to the x-distance to get a rough estimate on aiming offset.

Pros: Units become more valuable as they learn, it's a lot more modern, and it makes sense to me.

Cons: Unit types with low rate of fire will not have much use of their firing table. It's also somewhat complex to implement and will cause a much larger memory footprint as the firing table grows.

For the record, I'm writing this in java/libgdx, mainly targetting the android and HTML5 platforms, but if it turns out to be decent, ports are expected. I'd love to hear other ideas for how a unit can come up with an aiming offset, as well as pros/cons. I have to pick something, and I'm not entirely convinced either of my own algorithms are right for the task.


texts: Trouble with Inventory System and Item References

texts:
I'm currently trying to get a simple inventory system to work but I'm having a lot of trouble.

This isn't the exact code I have, but it's a shorter version that I'm pretty sure would function the same:

public struct ItemSlot {
    public Item item;

    public ItemSlot(Item item) {
        this.item = item;
    }
}

public class Item : MonoBehaviour {
    public string itemName;
}

public class Accessory : Item {

}

public class Inventory : MonoBehaviour {
    public ItemSlot[] itemSlots = new ItemSlot[1];

    public void AddItem(ItemSlot slot) {
        itemSlots[0] = slot;
    }
}

public class Player : MonoBehaviour {
    public Inventory inventory;

    private void Update() {
        if (Input.GetKeyDown(KeyCode.E)) {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hitInfo;

            if (Physics.Raycast(ray, out hitInfo, 20)) {
                GameObject target = hitInfo.collider.gameObject;

                inventory.AddItem(new ItemSlot(target.GetComponent<Item>()));
                Destroy(target);
            }
        }

        if (Input.GetKeyDown(KeyCode.G)) {
            print(inventory.itemSlots[0].item);
        }
    }
}

For a bit more prefacing I have a capsule object with the Player script on it, an empty with the Inventory script on it, which is then attached to the Player script (I'm not sure if I want to make the inventory a scriptable object which is why I've done this), and then lastly I have a cube object with the Accessory script on it.

So, when I press E and pick up the item it gets added into the player's inventory and then destroyed from the scene. Then, when I press G to display that item in the inventory the console just says null. Not Null, which is what an actual null would show up as, but the string "null". If I use visual studio's debugger and have a look at what the accessory's base is, it also says null, but for some reason if I then try and print the accessory's name then that works fine, even though that variable is defined in the Item class.

If I instead do this in the Inventory class:

public void AddItem(ItemSlot slot) {
    ItemSlot[0] = slot;
    print(ItemSlot[0].item);
}

It works fine and prints Item (Accessory) in the console. Even if I print it right after I destroy target in the Player class, that also prints Item (Accessory), so I have no idea why it doesn't work on the next block of code.

Sorry this is so long and maybe an easy fix, but I'm lost.

Edit: I think everything should be fixed now.


texts:
4X games (That is, Xpand, Xplore, Xploit and Xterminate) like Civilization, Sins of a Solar Empire, and other top Strategy games, all seem to have the same addictive hook. I'd like to know what elements these developers incorporate into their games to make them:

Well paced (You can't beat the game in 5 minutes, but it wont take a week)
Replayable (The first game isn't your last)
Competetive (The AI doesn't play like a 3 year old)
Not repetetive (Such as using the same strategy over and over, or spamming units)
Economical (Not having 7 trillion metal and coins after 10 minutes of play)
Not to much micro-managing
Exciting (Necessary?) combat
You stil need to use strategy
Intuitive interfaces (Civilization 5 is a good example)
And any other important parts to the Strategy/4X genre

Some of these seem pretty simple, but others look like balancing acts, and I'd like to have some opinions on how to make a game that is fun to play. I'd be grateful if anyone could answer tell me how you or another game\developer has managed to successfully balance them together.


texts: how to keep display tick rate steady when using continuous collision detection?

texts:
(I've just found about this forum). I hope it is ok to repost my question again here. I posted this question at stackoverflow, but it looks like I might get better help here.

Here is the question:

I've implemented basic particles motion simulation with continuous collision detection.

But there is small issue in display.

Assume simple case of circles moving inside square. All elastic collisions. no firction. All motion is constant speed. No forces are involved, no gravity. So when a particle is moving, it is always moving at constant speed (in between collisions)

What I do now is this:

Let the simulation time step be 1 second (for example). This is the time step simulation is advanced before displaying the new state (unless there is a collision sooner than this).

At start of each time step, time for the next collision between any particles or a particle with a wall is determined. Call this the TOC time; let’s say TOC was .5 seconds in this case.

Since TOC is smaller than the standard time step, then the system is moved by TOC and the new system is displayed so that the new display shows any collisions as just taking place (say 2 circles just touched each other’s, or a circle just touched a wall)

Next, the collision(s) are resolved (i.e. speeds updated, changed directions etc..).

A new step is started. The same thing happens. Now assume there is no collision detected within the next 1 second (those 2 circles above will not be in collision any more, even though they are still touching, due to their speeds showing they are moving apart now), Hence, simulation time is advanced now by the full one second, the standard time step, and particles are moved on the screen using 1 second simulation time and new display is shown.

You see what has just happened: One frame ran for .5 seconds, but the next frame runs for 1 second, may be the 3rd frame is displayed after 2 seconds, may be the 4th frame is displayed after 2.8 seconds (because TOC was .8 seconds then) and so on.

What happens is that the motion of a particle on the screen appears to speed up or slow down, even though it is moving at constant speed and was not even involved in a collision.

i.e. Looking at one particle on its own, I see it suddenly speeding up or slowing down, becuase another particle had hit a wall.

This is because the display tick is not uniform. i.e. the frame rate update is changing, giving the false illusion that a particle is moving at non-constant speed while in fact it is moving at constant speed. The motion on the screen is not smooth, since the screen is not updating at constant rate.

I am not able to figure how to fix this. If I want to show 2 particles at the moment of the collision, I must draw the screen at different times. Drawing the screen always at the same tick interval, results in seeing 2 particles before the collision, and then after the collision, and not just when they colliding, which looked bad when I tried it.

So, how do real games handle this issue? How to display things in order to show collisions when it happen, yet keep the display tick constant? These 2 requirements seem to contradict each other’s.


texts: 'CoreMinimal.h' file not found when building on Unreal Engine on Mac

texts:
I'm trying out C++ on Unreal Engine 4.25 on Mac. If relevant, my Xcode version is 12. When I try to compile, there's an error: 'CoreMinimal.h' file not found.
I've looked around and some solutions mention a workaround, which is to add the path to CoreMinimal.h into the .vscode/c_cpp_properties.json file. I did that:
...
    "includePath": [
        "${workspaceFolder}/**",
        "/Users/Shared/Epic Games/UE_4.25/Engine/**" // This is the filepath to CoreMinimal.h
    ],
...

I still get the same error. I couldn't find any other solution. Has someone found a solution to this?
Thanks.


texts:
I would like to make an enemy walk randomly around a map I have made and if the player is in his zone of sight the enemy to change state to attacking/following. So how would I accomplish something like this? Currently I have no idea how I would generate random paths with collision avoidance.

EDIT: I am making a 3D Game.


texts: Collision Detection: Simulation Inexplicably Slowing Down/How To Efficiently Calculate Extremes In Each Dimension

texts:
BACKGROUND: As discussed here: Fast 2D collision detection in an unbounded space I am working on a collision detection algorithm for a simulation.  The catch that makes this case unique is that the objects in the simulation could all be in a very small area (e.g. 1000x1000) or in a very large area (e.g. 9 bil x 10 bil). Moreover, changes like this could occur very rapidly because of high object velocities, so I needed a somewhat sophisticated algorithm to deal with this situation.  In the end, I went with quadtrees (http://en.wikipedia.org/wiki/Quadtree).  When I finished writing the quadtree class and determined that it was functioning correctly, I uploaded it into my simulation.

THE PROBLEM: At first, the quadtree worked wonderfully.  I was just testing it out for the first time, so instead of feeding it updated bounds every time step of the objects with the least x value/greatest x value/least y value/greatest y value, I just fed is a large area that I knew would be good enough for the test case (10 mil x 10 mil).

In a test involving 1600 objects, my simulation ran almost four times faster than the brute force solution of checking every object against itself!  (about 28 fps instead of 7 fps) Wonderful!  I then proceeded to feed the quadtree the updated "bounds" of the simulation by finding the min/max x/y each frame (this is where the problem begins).  After updating each object's position, I simply checked to see if it was the new min/max extreme in each dimension:

    double tempradius = (*getMoveableEntityVector()[n]).Retradius();
    double tempx = (*getMoveableEntityVector()[n]).Retxpos();
    double tempy = (*getMoveableEntityVector()[n]).Retypos();

    if (n == 0) { //if it's the first object initialize the variables based off it
        minx = tempx - tempradius;
        maxx = tempx + tempradius;
        miny = tempy - tempradius;
        maxy = tempy + tempradius;
    }
    else { //all other objects
        if (minx > tempx - tempradius) { //if this object has the lowest x value
            minx = tempx - tempradius;
        }
        else if (maxx < tempx + tempradius) { //if has the highest x value
            maxx = tempx + tempradius;
        }

        if (miny > tempy - tempradius) { //if has lowest y value
            miny = tempy - tempradius;
        }
        else if (maxy < tempy + tempradius) { //if has highest y value
            maxy = tempy + tempradius;
        }
    }

Running through this simple code a mere 1600 times per time step slowed the simulation back down below the speed of my original brute force implementation! (about 7 fps)

WHY THIS DOESN'T MAKE SENSE TO ME: The original brute force implementation had to run through the relatively computationally intense distance formula (http://math.about.com/library/bldistance.htm) about 1600*1600 times per time step, or more exactly, 1600*1599/2 = 1,279,200 times per time step. I would think running through the above code once would be about as computationally intensive as doing the distance formula once.  How is going through the above code only 1,600 times costing me as much processor time as going through the distance formula more than a million times?!?

EDIT: The question is not directly about the quadtree; it is about the code above that finds the objects with the least/greatest x/y coordinates. (This code feeds its calcuations to the quadtree so the quadtree knows where to start, but it is definitely not quadtree code). The quadtree code ran quite fast until I added the above helper code. The only reason I mentioned the quadtree and the background to this issue is because the quadtree/background stuff gives context on why I think that this code should be going much faster (1000 comparable checks vs 1,000,000!)

TLDR (TOO LONG DIDN'T READ):  Check out the code above.  Is there something making it take up WAY more (about 1000x more!) processor time than I think it should be taking?

Thanks in advance for the time and help!


texts: Carve river beds into existing 3d procedural generated terrain

texts:
Ok, I've read many threads around about procedural terrain generation with rivers and roads but they suggest approaches from zero to result.

I'd like to know if exists an algorithm to apply to an existing vertex structure which models it by adding rivers beds like cuts through the slope of a mountain for instance.

This approach should:

not work on heightmaps, since my terrain is not generated with
heightmaps
modify the surface with randomness
according to the heights (river sources should be higher and the flow should descend)
be as realistic as possible (like not too many circular paths)

I have no needs for speedy algorithms. would be enought to have a separated algorithm to modify the surface so that I am not forced to do all the work during the creation of the terrain.

I tagged this question with c# because this project is written in c# using xna4.0 and in the case that someone knows any algorithms in different languages, c# is preferred (ye, this is optimism)

By the way, I'm looking forward to see if someone knows anything that could fit these needs


texts: How can I change the rotatearound radius in real time when the game is running?

texts:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TargetBehaviour : MonoBehaviour
{
    // Add this script to Cube(2)
    [Header("Add your turret")]
    public GameObject Turret;//to get the position in worldspace to which this gameObject will rotate around.

    [Header("The axis by which it will rotate around")]
    public Vector3 axis;//by which axis it will rotate. x,y or z.

    [Header("Angle covered per update")]
    public float angle; //or the speed of rotation.

    public float upperLimit, lowerLimit, delay;// upperLimit & lowerLimit: heighest & lowest height;
    private float height, prevHeight, time;//height:height it is trying to reach(randomly generated); prevHeight:stores last value of height;delay in radomness;

    [Range(0, 50)]
    public float xradius = 5;
    [Range(0, 50)]
    public float yradius = 5;

    private void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        //Gets the position of your 'Turret' and rotates this gameObject around it by the 'axis' provided at speed 'angle' in degrees per update
        transform.RotateAround(Turret.transform.position, axis.normalized, angle);
        time += Time.deltaTime;
        //Sets value of 'height' randomly within 'upperLimit' & 'lowerLimit' after delay
        if (time > delay)
        {
            prevHeight = height;
            height = Random.Range(lowerLimit, upperLimit);
            time = 0;
        }
        //Mathf.Lerp changes height from 'prevHeight' to 'height' gradually (smooth transition)
        transform.position = new Vector3(transform.position.x, Mathf.Lerp(prevHeight, height, time), transform.position.z);
    }
}

Using the xradius and yradius sliders I want to change the transform.RotateAround radius in real time.

UPDATE:

I added this to the Update:

if (radius > 0)
        {
            var newPos = (transform.position - Turret.transform.position).normalized * radius;
            newPos += Turret.transform.position;
            transform.position = newPos;
        }

The problem is now that some times when the radius the distance from the Turret is small for example 20 or less some times the transform is getting right above the turret not sure why. I want it to rotate around the turret at the fixed set distance(radius) but not to be above the turret. Can't figure out why sometimes it's moving right above the turret then after some time it's getting back to the set distance.


texts:
How do I add collision between two player controlled turtles. I asked the question before but misunderstood my own groundings on the plan. I cannot figure out how to make two player controlled turtles in the game to hit each other and end the game. This is what I have so far:
import turtle
import pygame
import math
import string

wn = turtle.Screen()
wn.bgcolor("black")

Write Tron

text=turtle.Pen()
text.pencolor("aqua")
text.hideturtle()
text.penup()
text.setposition(150, 300)
text.write("TRON", font=("system", 30))

Draw border

mypen = turtle.Turtle()
mypen.penup()
mypen.pencolor('white')
mypen.setposition(-300,-300)
mypen.pendown()
mypen.pensize(3)
for side in range (4):
    mypen.forward(600)
    mypen.left(90)
mypen.hideturtle()

pygame.display.update

Create player 1

player = turtle.Turtle()
player.setposition(240,240)
player.setheading(180)
player.color("red")
player.shape("triangle")

player.speed(0)

Create player 2

player2 = turtle.Turtle()
player2.setposition(-240,-240)
player2.color("aqua")
player2.shape("triangle")
player2.position()
player2.speed(0)

Set speed variable

speed = 3

Define functions

def turnleft():
    player.left(30)

def turnright():
    player.right(30)

def increasespeed():
    global speed
    speed += 3

Set keyboard bindings for p1ayer 1

turtle.listen()
turtle.onkey(turnleft,"Left")
turtle.onkey(turnright,"Right")

Define player 2 functions

def turnleft():
    player2.left(30)

def turnright():
    player2.right(30)

def increasespeed():
    global speed
    speed += 3

Set keyboard bindings for player 2

turtle.listen()
turtle.onkey(turnleft,"a")
turtle.onkey(turnright,"d")
turtle.onkey(turnleft,"A")
turtle.onkey(turnright,"D")

turtle.onkey(increasespeed,"Up")

while True:
    player.forward(speed)
    player2.forward(speed)

#Bouandary
if player.xcor() > 300 or player.xcor() < -300:
    print("GAME OVER")
    quit()
#Boundary
if player.ycor() > 300 or player.ycor() < -300:
    print("GAME OVER")
    quit()
#Bouandary2
if player2.xcor() > 300 or player2.xcor() < -300:
    print("GAME OVER")
    quit()
#Boundary2
if player2.ycor() > 300 or player2.ycor() < -300:
    print("GAME OVER")
    quit()

#Collision

while True:
  if player.setposition(player.ycor()+10, player.xcor()+10) and player2.setposition(player2.xcor()+10, player2.ycor()+10):
      quit


texts: pre-rendering light on texture based on bump map

texts:
Using a gray-scale bump-map and N sources of colored light, what is the algorithm to render the light on the textured surface, assuming I have the angle(s) and distance of each light source? (I am pre-rendering in software).

I have the part where it renders light based on the position and angle of light source.
My question is twofold:

How do I decide on an RGB color based on multiple different light sources? Is it simply additive by nature?
What do I do about cases where the angle is not a sufficient way to determine intensity? For instance when there is a deep caveat in the surface and a higher elevated area is blocking the light to that lower shaded area? How do you handle something like that?


texts: OpenGL 2.0 - How to swap buffers for color picking

texts:
I'm trying to reproduce color picking on iOS, following the technique described here: http://www.lighthouse3d.com/opengl/picking/index.php3?openglway2, with OpenGL ES 2.0.

When the user touches the screen, I need to draw the objects on a buffer different from the one displayed on the screen, which seems to be done by glRenderMode(GL_SELECT); how could i do the same with OpenGL ES 2.0?

Should I create a support buffer as described here?
https://developer.apple.com/library/ios/documentation/3DDrawing/Conceptual/OpenGLES_ProgrammingGuide/WorkingwithEAGLContexts/WorkingwithEAGLContexts.html#//apple_ref/doc/uid/TP40008793-CH103-SW6

Thanks for any suggestion,

DAN


texts:
so I'm working on a mobile game where I have touch input from a Asset from the asset store. It all works perfectly fine, except for one thing:
I want to implement a "drag and drop" feature so when I pick up an Item it should follow to the position of my finger. But because the playground is a sphere, I have to do the movement with a Raycast. So my plan is that the item should follow the Raycasts position. My current attempt looks like this:

public void DragTo(float screenX, float screenY)
{
    if (draggingObject == null)
    {
        return;
    }

    Debug.Log("Dragging");

    //Converts the screen space to world space
    Vector3 mousePosFar = new Vector3(screenX, screenY,      Camera.main.farClipPlane);
    Vector3 mousePosNear = new Vector3(screenX, screenY, Camera.main.nearClipPlane);

    Vector3 mousePosF = mainCam.ScreenToWorldPoint(mousePosFar);
    Vector3 mousePosN = mainCam.ScreenToWorldPoint(mousePosNear);

    //shoots an ray to the world space
    RaycastHit hit;

    if (Physics.Raycast(mousePosN, mousePosF - mousePosN, out hit))
    {
        float step = speed * Time.deltaTime;
        draggingObject.GetComponent<Rigidbody>().MovePosition(hit.point);
    }
}

I already have tried the following options:

draggingObject.GetComponent<Rigidbody>().MovePosition(hit.point);
draggingObject.GetComponent<Rigidbody>().MovePosition(hit.normal);
draggingObject.transform.position = hit.point;
draggingObject.transform.position = normal;

They all work, but they all have really buggy and strange behaviors.
Also when I dont freeze the z. axis on the Rigidbody the item just "flies" up on the z axis, until it reaches the camera. Then it teleportes again down and it all starts again. So its flying up on the ray.
So if you have any Ideas why this happens let me know.
Any help is appreciated.
(Also dont forget that its all happens on a sphere)

UPDATE:
It works now. When the dragging began i changed the layer from the object to "Ignore Raycast" and when it end changed it back to "Default".


texts:
I'd like to apply a simple few masks to few images.

The first mask I'd like to implement is mask like:

XXXOOO

I mean, that on the right everything is masked (to black), and on the left everything is stayed without changes.

The second mask I'd like to implement is glow mask. I mean something like this:

    O
  O***O
 O**X**O
  O***O
    O

What I mean, is a circle mask, which in the center everything is saved without changes, and going outside the circle everything is starting to be black

The last mask is irregular mask. For example like this:

  OOO*
 O**X**O
  OO**OO**O
    OO*X*O
      O*O
       O

Where:
O - to black
* - to gray
X - without changes

I've read, how to apply distortion pixel shader in XNA: msdn

Could you explain me how to apply mute mask on an image? (mask will be grayscale)


texts: Is it legal to publish a game that uses a youtube tutorials code?

texts:
I am working on my noughts and crosses game, and I am following a youtube tutorial,
It is helping me write the Java code.
I am wondering I could to publish it to the website itch.io legally.
The game would be free.
Thankyou.


texts: How do I smooth out of the effects of a too-sensitive control?

texts: I have a game that takes input from a joystick. If you tilt the joystick right, the ship moves right linearly according to how much the joystick is tilted. So if you tilt the joystick twice as much the ship tilts twice as much. This feels fine in cases when you want to bank the ship through a steep turn (ie. lots of tilt). But for small tilts, the controls feel far too sensitive. How do game devs flatten/smooth the effects of controls? Do I just take the log of the tilt? Mostly, I want to flatten things in the middle of the range of possible tilts.


texts: Using Smartphone as a steering wheel on Linux

texts:
I am making a car simulation game, however, I find it being inefficient and difficult to test the simulation realism and accuracy via keyboard or even joystick control. I need a steering wheel controller to do this. However, getting good steering wheel controllers is so difficult - they cost a lot. However, I noticed(when playing Real Racing 3) that the phone actually can handle such task kinda well.

What sort of code could I write to use a smart phone as a steering wheel?

Looking forward to see some useful answers ;)


texts: Drawing sprites messes up my model in XNA4

texts:
I have a model which draws correctly in XNA4.

However if I try to add a background image (or any sprite), the rendering of my model is messed up. There are two problems with the rendering

model is partially transparent
hidden surfaces are visible.

 Above is the 'problem' rendering (the cyan coloured cockpit cover is visible through the bottom of the ship)

 This is how the rendering should look


texts: A panel to change 3d object properties when right click on it (Unity)

texts:
I'm building a UI system to edit selected 3D objects. I have spheres on the screen and I want to be able to edit their proprieties (radius for example). In order to do that I want the user to be able to click on a sphere and then it show a panel next to the object. When the user changes slider value the radius of the sphere which as been clicked on change. Using the new unity event system, I think it's easy to achieve, but I'm a new to unity and even if I know the basic I don't know how to organize this properly.

At the end my goal would be to select multiple sphere, right click and edit the radius to all selected spheres. http://imgur.com/WgBCrmk Any tips on how to do that ? Sorry for my poor english. Thanks


texts: Export baked lightmaps from Unity to Monogame

texts:
I'm trying to bake lightmaps in Unity, export as textures and apply the textures in Monogame. Is this the right path to go? If so, how it should be done?

Thank you.


texts: Unity 3D - Game is fine in "play" but when built, player moves diagonal up+left

texts:
So I just completed the first "Roll-a-ball" tutorial, but when I run the build, the game ball races to the Upper-Left corner even when I don't press any buttons.

I did the obvious stuff (reboot, build again...) but it still does it for the PC stand-alone build, and not when I play directly from Unity.

My code doesn't seem to be different from the tutorial (see link above).  Here's the input handling code inside of the "PlayerController.cs":

    void FixedUpdate()
    {
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

 Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);

 rb.AddForce (movement * speed);
    }

Then I added statements to print the Horizontal and Vertical. When inside the IDE and I play it, they're zero, and when I press an arrow key, they move from 0 to 1 floating point in about a second. In the built stand-alone, Horiz is -1, Vert is 1.

void SetCountText ()
{
    countText.text =
        "Count: " + count.ToString () + "\n" +
        "Horizontal: " + Input.GetAxis("Horizontal").ToString() + "\n" +
        "Vertical:" + Input.GetAxis("Vertical").ToString()
        ;
    if (count >= 12) {
        winText.text = "YOU WIN!!";
    }
}


texts: How do I calculate the exit vectors of colliding projectiles?

texts:
I'm trying to create projectiles which bounce/ricochet off one another when they collide in mid-air.

All projectiles are spherical and have identical size, mass, and speed.  Each has two vectors: one representing its current location and the other its direction and speed.  (Vectors, here, basically being <x,y,z> tuples.)  The distance/direction between the two projectiles can easily be calculated as a fifth vector.

In my head, I envision the ricochet as reflecting each projectile's velocity off of a plane perpendicular to the line between the two projectiles, but Googling for "vector reflection" and the like just gets me pages full of math I don't know how to translate into code.  :-)

How can I model this collision?  I'm not worried about real-world factors like drag, friction, or gravity — simple reflection is enough.

static void ricochet(Projectile projectile1, Projectile projectile2) {
    Vector position1 = projectile1.position;
    Vector position2 = projectile2.position;

    Vector direction1 = projectile1.direction;
    Vector direction2 = projectile2.direction;

    Vector distance = new Vector(position1).subtract(position2);

    Vector reflection1 = new Vector();
    Vector reflection2 = new Vector();

    // MAGIC!

    projectile1.direction = reflection1;
    projectile2.direction = reflection2;
}


texts:
I'd like to have a Waveform in my iPhone game that I am developing using Cocos2d v2.0.

That's the ideal wave I'd like to achieve. A simpler wave which I would still be happy with is this one.

Some people suggested me to use ParticleEffects ands ParticleDesigners like 71squared but I am not sure that this is the right approach.

Brainstorming, I think that at the end a wave is a plot of some function, and at each frame translate the wave points that where from the origin apart (-x and +x) and computes new wave points for the origin.

Something like this:

for (duration of effect)
compute wave point intensity at origin and display it
and
for each wave point before the center translate to -x and display it
and after the center translate to +x and display it

Let me know what you think and if you have any better solution. I was thinking to achieve the display point by colouring a particular pixel but I need to figure out how :)..


texts:
My settings.json (generated with JsonUtility.ToJson):

{
    "masterVolume": 0.10000000149011612,
    "fullScreenMode": 1,
    "cheatsEnabled": false
}

Offending line:

SettingsData sd = JsonUtility.FromJson<SettingsData>(Application.dataPath + "/Settings/settings.json");

My SettingsData-class.

[System.Serializable]
public class SettingsData
{
    [SerializeField]public float masterVolume;
    [SerializeField]public int fullScreenMode;
    [SerializeField]public bool cheatsEnabled;

    public SettingsData(float masterVolume, FullScreenMode fullScreenMode, bool cheatsEnabled)
    {
        this.masterVolume = masterVolume;
        this.fullScreenMode = (int)fullScreenMode;
        this.cheatsEnabled = cheatsEnabled;
    }
}

I really can't fathom why it's having trouble reading this back in, I even tried to save the enum as an int instead, but still no luck.


texts: Add singleton to an existing gameobject in Unity via script

texts:
I did notice that if I assign scripts that generate singleton classes (for my managers), to an empty game object, everything works fine.

Now I would like to start the scene with the empty game object, attach the main game manager singleton, and in the game manager singleton I would like to attach to it the other manager singleton classes.

Although I am not sure how you actually do so. Do you run addComponent to the main game manager, and they will be attached to the existing gameobject?

The gameobject that I use for the main gamemanager is set to not be destroyed on load; the doubt is if I should run addComponent on the scripts, or create a reference from the gamemanager script and instantiate it from there.

I did look for examples on the subject, but the only thing that I found is the reference to add a script to a game object; and I am not sure if that's actually what is supposed to be done.


texts: Unity - Where should downloaded level data be stored?

texts:
I've been looking around and it appears suggestions are only to store data to UserPrefs, or PersistentDataPath.

I intend to have map files streamed to the client on demand, and saved for reuse. UserPrefs seems inappropriate for large blobs. PersistentDataPath is per computer user, thus duplicating data and space usage. I believe Program Files has access restrictions too.

What are the current best practices for storing runtime data that meet the following criteria?

Is shared across user accounts to avoid wasting disk space.
Doesn't require elevated permissions.
Doesn't annoy the user (such as data being placed in My Documents).
Can be modified at any time.


texts: (Unreal) Creating 3D tiles (cubes) for the scenery of a 2.5D rpg (similar to Pokemon Gen IV and V)

texts:
I developed a concept for a college class and I think it has enough potential to actually become a game. The visuals will be similar to games like Pokémon Black and Octopath Traveler as in the characters are 2D pixelated sprites travelling through a 3D world with a fixed top down camera. I already made the character blueprint (the movement and camera position) in Unreal and it's working close to what it's intended but now I'm having trouble making the scenery!

I would love to learn a pratical way to make a "blocky" world that fits the 2D pixelated sprites aesthetic. Even better, a way to make 3d tiles that make that my Paper2D char will travel only in 4 directions and from tile to tile (identical to old DS pokémon games).

I have a lead from the Octopath dev's presentation where they show this custom tool to place blocks in the world (GIF bellow) but i have yet to find a way to develop something similar. I thought of Minecraft and how it has a blocky world where the player can place the blocks in it but I don't know if that's quite it.

Octopath MapEditor GIF


texts: Android ndk-build can't find glm headers

texts:
I am trying to port some boilerplate code of mine to work on android, using the android ndk & NativeActivity

So far I have just one file that defines the glue between android and my code and it works fine. It includes one GLIncludes file, that sorts out the includes based on platform

However, if I add glm headers to the GLIncludes file, becoming:

#ifdef __ANDROID_API__
    #include <EGL/egl.h>
    #include <GLES/gl.h>
    #include <GLES/glext.h>
#endif

#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "glm/gtc/type_ptr.hpp"

ndk-build then complains about not finding glm.hpp:

In file included from jni/src/GLIncludes.h:41:0,
                 from jni/androidLauncher.cpp:4:
jni/src/glm/glm.hpp:86:18: fatal error: limits: No such file or directory

I have verified that the file does indeed lie at < ANDROID_PROJECT_ROOT >/jni/src/glm/glm.hpp so what could be the problem?

Here is my Android.mk file that sits in the jni folder:

LOCAL_PATH:= $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := libglobes
LOCAL_CFLAGS    := -Werror
LOCAL_LDLIBS    := -llog -lGLESv1_CM -lEGL -lm -landroid
LOCAL_CPP_EXTENSION := .cpp
LOCAL_STATIC_LIBRARIES := android_native_app_glue

LOCAL_SRC_FILES := androidLauncher.cpp

include $(BUILD_SHARED_LIBRARY)

$(call import-module,android/native_app_glue)

My directory structure is:

< ROOT >
    src/ (dir with all sources in it)
        GLIncludes.h
        glm/
            glm.hpp
    android/ (base dir for android port)
        jni/
            androidLauncher.cpp
            Android.mk
            src/ (symbolic link to upper src folder with same contents)

So why is the ndk-build not seeing the glm.hpp files? Is it because it is too deep? or is it because of the symbolic link? Or is it something else completely?

Thanks


texts:
I have a multiplayer game written in C# and we've recently been creating a lot of content but have been looking for a way to give our entities customization logic that the designers can hook into. I took a look at this post. With something like this in mind (using C# as a scripting language); I have a few questions.

Would one embed the script itself in the entity object before persisting to it to the disk? Is this okay?

Would I compile once per scripting then - this seems like a lot of overhead to store all these compiled Assemblies to execute.

Any general advice on how to do thigns is welcome, too. These entities are generated on the fly inside the editor and could be composed of a lot of different things.


texts:
When I launched my game on my iPad, the screen first displayed a faulty splash image with a black lower half momentarily, before displaying the normal splash image.

No matter what I tried, I couldn't get rid of this faulty 'pre-splash image'. I have tried the following:

Entered my Plus package serial number and updated my seat in Unity.
Deleted and left all splash images blank in Unity.
Checked all the LaunchScreen-XXX.png images in Xcode.
Checked the files referenced by Images.xcassets in Xcode.
Changed all the above images to a completely black image. Still, the old faulty picture would appear.
Cleared all the data and installation files on my iPad.
Deleted General > Launch Images Source.

I wonder where Xcode kept the faulty image.

I am using Unity 5.5.1 and Xcode 9.2.

Could someone please help?


texts: Camera Movement - Snap Camera back to origin in relation to the player object

texts:
I am trying to implement camera movement like it is done in Guild Wars 2. Scenario is when A and D keys are pressed, the player rotates right / left and the camera follows and stays behind the character / player like this
(Starts at 23 seconds)
https://www.youtube.com/watch?v=XkHJ2uSrLjE

I can get the basic working fine, and I did it this way

private void KeysRotateCameraAndPlayer()
{
    float keysOrbitingSpeed = 120;
    this.player = GameObject.FindWithTag("Player").transform;

    if (Input.GetKey(KeyCode.A))
    {
        Debug.Log("Rotate Left");
        CenterPoint.eulerAngles -= new Vector3(0, 360 + Time.deltaTime * keysOrbitingSpeed, 0);
        player.eulerAngles -= new Vector3(0, 360 + Time.deltaTime * keysOrbitingSpeed, 0);

    }
    else if (Input.GetKey(KeyCode.D))
    {
        Debug.Log("Rotate Right");
        CenterPoint.eulerAngles += new Vector3(0, 360 + Time.deltaTime * keysOrbitingSpeed, 0);
        player.eulerAngles += new Vector3(0, 360 + Time.deltaTime * keysOrbitingSpeed, 0);
    }
}

Now the next part I am trying to achieve , when the camera is rotated / orbited around the player using the mouse and is left in a position that is not the origin i.e behind the player (in relation to player)… when A and D keys are pressed, what happens in GW2 is the camera seems to snap back to the origin and then continue to follow the player from the back ( or its relation origin with regards to the player Object if that makes sense)

This is what the game does (which I hope to achieve)
https://www.youtube.com/watch?v=qTTDaeuHl80

so at present moment with my current code
https://www.youtube.com/watch?v=a53lZ_0BDtg
camera and player will continue to rotate (with A and D), from where the camera was last left during orbit. How can I add to this, to force the camera to snap back to origin like they have in Guild Wars 2?


texts: LOVE Physics - Breaking Joint Chains (LUA / Box2D)

texts:
Wasn't sure whether to post here or on SO so please move if needed.

I've been having a look into the box2D physics API provided by LOVE to try and create a swinging flail or weighted rope but I'm having some trouble keeping the jointed elements close together.

So far I've made a series of circular bodies and linked them together using revolute joints with the first element being static and the final element being slightly larger/heavier to act as a weight.

The code to generate each link is as follows:

    for i = 1, segments, 1 do

        link = {}

        if (i == 1) then
            link.body = love.physics.newBody(world, xpos, ypos, "static") --Starting link
        else
            link.body = love.physics.newBody(world, xpos, ypos, "dynamic")
        end

        if (i == segments) then
            link.shape = love.physics.newCircleShape(endlink_radius) --Ending link
        else
            link.shape = love.physics.newCircleShape(link_radius)
        end

        link.fixture = love.physics.newFixture(link.body, link.shape) --Fix bodies to shapes

        table.insert(chain,link)

        ypos = ypos + link_distance --Place next link further down, keeping x position

    end

And the code to join each link:

    for i = 2, #chain, 1 do

        x1,y1 = chain[i-1].body:getPosition() --First link position
        x2,y2 = chain[i].body:getPosition() --Second link position
        chain[i-1].join = love.physics.newRevoluteJoint(chain[i-1].body, chain[i].body, x1, y1, x2, y2, false ) --Join the two with a revolute joint

    end

And this works quite well, producing a chain like this:

The next step is to move the chain, I'm currently moving the first static element and having it "drag" the rest of the links along with it using the following code:

    position = vo.add(position, velocity) --Vector addition add velocity to current position to get new position
    chain[1].body:setPosition(position.x, position.y) --Update the first link position

This works fine for slow speeds (chain currently moves towards mouse cursor) but any rapid movement causes everything to fall apart.

Is there anyway to easily keep the elements close together?

I've tried adjusting the weights and world gravity but couldn't see any difference, I've also thought about applying a force to each element when the first one moves but that doesn't seem quite right.

Thanks

Solution (Thanks to NauticalMile)

Change the previous position update:

    position = vo.add(position, velocity) --Vector addition add velocity to current position to get new position
    chain[1].body:setPosition(position.x, position.y) --Update the first link position

To a velocity update and have Box2D handle the movement:

    chain[1].body:setLinearVelocity(velocity.x, velocity.y)


texts: Best strategy when player left the online multiplayer game

texts:
I have developed a online multiplayer HTML5 card game. This game can be played by four players.

Now I am having this confusion on what to do when a player left the game in the middle.

Possible strategies

If player left the game intentionally(like pressing 'quit' button)

Notify other players about this event and stop the game(This will be hated by other players as they have invested their time in this round of game)
Notify other players about this event and assign bot to the position of this player. Penalize the player who left the game.(I think, this step will also decrease interest level of other players about the idea of playing with the bot)

If player left the game unintentionally due to network glitch and he may reconnect to game.

Wait for that player indefinitely(not a good strategy)
Wait for that player for finite duration, if he/she is not reconnected then kick out that player and assign bot in his/her place.

Also, from technical point of view, it will difficult to know on server end that if player left due to network issue or simply he close his browser(or switch off his network)

Any suggestion on how I can handle this scenario ?


texts: Why, after calling SetVideoMode as in the following, does nothing appear on my screen?

texts:
I am trying to create an application that will need to use double buffering (for purpose of vsync). I am using SDL.NET. From what I understood, in order to have double buffering, I have to SetVideoMode with the opengl paremeter set to true.

Here's the code I'm using:

        Video.Initialize();

        Video.GLSetAttribute(OpenGLAttr.DoubleBuffer, 1);
        Video.GLSetAttribute(OpenGLAttr.SwapControl, 1);
        Video.GLSetAttribute(OpenGLAttr.RedSize, 8);
        Video.GLSetAttribute(OpenGLAttr.GreenSize, 8);
        Video.GLSetAttribute(OpenGLAttr.BlueSize, 8);
        Video.GLSetAttribute(OpenGLAttr.DepthSize, 16);

        Video.SetVideoMode(VideoInfo.ScreenWidth, VideoInfo.ScreenHeight, false, true, true, true);

If 4th parameter (bool opengl) is false, it works: a new fullscreen window is created and displayed (but I assume the OpenGLAttr's set above are meaningless in this case).

If 4th parameter is true, nothing happens. A new window gets created (at least, it appears in the list of open windows) but I cannot alt-tab into it and nothing appears on the screen.

What am I doing wrong?


texts: What should be the code design for interactions management in a game with lots of object?

texts:
I'm writing a 2d game for Android in Java using LibGDX. The game consists many interactions between different types of objects. Most of them happen between enemies and bullets. At the beginning, I needed to check every moment if any enemy collide any bullet (if their masks overlaps each other). The code for checking overlap is clear to me. My question is how should I make the interactions be checked between everyone every moment?

What I did is creating a class called InteractionsManager which takes the array of all enemies and the array of bullets and checking in every step collision between each other (if collision happens, it calls the object's onCollision(Object object) method).

My problem got bigger when I needed to check other interactions types (like if enemy is in a specific distance from other type of object and other stuff like that).

I thought about passing to each object the InteractionsManager object and it should tell it whatever interaction it needs.


texts: What's the best open source physics engine to use with JOGL?

texts:
I have a past with jbullet but the existing jogl compatible sources and demos seems uncompleted. I have managed to implement it to an extent but still looking for a better documented engine with more demo applications.

My answer to this question is currently JBullet but wondering if there are any better and easier solutions.

Any ideas & suggestions?


texts:
Let's take for example that in our game, we divide our world (1000x1000 tiles) into chunks of 100x100 tiles. Each chunk contains its own npcs, traps, players, items, whatever. Now, there comes to my mind many problems:

Pathfinding: what if an npc at one chunk needs to find a player/npc that is near him but not in the same chunk?
Sight: Npc wants to check if someone is near him, what if the nearest npc/player is like the previous example at other chunk.

I'd like to find a solution where the player doesnt have to see how chunks are loaded and interaction between chunks is possible, but seems hard.

EDIT: what i have in mind is a multiplayer rpg (not as big as a mmo), where the map is divided into chunks. Each chunk would represent maybe a settlement, a portion of a forest, a portion of a hill, etc ... I thought about loading not just the chunk being visited by a player, but its surroundings, so transitions are easier.

I need this organization because i'll have many entities to manage. Maybe in the world map exists 100 cities, and each one contains 10 citizens. If a chunk is visited by a player, i want him to see how each citizen talk, and walk, and live. But a chunk not being visited should be handle differently. Maybe i'll do some checks when the night comes to see what happened there.


texts: Is there any term for reverse gamification?

texts:
Gamification is a process of applying game mechanics to non-game contexts.

Reverse gamification is a process of using non-game context or non-game mechanics in games.

For example:

Gamification - you can learn traffic code with leaderboards, badges, etc.

Reverse gamification - you can create a game (something like gta) to teach traffic code inside it.

Is there any better term for that?


texts: Access a clone of an instantiated object - not all the clones?

texts:
I am trying to access the object I instantiate - basically a prefab car instantiates cars (one after one) ..the problem that when try to move one .. they all move together ... what's the best way to separate them (and control them one after one)

the game is about parking .. the first car appear i choose which line to move to (target = empty-object) , then the second car appears and i choose which line also to move (the problem is here : when i hit the left/right-row all the cars go left and right .. i want only the last one to change the line )!! Any Ideas ... Thank You:)

this in Spawn.cs

public void SpawnCars()
{
    if (spawnAllowed)
    {
        // choose a random strat point 1/6
        randomSpawnPoint = Random.Range(0, spawnPoints.Length);
        // choose a random car 1/6
        randomSpawnCars = Random.Range(0, Cars.Length);
        // clone randomly a car(1/6) from a random pre_set-points(1/6)
        GameObject obj = Instantiate(Cars[randomSpawnCars], spawnPoints[randomSpawnPoint].position, Quaternion.Euler(-90, 180, 0)) as GameObject;
        // carNumber will count how many cloned car
        carNumber++;
        // destroy the  cloned car after N sec
       // Destroy(obj, 8);
        // every cloned car will take a tag with it
        obj.gameObject.tag = "select" + k;
        k++;
        rcf = obj.GetComponent<RayCastForward>();

    }
}

this in CarController.cs
changing line problem (it change all the cars line)

void ChangeLine()
{
     if (Input.GetKeyDown(KeyCode.RightArrow))
    {
        f.RayDis();
        if (f.v != "R6")
            {
                tf.transform.position = new Vector3(tf.position.x,tf.position.y,tf.position.z - 6.5f);
            }
    }
    else if (Input.GetKeyDown(KeyCode.LeftArrow))
    {
        f.RayDis();
        if (f.v != "R1")
            {
                tf.transform.position = new Vector3(tf.position.x, tf.position.y, tf.position.z + 6.5f);
            }
    }

the car will move to target after i click the UpRow key

// move the car to (target)
public void MoveCars(string go)
{
        target = GameObject.Find(go);
        directionToTarget = (target.transform.position - transform.position).normalized;
        rb.velocity = new Vector3(directionToTarget.x * moveSpeed, directionToTarget.y * moveSpeed, directionToTarget.z * moveSpeed);
}


texts: How to prevent cube intersecting with other objects when moved around with mouse?

texts:
I want to allow the player to freely place cubes anywhere they like in 3D space, but the cube being moved around is not allowed to intersect with other objects.

Currently I do a ray cast based on where the mouse is (ScreenPointToRay), and position the cube at the hit point.  This allows me to move the cube around, but it's possible to intersect other objects if the raycast hit is right next to an object.

I see that there is a Physics.BoxCast method, but I can't get this working based on where the mouse position is.  Am not sure if this is even the best solution.

I was thinking of ray casting out from each 4 points of each face on the cube (4 up, 4 down, 4 right, 4 left, 4 forward, 4 back), but I feel this is a lot of raycasts just to prevent intersecting on movement and placement for a cube.

How can I prevent a cube that is being moved around, and then placed with the mouse from intersecting other objects?


texts:
How to create a splash (loading) screen in cocos2d for Android?

I need a loading screen that shows my app name and after that the next scene will show automatically.

Thanks


texts:
Here is a snippet of code from Quake I.
    LARGE_INTEGER   PerformanceFreq;
    unsigned int    lowpart, highpart;
    OSVERSIONINFO   vinfo;

    if (!QueryPerformanceFrequency (&PerformanceFreq))
        Sys_Error ("No hardware timer available");

    // get 32 out of the 64 time bits such that we have around 1 microsecond resolution
    lowpart = (unsigned int)PerformanceFreq.LowPart;
    highpart = (unsigned int)PerformanceFreq.HighPart;
    lowshift = 0;

    while (highpart || (lowpart > 2000000.0))
    {
        lowshift++;
        lowpart >>= 1;
        lowpart |= (highpart & 1) << 31;
        highpart >>= 1;
    }

The comment indicates that they are reducing the 64 bit PerformanceFreq to 32 bits and that the resolution is about 1 microsecond (the default resolution of QueryPerformanceFrequency is 1 second).
I understand what the code is doing generally, but I don't know what (lowpart > 2000000.0) is meant to be doing or why it's there. I think it's related to ensuring the resolution is about 1 microsecond.
When I run this code through the debugger the lowpart is shifted 3 times meaning that the resolution is actually 1s / 2^3 - 0.125s or 125 milliseconds and not 1 microsecond. The documentation for QueryPerformanceFrequency says that the result is hardware dependent so I don't see how a constant value 200000.0 could work unless you were making an assumption for the result based on modern hardware of the time.
Is this code wrong about the resolution or am I missing something?


texts: Most effective way to manage a gamestate system that is easy to use?

texts:
I just started working on my game, mostly the game management. I plan and using game-states to make the menu's and other stuff easier.

My main idea for implementing the game-states is creating a game object and passing it as a reference to classes which control the current state, then storing the game-state classes via references inside a vector.
My main concern is that is this the better way to do it? Or should I implement it differently? Also, when you do use game states, where does the game loop go? Does it go inside a state such as gamePlaying or is it put somewhere else?

Hopefully someone can clear this up for me, thank you!


texts: Using transform.position on an instantiated prefab in an array one by one

texts:
So I've been trying to make an already instantiated prefab to fall one by one in my scene. First they instantiate hidden in the camera and that works so far. But when I apply transform.position on them they don't seem to move. Here's the code

   public GameObject[] enemySpawn;

void Start()
{
    for (int i = 0; i < enemySpawn.Length; i++)
    {
        Instantiate<GameObject>(enemySpawn[i], new Vector2(-4,6),Quaternion.identity);

    }

    StartCoroutine(spawnBlades());
}

void Update()
{

}
IEnumerator spawnBlades() {
for(int i = 0; i<6; i++ )
        enemySpawn[i].transform.position = new Vector3(Random.Range(-3, 3), 6);
    yield return new WaitForSeconds(0.5f);

}


texts: Move background with the player location

texts:
I want to move background with  player location in ios . I have implemented the infinite parallax background by using the CCParallax class but i don't need it. I want to do something similar to this game http://www.youtube.com/watch?v=fNRNlLzrKmc.

my game level is large want to parallax up when player will move up. How will i do that please explain me. will i have to use CCCamera or i can do this by using CCParallax class.

Thanks,


texts: rough texturing on edges of mechanical parts

texts: How do major studios fake the effect of "wear & tear" on the edges of guns and other things? I've always wondered this, but today it got to the point where I figured, why not just ask you guys. I"ve tried painting a greyscale mask, where the edges show a rough concretelike texture (Painted white and use lerp in ue4) but for some reason I feel like There is something im missing. Then, today I noticed sometihng playing BO3 - the edges seemed to have some more specularity on guns. Is this my answer? What process would you go through to show roughed edges? What goes into that effect?


texts: How to calculate new direction after sprite collision

texts:
The scenario as you can see in the picture. A ball will be hitting a surface and I want to fairly correctly get the new angle after the collision..

I expect to know the X,Y coordinates of the lines breaking points (The picture below would has 6 lines)

Secondly, if the ball would have a rotation - Is there a standard way of compensate for a "screewed" ball?


texts: Combine diffuse map and lightmap into one texture file

texts:
Working with Unity, I'd like to do some more memory optimization. Currently, my 3D models have a diffuse texture and a lightmap, both at the same resolution and compression.

I was wondering if there was a way (possibly via Photoshop) by which I can "bake" the lightmap into the diffuse texture to produce the same effect as in-engine.

Thanks!


texts: LibGDX - How to do more things asynchronously

texts:
Most documentation only mentions how to load assets asynchronously, eg with code similar to

private void render(float delta){
  if (assetManager.update()){
     // ** HERE ** //
     game.setScreen(new MainGameScreen(game));
  } else {
    progress = assetManager.getProgress();
  }

  // draw progress bar or whatever
}

but what if, as part of game initialization, I have to do other things before switching to the main game screen (marked with ** HERE ** in the above code)? Sure, the user is still seeing the splash screen, but what if I wanted to do these things in background as well, and give some sign of progress (another progress bar, or whatever). I haven't found examples of similar things (or perhaps I haven't looked hard enough).


texts: Is this the correct implementation of a fixed timestep game loop?

texts:
public static void main(String[] args) {

        long newTime, delta, timeSince1Second, startTime, oldTime;
        long ticks = 0;
        double frameCap = 1000/60;
        double time_passed = 0;

        startTime = System.currentTimeMillis();
        oldTime = System.currentTimeMillis();
        while(true)
        {
            newTime = System.currentTimeMillis();
            delta = newTime - oldTime;
            timeSince1Second = newTime - startTime;
            currentTime = newTime;

            //update game based on dynamic time step here (if needed)

            //update loop (fixed time step)
            while(time_passed >= frameCap)
            {
                //update game logic (fixed time step update)
                time_passed = time_passed - frameCap; //resetting time_passed essentially to 0
                ticks++;
            }

            time_passed = time_passed + (double) delta; //time passed since start of loop

            //render here

            //frame rate counter
            if((timeSince1Second/1000) >= 1)
            {
                System.out.println(ticks+" frames per second");
                startTime = System.currentTimeMillis();
                ticks = 0;
            }
        }
} //end main function

This code has been written in java. I'd like to know if i'm missing anything here, because in the fixed time step update loop, if i display for example a window, and move the window around, the framerate will sometimes change until i stop moving the window around, which is kind of confusing to me. Is that normal? Or perhaps I might be missing something
Guidance will be appreciated


texts: Unity animations not transitioning properly

texts:
I am currently trying to animate transitions between four different directions. I have four total animations for walking, and another four for the idle state. I cannot seem to figure out why when I try to transition from a walking state to another walking state in a different direction (not the direction I am idling in) it must wait for the walking animation to finish, and then play the walking animation in the new direction.

You can see my sprite begin to walk forward, and then when I attempt to turn south the animation it continually plays the north animation until the animation is finished. What I am trying to achieve is a smooth transition that switches immediately.

I know very little about animating and much more about programming. My list of attempted solutions is very short, and limited to only changing the length of each animation.


texts: How to create a character animation where the parts of the sprite change?

texts:
Let's say I'm creating a game (in Java or C++). In this game I have a character that can do a sword swing animation, but the character can equip different swords.

Do I have to make an animation for each individual sword, or is there another way? I Like if a character can equip different armors, do I create a new sprite for each armor, or is there a way to have, say a base character that can perform all the animations with different swords and can have different armors on the same image?


texts: Displaying a Text component for every wave and then disabling it

texts:
I want to display the wave number before every incoming wave of enemies. And after displaying this it should hide the text component. I tried to get this done with StartCoroutine() and Ienumerator but that does not seem to work as it runs only once. As in Wave 1 is displayed and nothing after wards.

Below is the script I am using for this:

public class WaveUpdateTextScript : MonoBehaviour
{

    [SerializeField]
    WaveSpawner spawner;

    private WaveSpawner.SpawnState currentState;
    private Text waveDisplay;

    // Use this for initialization
    void Start()
    {
        waveDisplay = GetComponent<Text>();

        StartCoroutine(WaveDisplaySwitch());

    }

    IEnumerator WaveDisplaySwitch()
    {

        switch (spawner.NextWave)
        {
            case 1:
                waveDisplay.text = "Wave 1 of 8 !!";
                yield return new WaitForSeconds(4f);
                gameObject.SetActive(false);
                break;
            case 2:
                gameObject.SetActive(true);
                waveDisplay.text = "Wave 2 of 8 !!";
                yield return new WaitForSeconds(4f);
                gameObject.SetActive(false);
                break;
            case 3:
                gameObject.SetActive(true);
                waveDisplay.text = "Wave 3 of 8 !!";
                yield return new WaitForSeconds(4f);
                gameObject.SetActive(false);
                break;
            default:
                Debug.Log("This be the meh wave...");
                break;
        }

    }
}

I know whats going on, on start() the coroutine is started once and then case 1 of switch works and then stops at break.

How would I solve this? or is this not the best way of achieving the desired result?


texts: Pong - Changing the Ball's Y location depending on where it hits the paddle

texts:
I'm making my first game in, Pong, and I'm trying to make the ball's Y increase or decrease, depending on where it impacts the paddle. After implementing the code below, the ball only goes down, but not up. What could the problem be?

if(paddle.detectCollison(ball)){
    //30px on either side of the actual center of the paddle is considered the center
    if((ball.getY() > ((paddle.getH() / 2) + 30)))
        ball.setY(ball.getY() + 10);
    else if ((ball.getY() < ((paddle.getH() /2) - 30)))
        ball.setY(ball.getY() - 10);
    ball.setDX(-(ball.getDX()));
}


texts:
I understand that the following math topics are required for 3D graphics programming. I have started doing some of them in my math course. Can someone point me in the direction of a resource that explains how they apply? What graphics/game problems are they used to solve?

vector math
matrix math
quaternions
linear algebra

As far as I can see these are all linear algebra/matrix topics. Are there any other topics required?


texts: Is there a random command for Boolean variables in Unity C#

texts:
Can you randomly choose a Boolean's value in Unity C#. I tried random.range, but it only works with floats. Here is an example of what I'm trying to do:

Boolean = (random boolean value command)(false, true);
if(Boolean = true){
    Debug.Log("It's true!")
} else{
    Debug.Log("It's false!")
}

Any ideas?


texts: How to correctly synchronize a shared surface?

texts:
I am trying to share a direct3d9 surface between two processes. One process (let's call it A) writes to the surface, and the other (B) displays it on screen. Currently, process A does a StretchRect of its rendering surface to a shared surface, and then sets a flag in shared system memory to tell B that it's done. When B sees the flag, it then does a StretchRect of the shared surface to its own display surface. Process B then sets the flag again to tell A it is done.
It seems however that after the StretchRect on the shared surface returns, the texture has not necessarily finished copying, because sometimes Process B gets the previous picture, or sometimes even there is tearing (i.e. one half of picture N + one half of picture N + 1).
As I understand it, Direct3D is largely asynchronous under the hood, and does not ensure synchronisation between processes. I therefore need to ensure by myself that Process A has finished copying before displaying in process B, and vice-versa. Am I correct in my interpretation of the situation, and how would I achieve this? I am experimenting with LockRect() but I'm not sure if that's optimal or even guaranteed to work.
From MSDN documentation:

Shared cross-process surfaces provide no synchronization mechanism.
Read/write changes to a shared surface may not reflect a referencing
process's view of the surface when expected. To provide
synchronization, use event queries or lock the texture.
Only the
process that initially creates a shared resource can lock it (any
process that opens a reference to that shared resource cannot lock
it).


texts:
I finally got my GPU skinning to work! (Mostly) I'm using MD5 format and this here tutorial

However the weird part is that I'm getting EXACTLY the same issue as this unanswered post: here

The animations are opposite. When the head is supposed to be rotation left/right it rotates up/down and the arm when it goes up seems to look like the vertices invert (backface culling proves it since i can see through the mesh and see the inside of the arm)

Any clues the what might be causing this? Questions?


texts: DirectX How to Gernerate Vertices for Diamond Shape and Render it?

texts:
How to generate vertices for 3D Diamond Shape in DirectX?

EDIT:
I am creating an application which receive DIAMETER, CROWN, GIRDLE and PAVILION as parameter and render a model of diamond according to parameters.

Refer to the image:


texts: Unity - How to move a ship realistically to a point in a 2D top-down game

texts:
i'm trying to move a sailing ship to the point where i clicked with the mouse.
this movement should be realistic (oar at the back where the ship moves around)
so if the mouse click is left and in front of the ship the ship should afterwards move there with a curvy path in order to have the right rotation

i'd be glad if someone could help me with this issue
thank


texts:
I've written a script which will automatically generate a Mesh, assign a MeshFilter, MeshRenderer, BoxCollider, and RigidBody.

This script is meant as a tool to rapidly create a certain class of objects (in this case, dice). I don't want them to actually generate at runtime.

Is there a way to convert the GameObject to a Prefab with all of its different generated properties so that I can simply drop them into my game?

Just trying to drag it into the Assets causes it to lose its Mesh. Also to note, I have it so I can generate the Mesh via the Inspector in a ContextMenu, which works well.


texts: Resolve Unity error about "Constructors and field initializers" on the loading thread

texts:
The code below is producing an error message I don't understand:

  Constructors and field initializers will be executed from the loading
  thread when loading a scene. Don't use this function in the
  constructor or field initializers, instead move initialization code to
  the Awake or Start function

I don't know where the problem is in my code or what I need to change - can someone please explain?

var XPos : float = transform.position.x;
var YPos : float = transform.position.y;
var ZPos : float = transform.position.z;
var Waiting : float = 0.02;

function OnTriggerEnter (col : Collider) {
    if (col.gameObject.tag == "Player") {
        this.transform.position = Vector3(XPos, YPos+0.1, ZPos);
        yield WaitForSeconds(Waiting);
        // ...similar code omitted
        transform.GetComponent.<Collider>().isTrigger = true;
        Destroy(gameObject);
    }
}


texts: Can I make color data not render as gradient?

texts: I would like for the color between my vertices to not be rendered as a gradient, but as a hard break. Is there any way to accomplish this in OpenGL/GLSL?


texts: How do I apply a texture over a material in OpenGL ES?

texts:
How can I apply a texture over a material?

I've set up an object with the following material:

GLKBaseEffect *effect;
effect.colorMaterialEnabled = false;
effect.material.ambientColor = GLKVector4Make(251.0/255.0, 95.0/255.0, 96.0/255.0, 1.0);
effect.material.diffuseColor = GLKVector4Make(251.0/255.0, 95.0/255.0, 96.0/255.0, 1.0);

and it is correctly rendered with a pink color.

However, when I apply a texture with:

GLKTextureInfo * info = [GLKTextureLoader textureWithCGImage:...];
effect.texture2d0.name = info.name;
effect.texture2d0.enabled = true;

the material seems to disappear and I just see the texture; the object is transparent where the texture is not visible, instead of being pink.

Here's an example:

The texture is created with the following code:

- (UIImage*)generateTexturefromText:(NSString*)text {
    NSError *error;

    UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
    myLabel.text = text;
    myLabel.font = [UIFont fontWithName:"Helvetica" size:50];
    myLabel.textAlignment = NSTextAlignmentLeft;
    myLabel.textColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:1];
    myLabel.backgroundColor = [UIColor clearColor];
    myLabel.numberOfLines = -1;
    myLabel.lineBreakMode = NSLineBreakByCharWrapping;

    UIGraphicsBeginImageContextWithOptions(myLabel.bounds.size, NO, 1.0);
    CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0, 0);
    CGContextScaleCTM(UIGraphicsGetCurrentContext(), 1.0, 1.0);
    [myLabel.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *layerImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    if (error) {
        NSLog(" Error loading texture from image: %",error);
        return nil;
    }

    return layerImage;
}

Why is no color visible where the texture is transparent?


texts: So I have some experience programming in Java, and at the moment I am learning how to use Python.  I have read on the process of game design and such. I also have media covered, got experience with graphics and audio.  My question is geared more towards the actual tools to use for making games, developing.  I am willing to commit to a long term development cycle, as I will be doing this as a hobby.  I've heard of Flash, Gamemaker, etc.  I don't intend to create my own Game Engine, so I was looking for a platform that is extensible and easy to program with an OOP mind frame.  As a plus it would be great of said game could be played directly from a website.  TIA!


texts: How to obtain a camera stream from Unity without rendering it to the player's screen?

texts:
I'd like to stream the output of two cameras to a separate process. Right now, it looks like the best way to do that is to grab the rendered camera views from the screen via platform specific screen capture hooks then compress them real time with h.264. Is there a way to grab the input of the cameras within unity and avoid rendering them to the screen?

One solution I'm considering involves using Unity's multiplayer capability to run the game on a separate machine and grab it from that screen buffer, unbeknownst to the player.


texts: What is the best collision detection method or algorithm for a 2d platformer?

texts:
I'm working of a 2d platformer.
It's a preety simple game, but the ground is flat and it looks boring. I did the collision detection for it and it's all working when the boxes are axis aligned, but I want to add slopes so it's more interesting. I researched a lot and I found the separating axis theorem but I read that it is not good for platformers because it's not side specific. So, my question is: what is the best way to detect collision with curves and slopes? I use javascript if you want to provide some code.
Thanks in advance!


texts: Determine the direction of force when ball is moved through pipes

texts:
I have set of pipes(edge colliders) in my scene, through which I pass the ball.

     ____|  |  <---Edge colliders
   o _______|

How do I move the ball in upward direction. For above this pipe I have to move along the positive x direction first, then positive y direction. How can I detect that.?

mRigidBody.AddForce (new Vector2 (moveSpeed,moveSpeed));

I tried this, but this can be used to move one direction at a time


texts: Is using two languages in a game engine a good idea?

texts:
I'm thinking about making a game engine, as a learning project.

I know Java the best, and I figure most of the code is not going to be running that much of the time, given the 20/80 rule. Why not write most of it in a language I know? For the part that has to be really fast, like the renderer, I was thinking of writing that in native code.

Is this approach of using two languages a good idea, or a terrible one?


texts:
I'm looking for a 2D graphics engine that would allow me to release to Windows, Mac and the iPhone, much the way Unity does for 3D.

Is there a good engine that does this and is specific to 2D?


texts: How do you implement input handling in a C game engine?

texts: I am starting to learn C programming, though I have a lot of experience using higher-level languages. I want to write a game engine using C and OpenGL. I think I understand the graphics rendering part, but now I'm curious about how to receive and process keyboard, mouse and controller input. How does one implement this sort of thing in C?


texts:
I'm making a 2D, top down MMO game. ATM I can connect a player to a server and they get the map data from a DB. They can move around and hit some stuff and if they move near a viewport edge, the server sends new data etc.

Even a few players can do this, but since I don't have an, lets call it, "update manager" which tells the players where they are and the DB that the map has been altered. It's just a read only game at the moment.

My idea is, to tell the server where a player is and how big his viewport is. Then if any other player is in this viewport, the server will distribute the updates to each other player.

So I wouldn't have to tell the whole world what's going on.

The problem, however, is the ping.

If I have a ping of ~300ms, every other player would probably "jump" over the map, and not move smoothly. I could keep this synchronized with vector clocks, but it would still lag.

Also, how to keep the players from cheating? All ideas I got, don't really work. The only "safe" thing seems to be to calculate the game on the server and client, then throw away all data when the calculations are wrong. But this seems rather excessive to me.

--- Edit ---

Ok, I had some ideas after I read the comments.

I will send an absolute state to the server for ever game entity I have. This state object will consist  of the position, orientation, speed and an "action", which can be anything someone can do.
I'm gonna keep the clients seperated in "small" arrays, each representing a area of the map. So I can calculate which client is near or in my viewport and needs to get my information.
I have to find out if it's possible to get a timestamp of the request, to use it for sanity checking, so no player can send me actions from an invalid time-range to get his actions evaluated before the other players.
Only only updates from other clients and errors from the server get sent to the client, if everything is ok the server just takes the informations.


texts:
I am using cocos2D-x and am trying to achieve the effect of enemies going past and shooting projectiles at the player who is moving around the screen. I am using the code below, which is based on this article (Scroll down to the ’Shooting Projectiles’ section): https://www.raywenderlich.com/95835/cocos2d-x-tutorial-beginners

Point projPos = shooter->getPosition();
projectile->setPosition(projPos);
projectile->setVisible(true);

Vec2 offset = target->getPosition() - projPos;
offset.normalize();

auto shootAmt = offset * 1000;
auto projEndPt = shootAmt + projPos;

// Approach 1.
auto moveAct = MoveBy::create(10.0f, shootAmt);

// Approach 2.
auto moveAct = MoveTo::create(10.0f, projEndPt);

projectile->runAction(moveAct);

It works most of the time, however the projectiles speed varies, it seems based on the distance between the player and shooter. At medium distances the speed is fine, at shorter distances the speed is too slow and at longer distances the speed is too fast. The time being fixed (10.0f) over a variable distances seems to be the cause. I have tried both approaches as commented in the code, moving by move amount (Approach 1) and move to point (Approach 2) and both seem to give the same result.


texts:
I've heard countless times about the pitfalls of Singletons / globals, and I understand why they're so often frowned upon.

What I don't understand is what the elegant, non-messy alternative is.  It seems that the alternative to using Singletons/globals always involves passing objects a million levels down through your engine objects until they reach the objects that need them.

For example, in my game, I preload some assets when the game starts up.  These assets aren't used until much later when the player navigates through the main menu and enters the game.  Am I supposed to pass this data from my Game object, to my ScreenManager object (despite the fact that only one Screen actually cares about this data), then to the appropriate Screen object, and anywhere else?

It just seems that I'm trading global state data for cluttered dependency injection, passing data to objects that don't even care about the data except for the purpose of passing it on to child objects.

Is this a case where a Singleton would be a good thing, or is there some elegant solution I'm missing?


texts: Why does my character slide off of the platform if I'm using MovePosition, but not if I'm setting transform.position

texts:
I have a platform which consists of a box collider, a rigidbody2d and a script which moves the platform through waypoints.
I also have a Rigidbody2d character which can move around and jump.
One of the most common solutions I've found for having the character stay on a moving platform is by parenting it to the platform while the player is on it and removing the platform parent when the player jumps/walks off.
    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag(Tags.Player))
        {
            other.transform.SetParent(platform);
        }
    }

    private void OnTriggerExit2D(Collider2D other)
    {
        if (other.CompareTag(Tags.Player))
        {
            other.transform.SetParent(null);
        }
    }

I have noticed that this method works only if the platform is moved by setting the transform.position directly and if I use Rigidbody2D.MovePosition my character still slides off.
Why is that, and what would be proper way of having my character stay on the platform if the platform is moved by MovePosition?


texts:
I'm a beginner in Unity and i'm facing a little problem / question.
The main purpose of my 2D game is based on the mouvment of a specific light and the player have to avoid getting inside his rays. My actual game got different type of layers :

Z = -5 : A front light (don't pay attention of this one)
Z = 0 : The main scene, where the player move and interact with collider (2D based, player is a sprite with rigidbody2d and circlecollider2d
Z = 1 : Some elements to avoid the light to go through and give the player a chance to hide
Z = 10 : The main light that the player have to avoid

My problem is the following one, i don't know how to interact a Point Light (so a 3d object) and a sprite (2D). I tried to do some "OnTriggerEnter / Stay" in the Point Light but it never trigger.
I heard about "Raycast" but i prefer to ask some solution before learning this.
If anyone can give me tips, it would be very good :)

Thanks !

[EDIT SOLUTION, THANKS TO Géry Arduino]

#pragma strict

public var moon : Component;

function Start () {

}

function Update () {
var radiusMoon = moon.transform.light.range;
var zMoon = moon.transform.position.z;
var zPlayer = transform.position.z;
if(zMoon - radiusMoon <= zPlayer) {
    var zDirection = transform.position.z - zMoon;
    var xDirection = transform.position.x - moon.transform.position.x;
    var yDirection = transform.position.y - moon.transform.position.y;
    var direction = Vector3(xDirection, yDirection, zDirection);
    Debug.DrawRay(moon.transform.position, direction, Color.red, 10);
    if(Physics.Raycast(moon.transform.position, direction, radiusMoon)) {
        Debug.Log("there is something between me and the object....");
    }
    else {
        Debug.Log("i'm free");
    }
}
}


texts: Models loaded with Assimp have messed up UVs/normals

texts:
I've been trying to use Assimp to load models and so far I got it to load a few obj models, but all of them have messed up UVs (and maybe normals).

Here's what it looks like :

I tried several combinations of Assimp's loading flags, but to no avail.

Here are the used flags :

const aiScene* scene = importer.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs|aiProcess_GenSmoothNormals|aiProcess_ImproveCacheLocality|aiProcess_FixInfacingNormals|aiProcess_FindDegenerates|aiProcess_FindInvalidData|aiProcess_GenUVCoords|aiProcess_TransformUVCoords);

I'm only loading already triangulated (with Blender) obj models with no submeshes.

Thanks in advance for any help.


texts:
I have a set of planar polygons in 3D space defined by their vertices in counterclockwise order. Let's define the 'positive face' as being the face of the 3D polygon such as when observed, the vertices appear in counterclockwise order, and the 'negative face', the face which when observed, the vertices appear in clockwise order.

I'm doing perspective projection of the set of polygons onto a projection polygon defined by the points in this order: (0, h, 0), (0, 0, 0), (w, 0, 0), and (w, h, 0), where w and h are strictly positive integers. The positive face of this projection polygon is oriented towards positive Z, and the camera point is somewhere at (0, 0, d), where d is a strictly negative number.

In order to 'clip' the projected polygons into the projection polygon, I'm applying the Greiner-Hormann (PDF) clipping algorithm, which requires that the clipper and the to-be-clipped polygons be in the same order (i.e. clockwise or counterclockwise).

My question is the following:

How can I determine whether the projected face of the 3D polygon is the negative or the positive one? Meaning, how do I find out if I have to work with the vertices in normal or inverted order for the algorithm to work?

I noticed that only if the 3D polygon is facing the projection polygon with its negative face, both of them are in the same order (counterclockwise), otherwise, a modification needs to be done.

Here is a picture that illustrates this:

Note that the planes described by the polygon from the set and the projection polygon may not always be parallel.


texts: Libgdx: Am I abusing Vector2? Is there a better way to do my position updates and rendering?

texts:
I'm simulating hair in a game.  Currently I have a HairField object, which has a position defined by a Vector2.  Each HairField has multiple Hair objects in a list, each with a position defined by a Vector2.  Each hair has multiple HairParticle objects in a list, each with a Vector2 position.  Like so:

HairField class
    Vector2 pos;  //  In world coords
    List<Hair> hairs;

Hair class
    HairField hairField;
    Vector2 pos;  //  Relative to parent HairField
    List<HairParticle> hairParticles;

    public Vector2 getWorldPos() {
        return pos.cpy().add(hairField.getWorldPos());
    }

HairParticle class
    Hair hair;
    HairParticle parent;
    Vector2 pos;  //  Relative to parent HairParticle

    public Vector2 getWorldPos() {
        return pos.cpy().add(hair.getWorldPos());
    }

My hair physics/rendering loop looks like the following:

for each (Hair h : hairField):
    HairParticle parent = null;
    for each (HairParticle p : h):
        if (parent==null) continue;
        //  get position info from each HairParticle's getWorldPos()
        //  update p, constraining to certain distance from parent
        //  render line from parent --> p

You can see that I'm calling a metric buttload of getWorldPos() methods on the particles, all so I can have information for updating/rendering the particle.  Each of these calls involves multiple Vector2.cpy() calls and some vector math.

My question is, am I abusing Vector2's?  They make for easy math, but I'm wondering if there's some more primitive (but faster) way I should be doing things.  I've heard about transformation matrices, but don't know much about them yet (been reading).  Does Libgdx expose some quicker way to be doing this math for updating/rendering that I should be using instead?


texts:
I am creating an implementation of Snakes and ladders
and I run into some issues.The game is updating too fast and I want to limit the framerate kinda,or make a pause so that the move is actually visible.I tried using Thread.sleep() but that created issues of its own.Have you solved any similar problems that could point me to the right direction?
I have to point out that run method is in an abstract class and my actual game extends this abstract class

This is the game loop :

public void run() {
    init();
    this.requestFocus();
    long lastTime = System.nanoTime();
    double amountOfTicks = 60.0;
    double ns = 1000000000 / amountOfTicks;
    double delta = 0;
    long timer = System.currentTimeMillis();
    int updates = 0;
    int frames = 0;
    while (running) {
      long now = System.nanoTime();
      delta = delta + (now - lastTime) / ns;
      lastTime = now;
      while (delta >= 1) {
        update();
        updates++;
        delta--;
      }
      render();
      frames++;
      if (System.currentTimeMillis() - timer > 1000) {
        timer = timer + 1000;
        if (this.FPSLOG)
          System.out.println("FPS: " + frames + " " + "Ticks: " + updates);
        frames = 0;
        updates = 0;
      }
    }
    stop();
  }

The render method :

private void render() {
    BufferStrategy bs = this.getBufferStrategy();
    if (bs == null) {
      this.createBufferStrategy(3);
      return;
    }
    Graphics g = bs.getDrawGraphics();
    g.setColor(background);
    g.fillRect(0, 0, getWidth(), getHeight());
    draw(g);
    g.dispose();
    bs.show();
  }

The game implementation of those methods:

@Override
    public void init() {
        setBackground(Color.black);
        board = new Board();
        player = new Player(Color.cyan,board.getTiles()[0]);
        dice = new Random();
    }

    @Override
    public void draw(Graphics g) {
        board.draw(g);
        player.draw(g);
    }

    @Override
    public void update() {
        for (int i = 0; i < dice.nextInt(7)+1; i++) {
            player.move();
        }
    }

public void move(){
        this.currentTile = this.currentTile.getNext() == null ? this.currentTile : this.currentTile.getNext();
        this.xPos = this.currentTile.getxPos();
        this.yPos = this.currentTile.getyPos();
    }


texts: Is using Box2D for simulating gravity "in space" a good idea?

texts:
I'm attempting to write a simulation of a solar system of planets in 2D space that are attracted to each other through Newton's law of universal gravitation.

I know that it is possible to simulate this in Box2D by applying forces between each body in the system each frame, however I've read that Box2D is tuned for objects between 0.1m and 10m - In my simulation I want to be able to simulate the motion of large and small bodies (e.g. planets and artificial satelites).

When such large scales are involved is using Box2D (or an alternative 2D physics engine) to simulate the gravity between bodies in this way a good idea (I know I can scale the system, e.g. so that the sun has a diameter of 10m), or am I better off doing this myself?


texts: Cinemachine third person camera movement causes misalignment

texts:
I'm working on third person movement using CinemachineFreeLook as the player camera. At first I thought it was working fine but I've noticed that moving left/right actually moves the character with a curve instead of straight left/right. This behavior can be observed in the following video: https://imgur.com/sLGIia8
As you can see when trying to make the character move left/right the character doesn't stay on the grid but instead curves a bit to the left/right.
I'm inclined to believe that this occurs because of cinemachine camera but I am unsure what exactly is going on and how to fix this. I feel that this is a bit over my head and am thus asking for help in figuring this out.
The simplest form of movement code is as follows (the exact code that moves the character in the video)
private void FixedUpdate()
{
    Vector2 input = playerInput.MoveInput;

    bool hasInput = Mathf.Abs(input.x) > float.Epsilon || Mathf.Abs(input.y) > float.Epsilon;
    if (hasInput)
    {
        // get camera direction
        Transform cameraTransform = Camera.main.transform;
        Vector3 cameraForward = cameraTransform.forward;
        Vector3 cameraDirection = Vector3.Scale(cameraForward, Vector3.right + Vector3.forward);

        // transform camera direction vector to a quaternion
        Quaternion cameraRotation = Quaternion.LookRotation(cameraDirection);

        // transform input vector2 into x/z vector3
        Vector3 inputDirection = new Vector3(input.x, 0f, input.y);

        // create desired velocity from input and current camera rotation
        Vector3 desiredVelocity = cameraRotation * inputDirection * settings.Speed;
        Vector3 delta = desiredVelocity - body.velocity;
        delta.y = 0f;
        Vector3 acceleration = delta / Time.deltaTime;

        if (acceleration.sqrMagnitude > settings.SqrMaxAcceleration)
        {
            acceleration = acceleration.normalized * settings.MaxAcceleration;
        }

        body.AddForce(acceleration, ForceMode.Acceleration);
    }
}


texts: How do I detect collisions between a point and a sloped line?

texts:
The character in my game constantly falls due to gravity, so i have to detect the collision between the bottom point of the character and the tile slope line on the same x coordinate.

The character must stop just on the slope floor. for that i also need to define where is the slope by storing x, y of both ends of the slope.

In the image bellow, you see a 32x32 tile map, origin of each image is top left.

playerPointX = 420;
leftSlopeX = 13*tileSize;
leftSlopeY = 11*tileSize;
rightSlopeX = leftSlopeX+tileSize;
rightSlopeY = leftSlopeY+tileSize;

so regarding the awnser i should write this ?

float run = playerPointX - leftSlopeX;
float rise = 1 * run;
float collisionHeight = leftSlopeY + rise;

and how i can detect the collision against collisionHeight ?

if (playerX<collisionHeight) // collision detected

or

if (playerY>collisionHeight) // collision detected

Finally when the collision will be detected should i use y=mx+b for playerY displacement ?


texts: I was told that I should create a map editor, instead of hard coding out all the grids of my map. It sounds like a fun project and would make things easier in the long run, but I wouldn't even know where to start with it. It would be pretty simple, 3 cube types, a 1000x1000 grid, and the ability to stack cubes on top of each other. Exporting the map into something I can use in my game would be an issue though. Also creating the UI for the editor would be something completely new to me. Are there any links out there that can help with this?