texts: 2D planetary system simulation- how to improve gravity model? How to control simulation speed?

texts:
I'm making a simple planetary system simulator. I've run into some problems with physics model and simulation speed and I'd like to learn how to fix them.

My main class is Body:

public abstract class Body {

private double x, y; // position
private double w, h; // dimensions for drawing
private double vx = 0, vy = 0; //velocities along x, y axes
private double ax = 0, ay = 0; // accelerations along x, y axes
private double mass = 1;        //default = 1
private boolean stationary = false; //stationary body is centered during simulation

...
}

Then, in this class, the method I'm using to calculate the force of gravity. I decided to have another body as a parameter, so when I call the method it updates both of the bodies. If that's not the best way to do it, please tell me. I also know that using "this" inside a public method is not necessary, but it makes the code more clear for me.

public void interact(Body b2) {
    double x = calculateDistX(b2);
    double y = calculateDistY(b2);
    double r = calculateDistance(x, y);

    double f = (this.getMass() * b2.getMass()) / Math.pow(r, 2); // gravitational
                                                                    // force

    double fx = f * (x / r); // x component of the force - f times cosine of
                                // the angle
    double fy = f * (y / r); // x component of the force - f times sine of
                                // the angle

    /* calculate accelerations for both bodies, set vector orientation */
    if (b2.getX() > this.getX()) {
        this.setAx(fx / this.getMass());
        b2.setAx(-fx / b2.getMass());
    } else {
        this.setAx(-fx / this.getMass());
        b2.setAx(fx / b2.getMass());
    }

    if (b2.getY() > this.getY()) {
        this.setAy(fy / this.getMass());
        b2.setAy(-fy / b2.getMass());
    } else {
        this.setAy(-fy / this.getMass());
        b2.setAy(fy / b2.getMass());
    }

    /* calculate velocities for both bodies */
    this.setVx(this.getVx() + this.getAx());
    this.setVy(this.getVy() + this.getAy());

    b2.setVx(b2.getVx() + b2.getAx());
    b2.setVy(b2.getVy() + b2.getAy());

    /* calculate positions for both bodies */
    this.setX(this.getX() + this.getVx());
    this.setY(this.getY() + this.getVy());

    b2.setX(b2.getX() + b2.getVx());
    b2.setY(b2.getY() + b2.getVy());
}

Now, when I run the simulation it tends to blow up when bodies get too close. I will try to implement the Runge-Kutta or Verlet algorithm in the interact() method to change this, but how do I implement timestep? Should there be some timer that counts time and is used to calculate derivatives? Right now I'm using a Timer in my drawing method:

class DrawingPanel extends JPanel {
DrawingPanel() {
    int step = 15; // milliseconds
    ActionListener taskPerformer = new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            repaint();
            }
    };
    new Timer(step, taskPerformer).start();
    Body b0 = new Star();
    addBody(b0);
    Body b1 = new Planet();
    addBody(b1);
    Body b2 = new Planet();
    addBody(b2);
}

List<Body> bodies = new ArrayList<>();

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    bodies.get(2).interact(bodies.get(1));
    bodies.get(0).interact(bodies.get(1));
    bodies.get(0).interact(bodies.get(2));

    for (Body b : bodies) {
        f.draw(b);
    }
}
public void addBody(Body b) {
    bodies.add(b);
}
}

I feel like calling the interact() method in my paintComponent() method is not the right solution, but I don't know how to do it. Also, how to make the simulation slower? Right now changing the "step" to bigger value slows the simulation down, but it ends up being just low FPS, because it's just the separation between two drawing events. How should I implement the timer to control the simulation and preserve its smoothness?


texts: SharpDX - How do I write multiple streams to Texture2D?

texts:
I'm working on a 3D map that is cut as a simple grid of textures. The idea is to draw only one object with all those textures, instead of having a tile object for each of them. Correct me if I'm wrong, but only one big call is preferable to many small calls in terms of speed. Considering that textures loaded and shown are based on the camera view, ideally, it's not such a huge call.

Problem though, I need to put the corresponding textures altogether in a single Texture2D object I can pass to the shader. So I was thinking of having a rendertarget to create this Texture2D, but this beats the purpose of having only one draw call.

So basicaly, what I thought about is to load each texture, get their data and copy all of them in a new ordered Texture2D I can then pass to the object. Only thing is I have no idea on how to do that.

Any sample or suggestions on the matter? Or maybe someone tell me this is terribly wrong.

Thank you!


texts: Do you have to rewrite Corona SDK apps for different devices?

texts: I am using the trial windows edition of Corona, but I want to develop for iOS - the windows version only supports android, so my question is will I have to rewrite any parts of my application for iOS based devices?


texts:
I hate asking questions that are specific to my own code like this, but I've run into a pesky roadblock and could use some help getting around it. I'm coding floating platforms into my game that will allow a player to jump onto them from underneath, but then will not allow players to fall through them once they are on top, which require some custom collision detection code. The code I have written so far isn't working, the character passes through it on the way up, and on the way down, stops for a moment on the platform, and then falls right through it. Here is the code to handle collisions with floating platforms:

protected void HandleFloatingPlatforms(Vector2 moveAmount)
    {
        //if character is traveling downward.
        if (moveAmount.Y > 0)
        {
            Rectangle afterMoveRect = collisionRectangle;
            afterMoveRect.Offset((int)moveAmount.X, (int)moveAmount.Y);
            foreach (World_Objects.GameObject platform in gameplayScreen.Entities)
            {
                if (platform is World_Objects.Inanimate_Objects.FloatingPlatform)
                {
                    //wideProximityArea is just a rectangle surrounding the collision
                    //box of an entity to check for nearby entities.
                    if (wideProximityArea.Intersects(platform.CollisionRectangle) ||
                        wideProximityArea.Contains(platform.CollisionRectangle))
                    {
                        if (afterMoveRect.Intersects(platform.CollisionRectangle))
                        {
                            //This, in my mind would denote that after the character is moved, its feet have fallen below the top of the platform, but before he had moved its feet were above it...
                            if (collisionRectangle.Bottom <= platform.CollisionRectangle.Top)
                            {
                                if (afterMoveRect.Bottom > platform.CollisionRectangle.Top)
                                {
                                    //And then after detecting that he has fallen through the platform, reposition him on top of it...
                                    worldLocation.Y = platform.CollisionRectangle.Y - frameHeight;
                                    hasCollidedVertically = true;

                                }
                            }
                        }
                    }
                }
            }
        }
    }

In case you are curious, the parameter moveAmount is found through this code:

elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

        float totalX = 0;
        float totalY = 0;

        foreach (Vector2 vector in velocities)
        {
            totalX += vector.X;
            totalY += vector.Y;
        }

        velocities.Clear();

        velocity.X = totalX;
        velocity.Y = totalY;

        velocity.Y = Math.Min(velocity.Y, 1000);

        Vector2 moveAmount = velocity * elapsed;


texts: Draw a projection of a mesh on a surface

texts: I have a mesh looking almost like a cylinder, the cylinder goes through a mesh and continues on the other side. What I want to do is to draw the projection of the cylinder on the mesh. So if you look at the images down below. I just want draw the green color on the surface. Any ideas? Im working in opengl.


texts:
From the beginning of development on my game I was hoping to release it as a universal app, but the gameplay simply doesn't work as well on the iPad. Also, it was designed to work on the iPhone screen, and the (even slight) difference in width to height ratio gives iPhone users an advantage over iPad users by seeing more of the path ahead. Not to mention it doesn't look quite right on the larger screen.

Hypothetically, if my game becomes a top seller, would it be a bad idea to have it only an iPhone app? Would it make it far less likely for my app to become viral? My app would still work on the iPad like any other iPhone app, and I plan on eventually releasing an update that supports both iPad and iPhone.


texts: How to reference UnityEditor in external DLL when using UnityVS, successfully?

texts:
So I'm trying to put my scripts and custom inspector editor scripts in two external DLLs and I'm facing a problem on my Editor DLL.
First of, I'm using UnityVS with Visual Studio 2013 Ultimate.

I added a reference to C:\Program Files (x86)\Unity\Editor\Data\Managed\UnityEditor.dll and it successfully shows me IntelliSense and I can access all classes and it's members, too. But when I try to compile the build, it will complain not finding the assembly UnityEditor. Even referencing the same DLL like the UnityProject (inside the Library folder) results in that problem, as it's just a copy of installed UnityEditor.dll.

I even tried to open this project in a separate Visual Studio and build it, got the same result.

I've heard, placing the resulting DLL in the Editor folder will make the custom inspectors available, so I really wish this would compile.


texts: Unity Anti-aliased Edge Shader with Variable Thickness (does not require standard shaders or post processing)

texts:
I'm trying to create a coloring-book effect for an edge shader (not an outline shader) but having some difficulty creating straight line shaders that don't look badly anti-aliased. (Even before getting to the variable thickness on the lines part)

The solutions I've found seem to reference Vectrosity or post-processing stack. Is such a thing as a shader (not post-processing level) edge shader not possible?


texts:
I have a character that moves with a rigidbody.

When I jump, it looks fine, but sometimes, my character boosts up while in the air and shoots out of the map very quickly.

I checked, and when it happens, it says the velocity is at about 210.

Why is this happening and how can iIfix it?

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

public class playerManager : MonoBehaviour
{
    float xMovement;
    float zMovement;
    float xPosition;
    float yPosition;
    float zPosition;
    public float runningSpeed;
    public Animator animator;
    public Camera camera;
    public float cameraHeight;
    public float cameraAngle;
    public bool isOnGround;
    public float jumpForce;
    Rigidbody playerRigidbody;
    public float gravityMultiplier;
    Vector3 vel;
    public float airSpeed;
    public float groundSpeed;
    public bool canJump = true;

    void Start()
    {
        playerRigidbody = GetComponent<Rigidbody>();
        vel = playerRigidbody.velocity;
    }

    void Update()
    {

        xPosition = transform.position.x;
        yPosition = transform.position.y;
        zPosition = transform.position.z;
        PlayerMovements();
        CameraManager();
    }

    public void CameraManager()
    {
        camera.transform.position = new Vector3(xPosition+cameraAngle,cameraHeight,zPosition+cameraAngle);
    }

    public void PlayerMovements()
    {
        //Jump
        if(Input.GetKeyDown(KeyCode.Space) & isOnGround == true & canJump == true)
        {
            runningSpeed = airSpeed;
            canJump = false;
            playerRigidbody.velocity = new Vector3(xMovement,0,zMovement);
            playerRigidbody.angularVelocity = Vector3.zero;
            playerRigidbody.constraints &= ~RigidbodyConstraints.FreezePositionY;
            playerRigidbody.AddForce(transform.up * jumpForce);
            playerRigidbody.drag = 0;

        }

        //Move the Character
        if(isOnGround == true)
        {
            xMovement = Input.GetAxis ("Horizontal");
            zMovement = Input.GetAxis ("Vertical");
            Vector3 distanceToMove = new Vector3(xMovement,0,zMovement);
            playerRigidbody.AddForce(distanceToMove * runningSpeed);
        }

        //Make the player face the direction he's going at
        transform.LookAt(new Vector3(xPosition+xMovement,yPosition,zPosition+zMovement));

        //Trigger Idle or Running Animations
        if(xMovement != 0 | zMovement != 0)
        {
            animator.SetBool("Run", true);
            animator.SetBool("Idle", false);
        }
        if((xMovement < 0.05f & xMovement > -0.05f) & (zMovement < 0.05f & zMovement > -0.05f))
        {
            animator.SetBool("Run", false);
            animator.SetBool("Idle", true);
        }
    }

    public void OnCollisionEnter(Collision collidedOBJ)
    {
        if(collidedOBJ.gameObject.tag=="Finish")
        {
            Debug.Log(playerRigidbody.velocity);
            Debug.Log(runningSpeed);
        }
        if(collidedOBJ.gameObject.name == "Ground")
        {
            playerRigidbody.drag = 49;
            playerRigidbody.constraints &= RigidbodyConstraints.FreezePositionY|RigidbodyConstraints.FreezeRotationX|RigidbodyConstraints.FreezeRotationY|RigidbodyConstraints.FreezeRotationZ;
            isOnGround = true;
            canJump = true;
            runningSpeed = groundSpeed;

        }
    }

    public void OnCollisionExit(Collision exitCollidedOBJ)
    {
        if(exitCollidedOBJ.gameObject.name == "Ground")
        {
            isOnGround = false;

        }
    }

}


texts: How do I produce "enjoyably" random, as opposed to pseudo-random?

texts:
I'm making a game which presents a number of different kinds of puzzles in sequence. I choose each puzzle with a pseudorandom number. For each puzzle, there are a number of variations. I choose the variation with another pseudorandom number. And so on.

The thing is, while this produces near-true randomness, this isn't what the player really wants. The player typically wants what they perceive to be and identify as random, but only if it doesn't tend to repeat puzzles. So, not really random. Just unpredictable.

Giving it some thought, I can imagine hacky ways of doing it. For example, temporarily eliminating the most recent N choices from the set of possibilities when selecting a new choice. Or assigning every choice an equal probability, reducing a choice's probability to zero on selection, and then increasing all probabilities slowly with each selection.

I assume there's an established way of doing this, but I just don't know the terminology so I can't find it. Anyone know? Or has anyone solved this in a pleasing way?


texts: How can I get sensor data on iPhone onto a Windows PC? For use as a steering wheel

texts:
I am making a Unity game. I want to be able to allow the phone to be used as a steering wheel, as input into the PC game.

Technically, How can I achieve this? Can this be done through bluetooth?

Thanks


texts: Is there a way to check if an object is currently colliding with anything?

texts:
I need to test from another Script on a different GameObject, whether a particular GameObject is colliding with anything (in particular using trigger).

So, for my purpose, I don't need OnCollisionEnter/OnTriggerEnter events, but I need something like this:

if ( myObject.isOnCollision )
   do something

How can I do this?


texts:
As the reference page says, this function/method is used to optimize a mesh for frequent updates, but the description seems a little bit unclear.
What should I consider before using it in my code? Would there be any 'side effects' like heightened memory usage etc.?


texts: When I shoot from a gun while walking, the bullet is off the center, but when stand still it's fine. (Video Included)

texts:
I am making a small project in Unity, and whenever I walk with the gun and shoot at the same time, the bullets seem to curve and shoot off 2-3 CMs from the center. When I stand still this doesn't happen.
This is my main Javascript code:
@script RequireComponent(AudioSource);

var projectile : Rigidbody;
var speed = 500;
var ammo = 30;
var fireRate = 0.1;
private var nextFire = 0.0;

function Update() {
    if(Input.GetButton ("Fire1") && Time.time > nextFire) {
        if(ammo != 0) {
            nextFire = Time.time + fireRate;
            var clone = Instantiate(projectile, transform.position, transform.root.rotation);
            clone.velocity = transform.TransformDirection(Vector3 (0, 0, speed));
            ammo = ammo - 1;
            audio.Play();
        } else {

        }
    }
}

I assume that these two lines need to be tweaked:
var clone = Instantiate(projectile, transform.position, transform.root.rotation);
clone.velocity = transform.TransformDirection(Vector3 (0, 0, speed));

I just started Unity, and I might have a difficult time understanding some things.
EDIT:
Here is a video - http://www.screenr.com/2pxH
(If there are any more mistakes in my code, feel free to edit it.)


texts:
I am working on a FPS game for Android and I want to make a support for local multiplayer with no additional devices or server required. One of the player's devices would serve as a server, getting and distributing all the messages, OR every device broadcasts messages to everyone inside the group.
First I was thinking bluetooth or wifi direct, but I am running into many problems with both. The plan was to support up to 10 players,  so I am not sure bluetooth can handle that (broadcast messages and similar). If it is possible, let me know.
Also, I heard of an option to make a wifi hotspot on one device, and connect all other devices to it that way, but I have no idea how that would work.
Does anyone have any real experience with this, or any advice on how to implement it?
Thanks in advance.

PS. yes, I've ran through everything on android developers site, but their wifi direct example is kinda bad and only supports 1-way data transfer.


texts: OpenGL VBOs are slower than glDrawArrays

texts:
So, this seems odd to me. I upload a large buffer of vertices, then every frame I call glBindbuffer and then the appropriate gl*Pointer functions with offsets into the buffer, then I use glDrawArrays to draw all of my triangles.

I'm only drawing about 100K triangles, however I'm getting about 15FPS.

This is where it gets weird, if I change it to not call glBindBuffer, then change the gl*Pointer calls to be actual pointers into the array I have in system memory, and then call glDrawArrays the same, my framerate jumps up to about 50FPS.

Any idea what I weird thing I could be doing that would cause this? Did I maybe forget to call glEnable(GL_ALLOW_VBOS_TO_RUN_FAST) or something?


texts: Andengine onAreaTouched TouchEvent not working - ACTION_OUTSIDE & ACTION_CANCEL

texts:
I have a simple problem. I have a button on the screen. I want isActionDown to push the button down, and isActionUp to push the button back up again and make my character jump. But the problem is if I push the button down and drag away from it, the button stays pushed down. I would like the button to push back up again if the user drags away from it.

How can I create the desired affect? isActionCancel doesn't seem to do the trick.

    private void addButton(){
goB = new AnimatedSprite(240, 364, ResourceManager.getInstance().go_region, vbom){
    @Override
    public boolean onAreaTouched(final TouchEvent event, final float x, final float y){

        if (event.isActionDown()){
            goB.animate(new long[]{ 250 }, new int[] { 1 }, true);
            /*if(event.isActionCancel()){
                goB.animate(new long[]{ 250 }, new int[] { 0 }, true);
            }*/
        }
        if (event.isActionUp()){
            goB.animate(new long[]{ 250 }, new int[] { 0 }, true);
            fresh = true;
            playerBody.applyLinearImpulse(new Vector2(0, 45), playerBody.getPosition());
        }

        if (event.isActionCancel() || event.isActionOutside()){
            goB.animate(new long[]{ 250 }, new int[] { 0 }, true);
        }
        return true;
    }
};
goB.setScale(3);

registerTouchArea(goB);
attachChild(goB);

goB.animate(250);
}

I'm having the hardest time with this, and I've tried all sorts of variations of the code above. Please let me know if you have the solution.

Thanks for your help!


texts: 2D Circle detection algorithm partially working

texts:
Hello GameDev stack exchange!

I'm adapting a rectangle to circle collision detection algorithm from the second (not the accepted) answer from here: https://stackoverflow.com/questions/401847/circle-rectangle-collision-detection-intersection. This is C++ code. Here is my adaptation:

bool Collision::checkCircleToRectCollision(sf::CircleShape circle, float rectX, float rectY, float width, float height)
{
    sf::Vector2f circleDistance;

    circleDistance.x = std::abs((circle.getPosition().x - rectX) + circle.getRadius());
    circleDistance.y = std::abs((circle.getPosition().y - rectY) + circle.getRadius());

    if (circleDistance.x > (width / 2 + circle.getRadius())) {
        return false;
    }

    if (circleDistance.y > (height / 2 + circle.getRadius())) {
        return false;
    }

    if (circleDistance.x <= (width / 2)) {
        return true;
    }

    if (circleDistance.y <= (height / 2)) {
        return true;
    }

    float cornerDistance = ((circleDistance.x - width / 2) * (circleDistance.x - width / 2)) +
                          ((circleDistance.y - height / 2) * (circleDistance.y - height / 2));

    return cornerDistance <= (circle.getRadius() * circle.getRadius());
}

The problem is the collision detects only the lower right section of the circle. Without the + circle.getRadius() inside of circleDistance.x = std::abs((circle.getPosition().x - rectX) the algorithm detects even less area. Here is a a picture to visualize. I want the algorithm to detect the entire blue area. It currently only detects the red area. This is a an approximate, but very accurate from what I can tell. The white box is my players hitbox.

I've spent a few days googling and this is the closest I've gotten, but now I'm stuck. How can I make the algorithm detect the entire blue circle? Thanks in advance! :)


texts: How do I make an infinitely scrolling background?

texts:
I am trying to make a game where a torpedos keep coming from random directions and the player has to maneuver a submarine to escape them.

I am currently offsetting the background to give it an illusion that the submarine is moving i.e. if the submarine moves forward, I move the background (quad) backwards. This is primarily being done as I want it to be an infinite space. The position of the submarine does not change, the player just controls the rotation of the submarine and the background moves in the opposite direction. The background is set to repeat to give it an infinite space illusion.

The torpedo gets spawned at a random distance and moves towards the submarine. Since, the position of the submarine does not change, the torpedo will always hit the submarine. How do I structure this game, specifically the background repeat so that I can actually move the submarine in absolute dimensions and still maintain the infinite space illusion?


texts: Maintain speed, in 3D game, after collision in Unity

texts: I am making a simple breakout game. I have added bounce physics to the ball and to the bricks. When the ball collides with the bricks, the speed of ball slows down. I want ball to maintain its speed to what I set it to intially.


texts:
I'm working on a game with confusing mechanics such as energy storage and the coolant temperature. What is the best way to get a new player learned quickly? What are the pros and cons of different in-game tutorial methods? I was thinking of a tutorial with annotated screenshots, but that makes it sound like a science textbook ("Active towers are towers that consume energy and may generate heat.").
Other ways include:

in-game tutorials, which is somewhat difficult to program
tips that will show in-game and after game over
a reduced difficulty without the energy and coolant things


texts: How would I be able to get a game over screen using the pause function?

texts:
I am having problems with my snake game, when the snake collides with itself it draws a "game over" image in the background, but only while it's colliding with itself. I want it to behave like the pause function, so that as soon as the snake collides with itself it draws an image on the screen and stops the game play. And then how would you be able to restart or to quit the game?

I just have this for the detection at the moment:

if (snakeHeadRectangle.Intersects(snakeBodyRectangleArray[bodyNumber]))
            {

              spriteBatch.Draw(textureGameOver, gameOverPosition, Color.White);
            }

Thanks


texts: How to find a non active gameobject in unity?

texts:
I am trying to find a gameobject, which is not active in the current scene.It throws Null Reference error.

GameObject gameObject;
void start(){
//a non active gameobject tagged with InactiveTag
gameObject = GameObject.FindGameObjectWithTag("InactiveTag");
}
void update(){
if(someCondition){
gameObject.setActive(true); //this line throws Null Reference error
}
}


texts: Changing Unity Rigidbody.centerOfMass throws off AddRelativeTorque() calculations

texts:
This is an odd one, that has me kind of stumped. If I execute the code:

void FixedUpdate()
{
    rigidbody.AddRelativeTorque(0, 1000, 0);
}

I get this:

Normal, expected behavior. The (car in this case) rotates fine around Y. But if I try and change the center of mass,

void Start()
{
    rigidbody.centerOfMass = new Vector3(0, -0.2, 0.9);
}
void FixedUpdate()
{
    rigidbody.AddRelativeTorque(0, 1000, 0);
}

The car spins on all 3 axis. AddTorque has the same problem. It is as if AddRelativeTorque/AddTorque are not accounting for the moved position of the center-of-mass. This was done in an empty Scene with the car floating at 0x 0y 0z.


texts: How to Call a function from another script?

texts:
I just learned in a C# tutorial that we can declare var name = new ClassNameOfOtherScript(); to create a new class object, then use the object to call the function in that class, but it doesn't seem to be working in Unity.
Am I understanding it wrong or does it work differently in Unity?
I have a class Cube1 this is attached to an object with SpriteRenderer enabled. Then I have another script ClockController which is not attach to any object. When I run it, the color of cube does not change to red?
public class Cube1 : MonoBehaviour
{

    public void Rectangle()
    {
        GetComponent<SpriteRenderer>().color = Color.red;
    }

}

public class ClockController : MonoBehaviour
{

    void Start()
    {
        var cube1 = new Cube1();
        cube1.Rectangle();
    }
}


texts: XNA hlsl tex2D() only reads 3 channels from normal maps and specular maps

texts:
Our engine uses deferred rendering and at the main draw phase gathers plenty of data from the objects it draws.

In order to save on tex2D calls, we packed our objects' specular maps with all sorts of data, so three out of four channels are already taken. To make it clear: I am talking about the assets that come with the models and are stored in their material's Specular Level channel, not about the RenderTarget. So now I need another information to be stored in the alpha channel, but I cannot make the shader to read it properly! Nomatter what I write into alpha it ends up being 1 (255)! I tried:

saving the textures in PNG/TGA formats.
turning off pre-computed alpha in model's properties.

Out of every texture available to me (we use Diffuse map, Normal Map and Specular Map) I was only able to read alpha successfully from the Diffuse Map!

Here is how I add specular and normal maps to my model's material in the content processor:

if (geometry.Material.Textures.ContainsKey(normalMapKey))
{
    ExternalReference<TextureContent> texRef = geometry.Material.Textures[normalMapKey];
    geometry.Material.Textures.Remove("NormalMap");
    geometry.Material.Textures.Add("NormalMap", texRef);
}

...

foreach (KeyValuePair<String, ExternalReference<TextureContent>> texture
in material.Textures)
{
    if ((texture.Key == "Texture") ||
        (texture.Key == "NormalMap") ||
        (texture.Key == "SpecularMap"))
        mat.Textures.Add(texture.Key, texture.Value);
}

In the shader I obviously use:

float4 data = tex2D(specularMapSampler, TexCoords);

so data.a is always 1 in my case, could you suggest a reason?


texts: Finding collaborators to work on projects

texts:
I'm wondering what are good ways to find people you can work with on indie projects.
Is there anywhere some sort of list of game developer forums ? Or if it doesn't exist, what websites would you advice for that matter ?

PS : I know the question may sound a little off-topic, but I think it actually relates to project management, sorry if it is not the case.


texts: Blender->Unity Import Animation Failing by Overlapping Mesh Objects

texts:
I'm new to both Unity and Blender. I created this penguin 3d model, rigged it up and animated it in Blender and all looked good.
When I imported it into Unity, I noticed that this idle animation did not appear to be working correctly. As the body moves, the body mesh overlaps the belly mesh and covers a portion of it.

This is not the case when viewing the animation from blender 2.9.

The belly uses a shrinkwrap modifier with the body as a target.
Is this a problem with Unity import, or how I modeled this penguin in Blender? Can anyone see what I have done wrong here? Any help is much appreciated!


texts:
I am trying to profile my LibGDX game, It runs on 60FPS on PC and 42-45 FPS on MY mobile phone. Either I improve performance and raise it to 60, or lock it at 30 (I don´t want to do this).

I have found GLProfiler on the LibGDX wiki, and I am giving it a try. (GLProfiler)

Here is how I am using it:

@Override
public void render(float stateTime)
{

    //my Render Code

    System.out.println(
            "  Drawcalls: " + GLProfiler.drawCalls +
                    ", Calls: " + GLProfiler.calls +
                    ", TextureBindings: " + GLProfiler.textureBindings +
                    ", ShaderSwitches:  " + GLProfiler.shaderSwitches +
                    "vertexCount: " + GLProfiler.vertexCount.value
    );
    GLProfiler.reset();
}

  with GLProfiler.enable() on the create() function.

  with GLProfiler.disable() on the dispose() function.

And this is my output:

  Drawcalls: 35, Calls: 666, TextureBindings: 35, ShaderSwitches:  60, vertexCount: 36.0

  Drawcalls: 33, Calls: 626, TextureBindings: 33, ShaderSwitches:  56, vertexCount: 36.0

  Drawcalls: 33, Calls: 626, TextureBindings: 33, ShaderSwitches:  56, vertexCount: 36.0

  Drawcalls: 33, Calls: 626, TextureBindings: 33, ShaderSwitches:  56, vertexCount: 36.0

  Drawcalls: 33, Calls: 626, TextureBindings: 33, ShaderSwitches:  56, vertexCount: 36.0

  Drawcalls: 33, Calls: 626, TextureBindings: 33, ShaderSwitches:  56,
  vertexCount: 36.0

  Drawcalls: 35, Calls: 666, TextureBindings: 35, ShaderSwitches:  60, vertexCount: 36.0

  Drawcalls: 35, Calls: 666, TextureBindings: 35, ShaderSwitches:  60, vertexCount: 36.0

  Drawcalls: 35, Calls: 666, TextureBindings: 35, ShaderSwitches:  60, vertexCount: 36.0

  Drawcalls: 35, Calls: 666, TextureBindings: 35, ShaderSwitches:  60, vertexCount: 36.0

  Drawcalls: 33, Calls: 626, TextureBindings: 33, ShaderSwitches:  56, vertexCount: 36.0

  Drawcalls: 33, Calls: 626, TextureBindings: 33, ShaderSwitches:  56, vertexCount: 36.0

This is just a couple frames, enough for the example.

I have been looking for information on how to read these numbers, I found nothing.

Do you guys know how can I learn from this information? (Identify problems maybe?)


texts:
Hi guys first time poster with a quick question. I'm just getting started with coding and as an easy exercise I wanted to make a block move and sprint. I got it to do that but when I press the shift key too fast the getKeyUp part divides the speed variable too many times. How do I fix this?

public class Movement : MonoBehaviour
{
    public float speed = 5f;
    public float speedmutiplier = 2f;

    private void FixedUpdate()
    {
        if (Input.GetKey("w"))
        {
            transform.Translate(0, 0, speed * Time.deltaTime);
        }

        if (Input.GetKey("s"))
        {
            transform.Translate(0, 0, -speed * Time.deltaTime);
        }

        if (Input.GetKey("a"))
        {
            transform.Translate(-speed * Time.deltaTime, 0, 0);
        }

        if (Input.GetKey("d"))
        {
            transform.Translate(speed * Time.deltaTime, 0, 0);
        }

        if (Input.GetKeyDown("left shift"))
        {
            speed = speed * speedmutiplier;
        }

        if (Input.GetKeyUp("left shift"))
        {
            speed = speed / speedmutiplier;
        }
    }
}


texts: How can I make Unity run fast when it's not focused?

texts:
I'm using Unity3D.  I have an automated test suite that takes 1-2 minutes to run.  When Unity has focus, these tests seem to run at least 2x as fast as when Unity is in the background.  But, it's very boring to stare at a progress bar for 1-2 minutes while I wait for the tests to complete.  The whole reason I want to put it in the background is so I can do something else while these tests are running, but because it slows down the tests to 2-4 minutes, doing so makes me even less efficient.

Is there a way to have Unity run as fast as it does when it's focused, even when it's not focused?

This could be a Windows 10 question more than a Unity question.  Maybe there's a way to set the Unity process as "high priority" or something.


texts:
Look at the picture.

The figure on the left shows the individual box colliders in green.

The yellow boxes on the right are the results of the optimization of the original box colliders.

What is the algorithm that makes this possible?


texts: Casting every received packet as struct?

texts:
What is the best performant solution to handle received data from socket, in a MMORPG game? Is it good to have something like:

[StructLayout(LayoutKind.Explicit, Pack = 1)]
public struct LoginPacket
{
    [FieldOffset(0)]
    public int size;
    [FieldOffset(4)]
    public int opcode;
    [FieldOffset(32)]
    public int someOtherImportantOffsetInPacket;
}

And then when every packet is received I create the correct struct for the received packet, to access its information easier?
Or the best performant solution is if I just pass the byte[] to the function and use functions like BitConverter.ToInt32 ? I know BitConverter is slow, but I already have my own class that does the same thing in a faster way.


texts: Unity3D Build Configuration for Deployment/ Publish

texts:
Is there the option within Unity3D to specify build configurations?

My goal is relatively simple - when building for mobile stores (Play Store/ App Store) I want to make sure my app is pointing to the production services, rather than the test one I use in the editor/ testing on devices.

It's controlled by a field on a MonoBehaviour currently, but we I need to remember to flip it from Test to Production before doing a build and publish.


texts: How can I move a 3d object to a known Cartesian point on the surface of a sphere?

texts:
I'm trying to figure out how to move an object from one Cartesian point to another located on the surface of a 3D sphere. So that the object will follow the spherical coordinate system (Theta and Phi)

I've a function that converts a Cartesian to Spherical but how can I make it work on the surface of a sphere just like we are using the equation of a line y=mx+b when moving from one point to another on a flat surface?

I'm going to use it to move an object from its point to a selected point somewhere else on the sphere so that the object will move in a straight line but following the curvature.


texts: How can i rotate gameobjects back from mirror?

texts:
For some reason when i create the gameobjects they are places like mirror.
And i'm not sure how to rotate them back.

for (int i = 0; i < pointsList.Count; i++)
        {
            GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
            cube.transform.parent = transform;
            cube.transform.position = new Vector3(pointsList[i].Y, 0, pointsList[i].X);
        }

pointsList is a List
For example in index 4 X = 3 Y = 17

But i'm not sure why it's creating the objects mirrored. And how to rotate it back.

In the screenshot it should be written Hello World but it looks mirror.
The empty GameObject rotation is 0,0,0 and each child Cube rotation also 0,0,0


texts: Tilemaps are loading differently each time

texts:
Tilemap data is stored in a 2D array.
It is saved using the following code

void Chunk::save_to_file() {

    // FILENAME
    std::string filename = std::to_string(chunk_seed);

    std::fstream file;
    file.open(filename + ".chunk", std::ios::out);

    for (int i = 0; i < Constants::BIOMESIZE; i++) {
        for (int j = 0; j < Constants::BIOMESIZE; j++) {
            file << std::to_string(chunk[i][j]);
            file << ",";
        }
    }

    file.close();

}

And it is loaded using the following code

void Chunk::load_from_file() {
    // FILENAME
    // The chunk will be located at hash(chunk_x, chunk_y) ^ seed = chunk_seed
    std::string filename = std::to_string(chunk_seed);
    // Data within file
    std::string data;

    std::fstream file;
    file.open(filename + ".chunk", std::ios::in);
    file >> data;
    file.close();

    std::vector<std::string> tokens = split(data, ',');

    for (unsigned int i = 0; i < Constants::BIOMESIZE; i++) {
        for (unsigned int j = 0; j < Constants::BIOMESIZE; j++) {
            chunk[i][j] = std::stoi(tokens[i + j * Constants::BIOMESIZE]);
        }
    }
}

Tilemaps are loaded using the loading function when the program is started up and displayed.
Tilemaps are saved using the saving function when the program is exited.
They do not display the same way each time.
I have pinpointed that the problem is in the saving function.
This is because I commented out the saving part and when I was only loading the same files it worked and had the same output each time.
It appears as though the saving function rotates the tilemap by 180 degrees each time I save it.
How can this be fixed?


texts: How can I draw blurred models/images in 3d space like here:


texts: Sending a players mouse movement to the server in an FPS

texts:
So I have a server-client model FPS set up. It uses udp to send data between the two with the server having a constant tick rate of 100 ticks per second (It updates movement 100 times a second) on the server with the client doing update of its key states etc 30 times a second and for keys the system works well. But now my question is how would I send the mouse movement to the server as this in not an on/off system is is constantly changing.

So my question is how do you send the movement of the mouse to the server. Do you send the direction and speed that the mouse is moving each update and interpolate it or something else. The problem I can see with interpolating something like a mouse is that in an FPS it is required to be very accurate and interpolating is literally guessing. Any advice would be appreciated.

The other problem that I see is that to get a direction vector of a mouse you would have to wait for enough movement to get the vector.

Another idea has come to me and that is just sending the direction that the client thinks its looking when it shoots.

Any advice would be much appreciated.


texts: Adding a function call to a prefabbed button in Unity

texts:
For each of my scenes, I have an empty GameObject _Manager that stores my scripts for setting up the level, keeping track of variables, etc.

On my main screen, I have a play button that isn't instantiated; I simply dragged it into the editor. In my script Main.cs I have a function Play() which calls LoadLevel("Game"). To get my play button to call the Play function, I dragged _Manager into the onClick slot and selected the function. This worked fine and I have a functional play button.

Unfortunately, this is not working for the prefabbed buttons I need to instantaite in my Game scene. In Game.cs I have a function LayoutButtons() which is both public and returns void, yet I am unable to drag _Manager into the slot on my prefabbed button. Even if I do it before converting the button to a prefab, it simply disappears once it becomes a prefab.

I've managed to work around this by putting my LayoutButtons() function in a new script which I attached directly to the prefab, but I'd like to keep the function within Game.cs and attached to my manager object if that's possible.


texts: How does IAP relate to Unity's Package Manager?

texts:
In Unity 2018.3, if you open Window > Package Manager, you can choose to install/remove "In App Purchasing".

This seems to be completely separate from the IAP version installed from the Services tab. If you only install IAP from the package manager, the Services tab doesn't detect that it's installed. If you install IAP from the Services tab and don't have it installed in the Package Manager, the Editor doesn't seem to care.

What does installing IAP from the Package Manager actually do?


texts: Depth sorting 2D textures in a batch with OpenGL ES 2.0

texts:
I have a combo of texture atlases and sprite batches in an OpenGLES 2.0 2D game I'm developing which is working well, but I have a problem with depth sorting.

I'm using atlases to reduce the number of texture bind operations, and sprite batches to reduce the number of draw calls and everything is rosy but I've hit a logical problem when it comes to how to arrange the sprites in the game.

Because the whole point of using the atlas together with the batch is to save on bind/draw calls I inherit a limitation that I can't draw sprites in the same batch which have textures across multiple atlases.

This means I have to think carefully about the z ordering of the 2D sprites.  If sprite "A" should sit behind sprite "B" then I have to draw sprite A's batch first.. ok fine.  The problem arises when there are three sprites, A,B and C where A is behind B and B is behind C but A and C are on the same atlas.

That is,

Atlas 1
---------
| A | C |
---------

Atlas 2
-----
| B |
-----

Scene
-----------------------
[CAMERA] -> C -> B -> A

Now obviously I could achieve this with multiple bind/batch operations but that kind of defeats the purpose of having it in the first place.  Ideally I don't want to have to think about which sprite is on which atlas and just change the 'z' value for the sprite.

I experimented with enabling GL_DEPTH_TEST but most of my sprites use textures with some level of transparency so this won't work for me.

Is there a "standard" approach to this?  Or have I painted myself into a corner I should never have?


texts:
I am building an MMO and want to add NPCs. The thing is I don't know the basic design. What does the calculations, the clients or the server? I would understand the server calculating events and reactions, but when it comes down to pathfinding and position and movement of player, who calculates that?

Who calculates the AI the server or client? I couldn't imagine the server calculating the pathfinding, position, movement and so on. Please I need help understanding this, thanks, anything will help.


texts: DPad style movement for AI without using A*

texts: What is the easiest way to implement DPad style movement (No diagonal) for AI without using and A* algorithm? I thought about having the enemy catch up to the player in the Y axis first then the X axis (or vice versa) but then it would be too easy to evade the enemy. If it matters I'm doing this in Objective-C using Cocos2d. Any input would be appreciated.


texts: Fast and simple attenuation from a flaming torch

texts:
I have a single point light-source which is a flaming torch.  I compute the distance from the light accurately.

I am not trying to have a particularly realistic torch effect, but I will be moving the light-source slightly each frame and perhaps introducing a slight flicker in strength.

I want near the light to be white - say up to a distance of 200 - and then getting darker and yellower until, say, 400 before fading rapidly to black at 450.

What is the best way to do smooth extinction like this?

Here's my current fragment shader, simply so I know that I have it centered correctly:

uniform vec4 COLOUR;
uniform sampler2D TEX_UNIT_0;
varying vec2 tex_coord_0;
varying vec3 normal;
varying vec3 light_0;
void main() {
    vec3 pixel = vec3(0.,0.,0.);
    vec3 N = normalize(normal);
    vec3 L = normalize(light_0);
    float lambert = max(dot(N,L),0.);
    if(lambert > 0.) {
        pixel = texture2D(TEX_UNIT_0,tex_coord_0).rgb;
        float att = 1.;
        float d = length(light_0);
        if(d > 300.) att *= .5;
        if(d > 350.) att *= .5;
        if(d > 400.) att *= .5;
        if(d > 450.) att *= .5;
        if(d > 500.) att = 0.;
        pixel *= att;
    }
    gl_FragColor = vec4(COLOUR.rgb * pixel * lambert,COLOUR.a);
}


texts: How to calculate corner positions/marks of a rotated/tilted rectangle?

texts:
I've got two elements, a 2D point and a rectangular area. The point represents the middle of that area. I also know the width and height of that area. And the area is tilted by 40° relative to the grid.

Now I'd like to calculate the absolute positions of each corner mark of that tilted area only using this data. Is that possible?


texts: How to change a Maya scene file's selected viewport renderer from the file itself (text edit)?

texts:
So I have been running Viewport 2.0 in my 2012 version of Maya for a couple weeks with no problem. Day before yesterday it started crashing on load with a random MSVC dll pointer error. It's common, but a work around doesn't exist. Anyone know how to modify my .ma scene file contents so that none of my viewports are running Viewport 2.0?

I can import my stuff to another scene, but it's not fun.


texts: Correctly implement of an object rotation

texts:
How can I correctly implement 360 degree rotation of some object, every time when some condition is meet?

I have two class, one with definition of function and second with setInterval() function. The problem is that the 360 degree rotation is performed only once, even if later also occurs this condition.

First class (A):

function rotObject()
{
if(rot < 360)
{
 _root.myObject._rotation = _root.myObject._rotation + 10;
}
else
{
clearInterval();
}
rot = rot + 10;
}
var rot = 0;

Second class (B):

class B extends MovieClip {
if (<something>) {
setInterval(A.rotObject, 10);
}
}


texts: LibGdx and in-game fonts - any proven methods?

texts:
I use 3 sizes for fonts in my game: small, medium, and large. I take the base font size and attempt to scale the font based on screen size and density, but this is proving to be pretty hard.

Does anyone have a proven formula for scaling fonts? Right now I'm simply using the pixel width of the screen to put the device into 1x, 2x, and 3x font scale bucket sizes, but I feel like I should be using the screen density in the calculation as well.


texts: I have a curious question regarding on musics used in music rhythm game. In Guitar Hero for example, they used all different music albums in one program. Then, each album requires to ask permission to the owner, composer of the music, or the copyright owner of the music. Let's say, if you used 15 albums for the music rhythm game, then you have to contact 15 copyright owners and it might be that, for the game developer, that the profit earned goes to the copyright owner or owner of this music. For the independent game developers, was it okay if either used the copyright music by just mentioning the name of the singer included in the credits and in the music select screen or use the non-popular/old music that about 50 years ago? And, does still earn money for the indie game developers by making free downloadable game?


texts: Image Buttons Have Low Resolution Quality

texts:
I'm using Synfig Animator to draw my animations for my android game
I'm also using Android Studio to write the code for it, However.
On testing, the images that i'm using looks very bad and unfocused even though i made them on a high resolution,
I've tried to change the resolution of it but it didn't work!
and when i change the size it just get bigger and stay the same..
How can i fix this problem? i need to have perfect animations for my game.


texts:
I'm an architecture student in my last year. I've always been interested in videogames design. I use 3d Max and Photoshop on a daily basis, and I was thinking about aiming for a career in videogames, starting as a level/environment designer.

How should approach it? Is it worthy to spend some time learning UDK or CryEngine? Should I try a smaller but more general software? I know some programming already.

Finally, will my skills as an architect be something valuable in the indusrty?

Thanks in advance.


texts:
So I've a 3d game project I'm working on and I'm using 2 model files (SkyBlock.x and AimedBlock.x).

So until now everything was all good and my models files were compiled all okay and I was able to use them within my game. With the latest changes (which I don't know what caused it really) - XNA stopped compiling my model files and instead only outputs files;

AimedBlockxnb - 1kb
SkyDome.xnb - 1kb
SkyDomeTexture.xnb - 1389 kb
SkyDomeTexture_0.xnb - 419 kb

So I created a test XNA game project and moved all my asset's to new solution content project's and tried compiling them and saw that they're all good.

AimedBlockxnb - 2kb
SkyDome.xnb - 13kb
SkyDomeTexture.xnb - 4097 kb
SkyDomeTexture_0.xnb - 683 kb

So I guess my main project sucks there but I couldn't came with a solution. I even tried overwriting my game's content project with new game's content project (which was all okay) but it didn't work.

Anybody had similar issues?


texts:
3d Max does export Opacity value of an material to Fbx, which in Xna (when importet/processed) can be easily found in BasicEffect of a mesh instance Alpha property (and used in draw method).

My question is:

Can opacity values on animated mesh be exported (specific opacity states/values over time/keyframes) ??

From what I gathered it seems that only Opacity value of the First frame of animated mesh is exported (and found in BasicEffect of mesh). So if in Max there are keyframes with different opacity values and Max animation preview clearly show these transparency transitions when moving scroll, then do not get exported to Fbx.

Are there knows techniques/hacks to inject opacity from animated meshed (values over time/keyframes) to Fbx?


texts: Visualization tools for physical simulations

texts:
I'm interested in starting some physics simulations and I'm getting hung up on the visualization side of things. I have lots of resources for reading how to implement the simulation itself but I'd rather not learn two things at once - the simulation part and a new complex visualization API.

Are there any high-level visualization tools that are language independent? I understand that I'll have to learn some new code for visualization but I'd like to start at a high level, OpenGL is my long-term goal and not my prototype goal.


texts:
What are the things one should consider before doing light maps?

We have custom models in Unity Scene,while doing light mapping it stuck at "Clustering job 5/11".

After researching I come to know models should be "Manifold" to be light mapped  so we did manifold our custom models and now light maps are occurring properly though at the cost of lot of polys which is causing performance hit on Android device.

So my question is has anyone faced similar issue or workaround for same?


texts:
I have a very general question: In games, what use does the programming concept of a window have? Or, in other words, why do some game dev libraries offer interfaces through which to create multiple windows? — Why would you need more than one windows in a game?

Are multiple windows used as different views/states of the game? (I.e. in-game, main menu, pause menu, etc.)


texts: Java RPG class implementation (design pattern ?)

texts:
For my school project I'm making a little NFC based game on Android.
The concept is simple, on each phone you create a character and you can fight with other people through NFC.

The character will have have a set of attributes, like strength, agility, etc which are represented as short (only 2 bytes => for NFC communication).
A character must have a race (human, dwarf, ...) and a class (warrior, wizard, ...).
Each race has attribute advantages (ex : + 2 strength for dwarf) and a passive bonus ex : +5% gold after a fight.
Each class can wear different weapon and will have a different attack() methods.

My problem is that I don't know how I should create my character class and allow it to have a race and a class.

Does anyone have an idea of how I can accomplish this ?


texts:
So I'm making a little engine with DirectX 11 and C++. (Some other help from other API's as well) DirectX has this function XMMatrixRotationQuaternion(XMVECTOR quaternion). I know nothing about this so excuse my cluelessness. I have a few questions about them that maybe someone could help me with.

Do I use XMMatrixRotationQuaternion(XMVECTOR quaternion) and multiply the resultant Matrix with my scaling matrix and translation matrix to get my transformation matrix?
How can I convert an angle (let's say in radians) to a quaternion. I've tried to look at this and what I got was something like this(I have a feeling this isn't anywhere close to correct)...
Lastly, do I need to normalize that XMFLOAT3 axis?

static XMVECTOR XMConvertToQuaternion(XMFLOAT3 axis, float radian)
{
   return XMVectorSet(cos(radian/2), sin(radian/2)*cos(axis.x), sin(radian/2)*cos(axis.y), sin(radian/2)*cos(axis.z));
}


texts:
My player is getting caught on something on the floor. My whole environment is just blocks. I have looked through (and tried to change) just about everything I can think of in my player update method. Any idea what could be solving this? Here is the code:

public void update(GameContainer gc, int delta, Map m){
    boolean updateX = true;
    boolean updateY = true;

    if(!movingLeft && dx < 0f){
        dx += .2f;
    }
    if(!movingRight && dx > 0f){
        dx -= .2f;
    }

    if(!movingLeft && !movingRight && ((dx < 0 && dx > -.2f) || (dx > 0 && dx < .2f))){
        dx = 0f;
    }
    boolean fallFlag = true;
    prx = new Rectangle(x + dx, y, 10, 10);
    pry = new Rectangle(x, y + dy, 10, 10);
    for(Platform p : m.platforms){
        r = new Rectangle(p.getX() - 2, p.getY() - 2, 20 + 2, 20 + 2);
        if(prx.intersects(r)){
            updateX = false;
            dx = 0;
        }
        //check if my dy will cause me to hit a platform
        if(pry.intersects(r)){
            //if I am moving down, set falling to false
            if(dy > 0)
                fallFlag = false;
            updateY = false;
            dy = .025f;
        }
    }
    inAir = fallFlag;
    if(inAir)
        dy += .025f;
    if(updateX)
        x+=dx*(delta/10);
    if(updateY)
        y+=dy*(delta/10);
}


texts: Is there a simple way to group two or more sprites, so all of them will be dependent on each other?

texts:
I think that this question is very similar to this one, but I'm not sure if the answers are universal.

So, my goal is:

Place two sprites in fixed position, for example player and his eyes
Make sure that whenever the player rotates, eyes sprite rotates too and gets to the same relative position from the body (so eyes aren't on player's back). So they'll be working as a group. - This step should be automated, that's my goal!

So, for example, I now want to place a gun in user's hands. So now I say, that player is in position Vector2(0, 0) and gun is in position Vector2(26, 16). Now I want to group them up, so whenever the player rotates, gun rotates too.

Currently in this example it's pretty okay but in case that I'd need to move my gun on axis y (only), I'm lost


texts: How to manage all the NPC/AI objects on the server?

texts:
I'm writing a simple MMO, and currently have the the server-client architecture in place for multiple users to see each other and be able to move around together...now its time to add enemies.

Was wondering if anyone had links to articles that discussed how to best handle the hundreds of NPC objects that need to be managed in the world. I've done some searching and couldn't find much info about how this is typically done.

The two methods of structuring the implementation I can think of:

Holding all the instantiated NPC objects in a list, and having an NPC Thread loop through them sequentially and see if each has any logic that needs to be processed and perform necessary actions. I'm not sure if the performance of this design would be sufficient?
Event based system. Create a method in the NPC class that processes AI/Logic on it, have this method be called when an associated event is signaled, either on a timer for non interacted AI functionality (such as wandering), or signal the event externally from the packet handler (player moving nearby, or player attacking within range).

Is either of these approaches the correct way? What other methods of doing this exist?


texts: Efficient Storage of Objects in a 2D Grid

texts:
When trying to store data related to objects in my 2d top-down tile based game (specifically, blocks), I realized that I don't have an efficient solution to storing them. I could have, for example, a 2D array of them, but that would be extremely inefficient considering the amount of possible locations there are. Also, an ArrayList is inefficient becauase number one, it severly impacts cpu usage when adding/subtracting/looking up elements, and number two, it isn't ordered.

Therefore, my question is how would I go about setting up an efficient way to store objects so as to be able to find them within a certain area and also to add and subtract from them quickly?


texts: Why are 3d projections on a 2d screen not like what the human eye sees?

texts:
Firstly, I'm sorry if this question doesn't make much sense or is poorly written - I have almost no experience with programming, and none at all with game development. I'm also not sure it's an appropriate question for gamedev stack exchange, so sorry if that's the case.

Anyway, the question is this - what are some ways of doing the vision in a fps game?

If I understand it correctly, the problem can be stated the following way - given a 3d environment given in 3d coordinates, and a camera with some direction and certain field of vision, our goal is to somehow project the environment, to a 2d screen, similar to how our eyes do it, or similar to how a camera does it.

One way to do this is the following - whatever is exactly in the direction of the camera will get displayed exactly to the middle of our 2d screen (let's presume the 2d screen is round for simplicity, with radius 1), and the rest in the field of vision will get projected linearly based on the angle. For example, if field of vision is 90 degrees (anything 45 degrees from the direction of the camera will be in the field of vision), then things 45 degrees away from the direction of the camera will get displayed to the outer circle/edge of the 2d screen, and things 22.5 degrees away will get displayed to the circle with radius 0.5. This might be similar to how a camera or our eye does it, but I'm not sure.

Now in reality, this doesn't seem to be how it's done. To give an example, if I take something like DOOM, or I think any modern fps game, and I were to stand in front of a very long wall that's of the same height everywhere, and I were looking perpendicularly towards it, the height of the wall will be the same everywhere in my 2d projection - in reality though, or a camera for example, would display the very furthest (furthest from the center of the vision) parts of the wall to be shorter in height.  But, given a small enough field of vision, the difference seems negligible.

Either way, it seems like fps games don't really consider this fact, and I want to ask - why? Maybe the difference is barely noticeable, but much more power demanding? Either way, I would appreciate an explanation or information concerning how exactly the human eye or camera projects 3d environment to a 2d picture.


texts:
I'm currently developing a 2D, top-down Windows Phone 7 game involving the surface of a pond.  I'm trying to make the surface feel like actual water (as opposed to just a blue background with sprites drawn on top of it), and one of the effects I'm looking into is a sort of aquatic distortion effect.  Basically, something similar to the first few seconds of this: http://youtu.be/1BpRsjF7QTM?t=3m17s

Any idea on how to do this in XNA? I'm sure I could figure out how to apply the answer to my particular application, but if it helps, my game involves a lot of ripples and I'd like to specifically distort the areas around and just behind the expanding sprite-based ripples.

Thanks!


texts: Difference between #DEBUG and #DEVELOPMENT_BUILD in Unity?

texts:
I've seen these two special compilation macros in our code base, What's the difference between #Debug and #DEVELOPEMENT_BUILD in Unity? What's the main purpose of using each?

#if DEBUG
Debug.Log("DEBUG");
#endif

#if DEVELOPMENT_BUILD
Debug.Log("DEVELOPMENT_BUILD");
#endif


texts: GameState management hierarchical FSM vs stack based FSM

texts:
I'm reading a bit on Finite State Machines to handle game states (or screens). I would like to build a rather decent FSM that can handle multiple screens.

e.g. while the game is running I want to be able to pop-up an ingame menu and when that happens the main screen must stop updating (the game is paused) but must still be visible in the background. However when I open an inventory pop-up the main screen must be visible and continue updating etc.

I'm a bit confused about the difference in implementation and functionality between hierarchical FSM's and FSM's that handle a stack of states instead. Are they basically the same? Or are there important differences?


texts: Eliminate 0.25 unit 'force fields' around Bullet Physics soft bodies

texts:
When I create soft body assemblies in Bullet Physics they will fall under gravity and then float about 0.25 units above a ground plane rigid body, and other rigid bodies all appear to push and interact with them from that same distance (all the rigid bodies correctly interact with each other only when they appear to touch).

Does one of the many soft body parameters cause this?

I can run more experiments to see if this effect is confined to nodes or shared by links/faces/tetras.

The soft body demo is worth another look- perhaps it has the same problem but all objects are so much larger than what I'm working with that it isn't obvious- I was hoping to do 1 unit = 1 meter but then have cm scale objects.

The code is here https://github.com/lucasw/simple_sim_ros/blob/master/bullet_server/src/soft_body.cpp and elsewhere in that same repository.

Update

The soft body demo does appear to be floating just like my own project, the picture above shows a gap between the bottom of the ellipsoid and the ground.


texts: change position/orientation of a bone using assimp

texts:
I have been using assimp to import rigged models and animations. I followed this tutorial for skeletal animation and I have got it done properly. The part that I am trying to do now is to orient a certain mesh by using transformation matrix, which represents change from the initial orientation of bone For example, rotating left hand of the model by a 90 deg angle shall make the hand vertical if it's initially horizontal. To achieve this I have taken the following steps:

map each bone with its bone offset matrix, given by pBoneData[BoneIndex].BoneOffset below. This BoneOffset matrix transforms from mesh space to bone space.
find the parent bone in a mesh i.e. body part,
get the matrix for orienting the mesh, and save this matrix for parent bone of that mesh, given by pBoneData[BoneIndex].rotTransform. For all the other bones in a mesh, the orientation matrix is identity matrix;
traverse the node heirarchy and assign final transformation for each bone as:

void rag::BoneTransform(const aiScene* mScene)
{
aiNode* pNode = mScene->mRootNode;
readNode(pNode, IdentityMatrix);
}

//recursive process
void rag::readNode(aiNode* pNode, Matrix4f& ParentTransform)
{
 Matrix4f rot, GlobalTransformation;
 std::string NodeName(pNode->mName.data);
 Matrix4f NodeTransformation(pNode->mTransformation);

 if (boneMapping.find(NodeName) != boneMapping.end())
 {
 //if node represents a bone, then take it`s unique index
 unsigned int BoneIndex = boneMapping[NodeName];
 //rot is the matrix that represents change in orientation of bone
 rot = pBoneData[BoneIndex].rotTransform;
 GlobalTransformation = ParentTransform * NodeTransformation;
 pBoneData[BoneIndex].FinalTransformation = GlobalInverseTransform * GlobalTransformation * pBoneData[BoneIndex].BoneOffset;
 }

 GlobalTransformation = ParentTransform * NodeTransformation;

for (unsigned int i = 0 ; i < pNode->mNumChildren ; i++)
readNode(pNode->mChildren[i], GlobalTransformation);

}

If the function above is run as it is, it will display the model in the state it was while posing it in Blender, in T pose in my case. I am having problems on using 'rot' Matrix. One of the books that I read suggested multiplying the initialBoneOrientation with the changeMatrix. My initial thoughts was to sum 'rot' with NodeTransformation as both of these represent relative change from their parent Matrices. However, I got a totally disfigured model on doing so. Any thoughts on these is highly welcomed.


texts: How to make an object track another object's exact movements

texts:
This script below helps me to to tell the follower object to copy exact movements of the leader object, I found this script in Unity forums and it works pretty well.

My question is how can I add some kind speed variable to it; how can I tell the follower object to move at lower speed?

 public class delayTracker : MonoBehaviour
 {
     float progress;
     const int MAX_FPS = 60;

     public Transform leader;
     public float lagSeconds = 0.5f;

     Vector3[] _positionBuffer;
     float[] _timeBuffer;
     int _oldestIndex;
     int _newestIndex;

     // Use this for initialization
     void Start()
     {
         int bufferLength = Mathf.CeilToInt(lagSeconds * MAX_FPS);
         _positionBuffer = new Vector3[bufferLength];
         _timeBuffer = new float[bufferLength];

         _positionBuffer[0] = _positionBuffer[1] = leader.position;
         _timeBuffer[0] = _timeBuffer[1] = Time.time;

         _oldestIndex = 0;
         _newestIndex = 1;
     }

     void LateUpdate()
     {
         // Insert newest position into our cache.
         // If the cache is full, overwrite the latest sample.
         int newIndex = (_newestIndex + 1) % _positionBuffer.Length;
         if (newIndex != _oldestIndex)
             _newestIndex = newIndex;

         _positionBuffer[_newestIndex] = leader.position;
         _timeBuffer[_newestIndex] = Time.time;

         // Skip ahead in the buffer to the segment containing our target time.
         float targetTime = Time.time - lagSeconds;
         int nextIndex;
         while (_timeBuffer[nextIndex = (_oldestIndex + 1) % _timeBuffer.Length] < targetTime)
             _oldestIndex = nextIndex;

         // Interpolate between the two samples on either side of our target time.
         float span = _timeBuffer[nextIndex] - _timeBuffer[_oldestIndex];
         float progress = 0f;
         if (span > 0f)
         {
             progress = (targetTime - _timeBuffer[_oldestIndex]) / span;
         }

         transform.position = Vector3.Lerp(_positionBuffer[_oldestIndex], _positionBuffer[nextIndex], progress );
     }

     void OnDrawGizmos()
     {
         if (_positionBuffer == null || _positionBuffer.Length == 0)
             return;

         Gizmos.color = Color.grey;

         Vector3 oldPosition = _positionBuffer[_oldestIndex];
         int next;
         for (int i = _oldestIndex; i != _newestIndex; i = next)
         {
             next = (i + 1) % _positionBuffer.Length;
             Vector3 newPosition = _positionBuffer[next];
             Gizmos.DrawLine(oldPosition, newPosition);
             oldPosition = newPosition;
         }
     }
 }


texts:
Given a mesh, I want to generate another mesh that is effectively a shadow volume of this mesh.

I am looking for an algorithm/solution/implementation/reference that can do this under the following constraints:

I have a single, point light source. Thus:

Not a polygon;
I want hard edges/faces (not soft shadows)

The light source is at infinity, in fact can be assumed to by directly above the mesh. Thus:

The projection is actually orthographic and depends only on a single direction.

I want an exact solution.

The result mesh is not used for display so cannot be based on resolution dependent rasterization as many algorithms are.

A naive algorithm is to extrude all mesh triangles in the direction away from the light, e.g. downward, and do a CSG union of all these extruded "prisms".
The drawback here is that:

It does this for all triangles and not just the visible ones (how to do exact visibility?);
it requires a massive amount of CSG operations which are expensive.

I'm looking for a more efficient algorithm.


texts: I was recently reading an article about clever ways programmers have protected their games from pirates, such as the creators of Game Dev Tycoon. This made me curious: how do they detect that the copy of the game running is in fact a pirated version on a technical level? The closest answer I was able to find through some research was how SNES cartridges can detect if they're pirated, but that tactic obviously doesn't apply to PCs.


texts: Broadcast message to Parent Gameobject and Siblings in Unity

texts:
I wish to broadcast a message from one object to it's parent and it's siblings. I am aware that unity does not support broadcasting a message to all other game objects but is there a way to broadcast to parent and siblings?

I am using Unity 5.


texts: Unity3D - Finding every subclass of monobehaviour in current project with reflection

texts:
I am trying to find all types that inherit from monobehaviour inside my Unity project. So not the instances of them but the actual types in the assembly. I've tried this little piece of code and I don't understand why it is not getting the types. The debug is logging 0.

Also I am going to use this in editor scripting. But for testing purposes I am running the code in the start method of a component.

using System.Collections.Generic;
using UnityEngine;
using System.Reflection;
using System.Linq;
using System;

public class TypeGetter : MonoBehaviour
{
    private Dictionary<Type, FieldInfo[]> monobehavioursInfo = new Dictionary<Type, FieldInfo[]>();

    private void Start()
    {
        monobehavioursInfo = GetTypes<MonoBehaviour>();
        Debug.Log(monobehavioursInfo.Count);
    }

    private Dictionary<Type, FieldInfo[]> GetTypes<T>()
    {
        Dictionary<Type, FieldInfo[]> temp = new Dictionary<Type, FieldInfo[]>();
        foreach (Type t in Assembly.GetAssembly(typeof(T)).GetTypes()
            .Where(myType => myType.IsClass && !myType.IsAbstract && myType.IsSubclassOf(typeof(T))))
        {
            FieldInfo[] fields = t.GetFields();
            temp.Add(t, fields);
        }
        return temp;
    }
}


texts:
Possible Duplicate:
  Legal issues for a “fangame” of a commercial franchise?

What if I decide to make a fanmade game from a popular, recent game release?

100% non-profit. I will just post my game in a forum.
Graphic work is 100% mine.
I DO have some sounds from the original game. I have credited the developers.
The game's title might include the original game's title, but I do have other unique words in it.

Is that possible?


texts:
Ok, so I was thinking of making a Texas Hold'em game, and I wanted to write down the game logic loop before starting. Here's what I have. Tell me if I missed anything or if anything is wrong.

Game sets or determines the number of players.
Game hands out 2 cards to each players.
Game takes a minimum amount of tokens from each player
Game lets players fold, play, or raise
If someone raise, the game let's other players fold or play, and then loop through the players who decided to play, but haven't put in the amount of required tokens.

If someone goes all in and one other person accepts, then the cards
of both players are shown.

Game draws 3 random cards and show it to the players.
Steps 4 to 5 are repeated to the player who didn't fold.
Game draws 1 more card and show it to the players
Steps 4 to 5 are repeated to the players who didn't fold.
Game draws 1 more card and show it to the players.
One player wins the lot
Repeat until one player is left.

Is this the correct loop? Is there anything to add or modify? Can you make this clearer?


texts: Circle Collision Resolution and Angular Momentum

texts:
I have a 2D engine working pretty well that involves rectangles and circles.  I just reworked parts of the collision detection/response system for better handling of angular speed/momentum.

The collision response algorithm I'm using is described here: http://www.myphysicslab.com/collision.html (the complicated "j = ..." equations towards the bottom of the page under "Physics of Collision for Rigid Bodies in 2 Dimensions").

Everything's working great, but I'm wondering about circles.  No matter how another another rectangle or circle hits a circle, it's impossible for the circle to gain angular speed through a collision, since the collision normal vector is always perpendicular to surface of the circle.

This makes sense to me mathematically, but it goes against my real-life intuition.  For example, in the picture below, if I poke a ball on the side with a rectangle (tangentially, not towards the middle of the ball), I expect the ball to start spinning (counter-clockwise in this case).

Why isn't this happening for me?  Do I need some kind of non-instantaneous collision (deformation maybe?) to experience this effect?  If so, is there a way to "fake" it? (Realistically! I don't want to mess up the realistic linear/angular momentums and energies of my system!)  Thanks in advance for the help!!


texts: How to reduce color space in a post-processing material in Unreal Engine 4

texts:
I'm trying to get an old-school Quake 1 look going in UE4.

I am currently using this blueprint in order to get a retro style large pixel filter.

In game (might need to zoom in to see the difference):

The look I am going for now is a low color depth (8 bit etc) that old games such as Quake had. Here is a picture for reference.

Is there any way I can reduce the color space through either a post-processing volume itself or a post-processing material?


texts: Character keeps falling through the terrain and jittering

texts:
I honestly don't know what the problem could be anymore. I have a humanoid character with animations, and a charactercontroller.
I also have a ragdoll (seperately) that only follows the animations through script (doesn't do anything else).
the ragdoll has a script on both feet, with colliders and rigidbody's, and sets a bool to true when either of them hits something.
It also has an update function that casts a ray, and sets that same bool when it hits something. this way i know if it is grounded or not. the charactercontroller is also used to see if it is grounded or not.

In my control script I translate the character downward when it is not grounded, and set that gravity vector to 0 if it is.

the collisions work, the raycasts work, and the charactercontroller work, but still the character falls through.
i've also tried increasing the solver settings, turning off auto simulation and PCM, increasing the contact offset to the point where it floats above the ground, and still falls through.

All the scripts use update functions, but the behaviour is the same in FixedUpdate. I tried with and without rigidbody's in the charactercontroller, and with and without charactercontroller itself.

this part of code is for movement:

bool walking = skaterParams.walking;

            if (walking && !Onboard && !Helper.bailing) {
                moveDirection.y = 0;

                moveDirection = new Vector3(Input.GetAxisRaw("Horizontal"), 0.0F, Input.GetAxisRaw("Vertical"));
                moveDirection = transform.TransformDirection(moveDirection);
                moveDirection *= speed;
                if (Input.GetKeyUp ("joystick button 1")) {
                    moveDirection.y = jumpSpeed  ;

                }

            }

        if (!walking && !Onboard) {
            moveDirection.y -= gravity * Time.deltaTime;
        }
        if (!Onboard  && !Helper.bailing) {
            Char.transform.Translate (moveDirection * Time.deltaTime * 10);
        }

i could also share the code for seeing if he is grounded, but i'm trying to limit the post here, to not have too much text. I just know it works, but it's just not consistent. When setting auto simulation to true, the ragdoll is also extremely jittery...
the ragdoll and character are on seperate layers and cannot collide. The raycasts have a layermask set to the terrain layer.


texts: How to document processes and concepts for a game?

texts:
For the sake of generating a documentation and having a reference for my self, I want to formalize some concepts, behaviors and processes in a proper way.
For example: My game has a game server. This server has to do a reset in some situations. These situations or events could be when all players left the game, the game was lost or one player sends a clear reset intent command.

Now I’m wondering how to formalize that. My first thought was to use a UML-process-diagram. But I have no idea how this should look in a case like the described one (since there are more than just one entry point and also async events).

Maybe I’m wrong and there are better way to formally describe the behavior of some concepts?

Can you give me an example please?


texts: Why do game developers force new players to play a big amount of unranked games before playing ranked?

texts:
I have noticed that CS:GO and Overwatch, two very popular competitive games, force you to play a rather big amount of unranked games and gain a certain "level" before you are allowed to play ranked. CS:GO aso limits the amount of ranked games that you can play per day until you have a rank, forcing you to wait even longer. Many other games do the same, but those two are different in the fact that they have a paywall, a huge one in case of Overwatch.

This means that for a long time a new player is forced to play in unfair teams (as making the teams fairly balanced is the sole benefit of ranked matches). Not only can one team be just stronger than the other, making the game predetermined and boring not matter which team is our newbie in, but there can also be a couple of very experienced players in each of the otherwise fair teams, and those veterans will really be the ones deciding the outcomes of a battle, making the newbies feel useless (as they will actually be useless in this particular match).

It also means that newbies who want to play seriously are mixed with people who want to play for fun (not to win) and troll.

Unranked matches also have an a bit different balance compared to ranked in CS:GO, which means that our newbie can also learn something that is not applicable in ranked matches.

What is the benefit of the game if new players are not allowed into ranked matches right away if they want to try them?

What is the benefit of making unranked balance even slightly different from ranked?


texts: Should input be per-frame or per-update?

texts: I'm implementing a GUI system to look around a 2D tile-based world. At the moment, I'm updating it every time the mouse moves (which happens to be per frame, since that's when it polls for events). However, I'm wondering if implementing it per-update (by taking all input events, averaging them out, then deferring them for processing until the next update) would be better. I figure it would make the GUI feel more consistent but at the cost that it may not be as responsive (since I can't interpolate the movement without the controls feeling "sticky"). In terms of creative a better interface, which should I go with? What do games normally go with?


texts: Soft body plasticity using Bullet Physics

texts:
I made this post on the Bullet forum(link), but the forum is slow so I'm just copying the text from there.

Hello,

I'm currently working on a game and I want to make certain surfaces of the game world deformable by the user. I've already implemented soft bodies and mouse picking but I cant get the surfaces to stop returning to their original shape.

I should note that I use joints to keep the soft bodies stationary.

Does anyone know which settings I need to play with to get the desired effect? I'm very new to soft bodies so I don't understand a lot of the terms in the source code.

If bullet does not have the capabilities I need, does anyone know where I can read up on the topic and soft bodies in general?


texts: Collaborations with colleges? How do you make them work?

texts:
I am a graphic artist and not a modeler or a programmer. For the last few months I have been developing the concept for a game, but could not find a proper team of collaborators to make a demo. Then, as luck would have it, I met a group of people from a local Design College that has a new degree in Game Design. After a brief chat with the program’s Director, he seems really interested in coming to an agreement. Most of his students need an actual project to work on for their final year, and I need a team to make a demo…

So it works out great for both of us. I am trying to make a formal meet with the school’s administration to reach a formal agreement. Just one thing I am not sure of.

Who owns the project?

After everything is said and done, the end result is a demo and a Game Design Doc what will be presented to a publisher, but who owns the rights to the game?

I know the answer technically is “who ever is agreed upon in the collaboration contract” but how does these collabs usually work?


texts: "Marching cubes" voxel terrain - triplanar texturing with depth?

texts: I am currently working on a voxel terrain that uses the marching cubes algorithm for polygonizing the scalar field of voxels. I am using a triplanar texturing shader for texturing. say I have a grass texture set to the Y axis and a dirt texture for both the X and Z axes. Now, when my player digs downwards, it still appears as grass. How would I make it to appear as dirt? I have been thinking about this for a while, and the only thing I can think of to make this effect, would be to mark vertices that have been dug with a certain vertex color. When it has that vertex color, the shader would apply that dirt texture to the vertices marked. Is there a better method?


texts: SpriteBatch.Begin() making my model not render correctly

texts:
I was trying to output some debug information using DrawString when I noticed my model suddenly was being rendered like it was inside-out (like the culling had been disabled or something) and the texture maps weren't applied

I commented out the DrawString method until I only had SpriteBatch.Begin() and .End() and that was enough to cause the model rendering corruption - when I commented those calls out the model rendered correctly

What could this be a symptom of? I've stripped it down to the barest of code to isolate the problem and this is what I noticed.

Draw code below (as stripped down as possible)

        GraphicsDevice.Clear(Color.LightGray);
        foreach (ModelMesh mesh in TIEAdvanced.Meshes)
        {
            foreach (Effect effect in mesh.Effects)
            {
                if (effect is BasicEffect)
                    ((BasicEffect)effect).EnableDefaultLighting();
                effect.CurrentTechnique.Passes[0].Apply();
            }
        }

        spriteBatch.Begin();
        spriteBatch.DrawString(spriteFont, "Camera Position: " + cameraPosition.ToString(), new Vector2(10, 10), Color.Blue);
        spriteBatch.End();

        GraphicsDevice.DepthStencilState = DepthStencilState.Default;
        TIEAdvanced.Draw(Matrix.CreateScale(0.025f), viewMatrix, projectionMatrix);


texts: Get the dropped object using IDropHandler.OnDrop

texts:
In Canvas, I drag some UI objects to a panel using this code:

public void OnDrag(PointerEventData eventData)
{
   Vector3 screenPoint = Input.mousePosition;
   screenPoint.z = 10.0f;
   Item2Drag.position = Camera.main.ScreenToWorldPoint(screenPoint);
}

But what I can't figure out is when I dropped an object on the panel, how can I get the gameObject which has been dropped?


texts:
Kill X number of monsters.
Gather Y number of items (usually by killing X number of monsters).
Deliver this NPC's package to this other NPC who is far far away.
etc.

Yeah. These quests are easy to implement, easy to complete, but also very boring after the first few times. It's kind of disingenuous to call them quests really; they're more like chores or errands.

What ideas for quests have people seen that were well designed, immersive, and rewarding? What specific things did the developers do that made it so?

What are some ideas you would use (or have used) to make quests more interesting?


texts: How do I set up in-app purchasing in iOS?

texts: I am using Unity and I developing an app for iOS. How do I implement in-app purchases that work world-wide?


texts:
What are some tools I can use to create 2d tile based maps?

Please provide the information below, and try to limit to one tool per answer.

Name
Link to website
General features
Export format
Anything else you deem noteworthy


texts: Normal map causing certain faces to get shaded

texts:
I added a normal map to a MR arch & design material in Max 2012. I have a specular in the reflection color slot and a diffuse in the diffuse slot. As i increase the intensity of the normal map i certain faces get darker and they get really "obvious". Last time i was fiddling with this the exact same thing happened which made me quit normal maps and all. Some UV's are overlapping and the normal map is made with the Nvidia photoshop plugin. My scene just has a daylight system with a MR sun and MR sky.

Does anyone have an idea what is causing this?

As you can see the face gets shadowed as a whole. The face next to it has the same problem on the opposite corner you see the same effect but much less hard.


texts: How do 3D game engines render 3D environments to a 2D screen?

texts: For 2D sprite games, I can understand that sprites move on the X and Y axis. However, for 3D games, how do game engines calculate how to render a 3D environment on to a flat 2D computer monitor?


texts: EditorApplication.SaveScene followed by EditorWindow.Close throws InvalidOperationException

texts:
I'm making a really basic custom editorwindow that has a textbox for a scene name, creates a scene with that name and closes itself. Trimmed down to the essence it looks like this:

public void OnGUI()
{
    if (!GUILayout.Button("Create")) return;

    if (CreateScene())
    {
        Close();
    }
}

private bool CreateScene()
{
    var path = string.Format("{0}/{1}.unity", Application.dataPath, "bug");
    EditorApplication.NewScene();
    return EditorApplication.SaveScene(path);
}

This throws an InvalidOperationException

InvalidOperationException: Operation is not valid due to the current state of the object
System.Collections.Stack.Peek () (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Collections/Stack.cs:321)
UnityEngine.GUILayoutUtility.EndLayoutGroup () (at C:/BuildAgent/work/d63dfc6385190b60/artifacts/EditorGenerated/GUILayoutUtility.cs:223)
UnityEngine.GUILayout.EndVertical () (at C:/BuildAgent/work/d63dfc6385190b60/artifacts/EditorGenerated/GUILayout.cs:266)
UnityEditor.HostView.OnGUI () (at C:/BuildAgent/work/d63dfc6385190b60/Editor/Mono/GUI/DockArea.cs:135)

When I remove either the save or the close, the exception doesn't rise.
My guess is the project window needs to finish refreshing somehow.

UPDATE

Tried a frame of delay
Tried AssetDatabase.Refresh()
Tried GUILayout.EndVertical()
Filed a bug
Bugtrack: http://fogbugz.unity3d.com/default.asp?668833_nmit48pnb2fivo27

Any advise?


texts:
Suppose I have an array of 5 objects, each time the touches the screen I generate a new array and save the previous objects in another array.

Is there a way to check if the object align perfectly on only axis with a reasonable error margin and detect objects wrongfully aligned?

I could do it using mathematics but I want to see if I could take advantage of overlaps in Libgdx or a similar method.


texts: How can I load textured objects in jMonkey?

texts:
I am working on a project in jMonkey, and I managed to create boxes, spheres and such objects, and load textures form image files, but when I converted a Blender file to .j3o and imported it in my game, it shows up with no textures (it's just white).

The object does have textures, and they even show up in the jMonkey SDK. How do I load the textures that are already stored in the object file?


texts: Stop rotating when select the game object by mouse input

texts:
I am new to Unity and I am confused about how to solve this problem. Initially, I want to make a platform rotate to its center vector up like this.

transform.Rotate (Vector3.up, speed * Time.deltaTime);

Then, I want to stop it from rotating when the mouse select it, like:

Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast (ray, out hit)){
  //find a way to stop rotate
}

I cannot figure out how to stop it from rotating. Can anyone help me, please?


texts: Cutting out smaller rectangles from a larger rectangle

texts:
The world is initially a rectangle. The player can move on the world border and then "cut" the world via orthogonal paths (not oblique).
When the player reaches the border again I have a list of path segments they just made.

I'm trying to calculate and compare the two areas created by the path cut and select the smaller one to remove it from world.

After the first iteration, the world is no longer a rectangle and player must move on border of this new shape.

How can I do this?
Is it possible to have a non rectangular path? How can I move the player character only on path?

EDIT

Here you see an example of what I'm trying to achieve:

Initial screen layout.
Character moves inside the world and than reaches the border again.
Segment of the border present in the smaller area is deleted and last path becomes part of the world border.
Character moves again inside the world.
Segments of border present in the smaller area are deleted etc.


texts: 3D Flight with pure local rotation without roll creep

texts:
I'm working on a flight race game with a specific constraint and cannot find a solution.
Hereinbelow, an image of a test scene.

My ship has a cylinder (children) in front of it from which I get a TargetYaw and a TargetPitch. Each of them is clamp between [-1,1]. After, I update my yaw and pitch angle of my parent object using this values.

private void UpdateYaw()
{
    _deltaYaw = Mathf.Lerp(_deltaYaw, _targetYaw, _yawAcceleration * Time.deltaTime);
    _yawAngle += _deltaYaw * _yawSpeed * Time.deltaTime;
}

private void UpdatePitch()
{
    _deltaPitch = _targetPitch;
    _pitchAngle = Mathf.LerpAngle(_pitchAngle, -(_deltaPitch * _pitchMaxAngle), _pitchAcceleration * Time.deltaTime);
}

This is where my constraint happens. My flying object upward vector must be align with the normal vector of the road it is following. But, at the same time, I need to keep the same controls over it. Hereinbelow how I get the angle to make this happens.

// hover
float _targetRoll = 0;
float _rollAngle = 0;
public float _rollAcceleration = 2;
private int layermask = (1 << 8);
private Vector3 oldDown = Vector3.down;
private Quaternion toRotation = Quaternion.identity, targetRotation = Quaternion.identity;
void UpdateHoverRoll()
{
    RaycastHit hit;

    if (Physics.Raycast(transform.position, oldDown, out hit, Mathf.Infinity, layermask) == true)
    {
        toRotation = Quaternion.LookRotation(transform.forward, hit.normal);
        oldDown = -transform.up;
        LocalRotationTarget = toRotation.eulerAngles.z;
    }
    _rollAngle = Mathf.Lerp(_rollAngle, _targetRoll, Time.deltaTime * _rollAcceleration);
}

So, now that I got my 3 angles I need to find a rotation system which after I apply my roll, pitch and yaw do not change how I control my ship. If I roll to 90 degrees, I must still yaw around my local up vector and pitch around my local right vector (my control don't get inverse) for exemple. Here an example of what i tried:

private void UpdateRotation()
{
    Quaternion q = Quaternion.AngleAxis(_turnAngle, Vector3.Normalize( Quaternion.Euler(0, 0, LocalRotation) * Vector3.up))
                   * Quaternion.AngleAxis(_pitchAngle, Vector3.Normalize(Quaternion.Euler(0,0,LocalRotation) * Vector3.right))
                   * Quaternion.AngleAxis(LocalRotation, Vector3.forward);
    transform.rotation = Quaternion.Lerp(transform.rotation, q, 1);
}

Thank you in advance.

PS : I am having difficulties to write this because my English skill are kinda low. Hopefully, it is still understandable, if not don't hesitate to ask/tell me.


texts: vkCmdCopyBuffer has no effect for transfer of staging buffer

texts:
for a vulkan renderer using vulkan-hpp and Vulkan Memory Allocator I am trying to transfer vertex data to the gpu using a staging buffer.
Without using an intermediary staging buffer the transfer works and the meshes can be rendered
with no problems (just a single buffer created with VMA_MEMORY_USAGE_CPU_TO_GPU).
But with the call to vkCmdCopyBuffer the resulting vertexBuffer only contains 0s (checked with NSight).
Thinking that synchronisation using barriers might be required I tried the following code, but still have the same problem.

Maybe there is a need to synchronize the command buffer doing the copy with the later command buffer binding and sourcing from the vertex buffer? Although I didnt see this done or mentioned in any tutorials I came across.

// vulkan initialization
// VmaAllocator initialization

std::vector<Vertex> vertices = { /*filled*/ };
auto vertexBufferSize = vertices.size() * sizeof(Vertex);

vk::Buffer stagingBuffer;
auto ci = vk::BufferCreateInfo().
    setUsage(vk::BufferUsageFlagBits::eTransferSrc).
    setSharingMode(vk::SharingMode::eExclusive).
    setSize(vertexBufferSize );
VmaAllocationCreateInfo allocationCI = {};
allocationCI.usage = VMA_MEMORY_USAGE_CPU_ONLY;
vmaCreateBuffer(allocator, (VkBufferCreateInfo*)&ci,
    &allocationCI, (VkBuffer*)&stagingBuffer, &allocation, nullptr);
void* pVBufMem = nullptr;
vmaMapMemory(allocator, allocation, &pVBufMem);
std::memcpy(pVBufMem, vertices.size(), vertexBufferSize );
vmaUnmapMemory(allocator, allocation);

vk::Buffer vertexBuffer;
ci = vk::BufferCreateInfo().
    setUsage(vk::BufferUsageFlagBits::eTransferDst | vk::BufferUsageFlagBits::eVertexBuffer).
    setSharingMode(vk::SharingMode::eExclusive).
    setSize(vertexBufferSize);
allocationCI = {};
allocationCI.usage = VMA_MEMORY_USAGE_GPU_ONLY;
vmaCreateBuffer(allocator, (VkBufferCreateInfo*)&ci,
    &allocationCI, (VkBuffer*)&vertexBuffer, &allocation, nullptr);

// copy staging buffer to vertex buffer
auto allocCI = vk::CommandBufferAllocateInfo().
    setCommandBufferCount(1).
    setCommandPool(pool).
    setLevel(vk::CommandBufferLevel::ePrimary);
auto cmd = device.allocateCommandBuffers(allocCI)[0];
cmd.begin({ vk::CommandBufferUsageFlagBits::eOneTimeSubmit });

// barrier host write -> copyBuffer read
auto bufferMemoryBarrier = vk::BufferMemoryBarrier()
.setBuffer(stagingBuffer)
.setSize(vertexBufferSize)
.setSrcAccessMask(vk::AccessFlagBits::eMemoryWrite)
.setDstAccessMask(vk::AccessFlagBits::eTransferRead)
.setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED);
cmd.pipelineBarrier(
    vk::PipelineStageFlagBits::eAllCommands, vk::PipelineStageFlagBits::eAllCommands, {},
    { }, { bufferMemoryBarrier }, { });

cmd.copyBuffer(stagingBuffer, vertexBuffer, { 0, 0, vertexBufferSize });

// copyBuffer write -> vertex read
bufferMemoryBarrier = vk::BufferMemoryBarrier()
.setBuffer(vertexBuffer)
.setSize(vertexBufferSize)
.setSrcAccessMask(vk::AccessFlagBits::eTransferWrite)
.setDstAccessMask(vk::AccessFlagBits::eVertexAttributeRead)
.setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED);
cmd.pipelineBarrier(
    vk::PipelineStageFlagBits::eAllCommands, vk::PipelineStageFlagBits::eAllCommands, {},
    { }, { bufferMemoryBarrier }, { });

cmd.end();
auto submitInfo = vk::SubmitInfo().
    setCommandBufferCount(1).
    setPCommandBuffers(&cmdBuffer);
queue.submit({ submitInfo }, {});
queue.waitIdle();