texts: Unity multyplayer change player prefab on scene change

texts:
How do you change player prefab with mirror network? I have tried this but its not working, atleast not on switching scenes.
My current code is:
 public void switchScene()
    {
        ServerChangeScene(gameScene);
    }

    public override void OnServerSceneChanged(string sceneName)
    {
        foreach (NetworkConnectionToClient conn in NetworkServer.connections.Values)
        {
            GameObject obj = conn.identity.gameObject;

            NetworkServer.ReplacePlayerForConnection(conn, Instantiate(shipPrefab));

            NetworkServer.Destroy(obj);
        }
    }

I have also tried OnClientSceneChanges but i always keep getting the same error:
MissingReferenceException: The object of type 'NetworkIdentity' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
LobbyManager.OnServerSceneChanged (System.String sceneName) (at Assets/LobbyManager.cs:56)
Mirror.NetworkManager.FinishLoadSceneHost () (at Assets/Mirror/Runtime/NetworkManager.cs:1011)
Mirror.NetworkManager.FinishLoadScene () (at Assets/Mirror/Runtime/NetworkManager.cs:953)
Mirror.NetworkManager.UpdateScene () (at Assets/Mirror/Runtime/NetworkManager.cs:936)
Mirror.NetworkManager.LateUpdate () (at Assets/Mirror/Runtime/NetworkManager.cs:274)

Running around in the source code of mirror shows, that at somepoint the existing prefab is destroyed and then recreated once new scene has loaded. But i want the new scene to have a new player prefab. How or when can i change the player prefab for connection?
And trying to switch character without scene change also gives error.
public void ChangeCharacter()
    {
            GameObject obj = NetworkClient.connection.identity.gameObject;

            NetworkServer.ReplacePlayerForConnection(NetworkClient.connection, Instantiate(shipPrefab));

            NetworkServer.Destroy(obj);

    }

Error
InvalidCastException: Specified cast is not valid.
Mirror.NetworkIdentity.SetClientOwner (Mirror.NetworkConnection conn) (at Assets/Mirror/Runtime/NetworkIdentity.cs:362)
Mirror.NetworkServer.InternalReplacePlayerForConnection (Mirror.NetworkConnection conn, UnityEngine.GameObject player, System.Boolean keepAuthority) (at Assets/Mirror/Runtime/NetworkServer.cs:837)
Mirror.NetworkServer.ReplacePlayerForConnection (Mirror.NetworkConnection conn, UnityEngine.GameObject player, System.Boolean keepAuthority) (at Assets/Mirror/Runtime/NetworkServer.cs:697)
LobbyManager.ChangeCharacter () (at Assets/LobbyManager.cs:56)
UnityEngine.Events.InvokableCall.Invoke () (at <e8645a79b0794e0e9a2b5bbff081b88a>:0)
UnityEngine.Events.UnityEvent.Invoke () (at <e8645a79b0794e0e9a2b5bbff081b88a>:0)
UnityEngine.UI.Button.Press () (at C:/Program Files/Unity/Hub/Editor/2020.1.4f1/Editor/Data/Resources/PackageManager/BuiltInPackages/com.unity.ugui/Runtime/UI/Core/Button.cs:68)
UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at C:/Program Files/Unity/Hub/Editor/2020.1.4f1/Editor/Data/Resources/PackageManager/BuiltInPackages/com.unity.ugui/Runtime/UI/Core/Button.cs:110)
UnityEngine.EventSystems.ExecuteEvents.Execute (UnityEngine.EventSystems.IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at C:/Program Files/Unity/Hub/Editor/2020.1.4f1/Editor/Data/Resources/PackageManager/BuiltInPackages/com.unity.ugui/Runtime/EventSystem/ExecuteEvents.cs:50)
UnityEngine.EventSystems.ExecuteEvents.Execute[T] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.ExecuteEvents+EventFunction`1[T1] functor) (at C:/Program Files/Unity/Hub/Editor/2020.1.4f1/Editor/Data/Resources/PackageManager/BuiltInPackages/com.unity.ugui/Runtime/EventSystem/ExecuteEvents.cs:261)
UnityEngine.EventSystems.EventSystem:Update() (at C:/Program Files/Unity/Hub/Editor/2020.1.4f1/Editor/Data/Resources/PackageManager/BuiltInPackages/com.unity.ugui/Runtime/EventSystem/EventSystem.cs:376)


texts: Unity Input System On-Screen Button doesn't work with touchscreen 2019.3.2f1

texts:
I am trying to make my player jump whenever the space button is pressed (if a keyboard is present), and I'm adding a on-screen button for players on mobile. The on-screen button works fine in the editor but when I try the game in a device the on-screen button doesn't work.

Here's how things are set up:

Change the Active Input Handling to Input System Package (New) on
the player settings.
Create the Jump action for the Player action map.
Bind <Keyboard>/space to my Jump action.
Add a PlayerInput component to my player object, pass my actions
file to it, and set up the events to call for each action.
Change the StandaloneInputModule to an InputSystemUIInputModule in my
event system object.
In my canvas I add an image and add OnScreenButton component to it (I
do NOT add a Button component).
Set the control path to <Keyboard>/space.

When I try the game on the device the rest of the UI buttons work fine except the on-screen button. On the editor though (using mouse input), the on-screen button works fine.
This is my first time using the Input System, I had actually found it somewhat nice to work with, however this does seem really strange. It is either a really strange bug (unlikely), or I messed up some setting (the setup process feels really convoluted actually).


texts: "Instantiate" function in Unity spawns enemy but it doesn't show up

texts:
So, I'm making a top down shooter (2D) and I already made an enemy prefab. It walks to the player and damages it, and reacts to bullets physically until it eventually dies. The prefab itself is ok, because I can spawn it manually and it works as intended. The problem comes when I want to automate the spawn process with a script. So I made a script to do so, here it is:

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

public class GameController : MonoBehaviour
{

    public GameObject enemy;

    private float spawnPositionX;
    private float spawnPositionY;

    Vector2 spawnVector;

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

    void SpawnEnemy()
    {
        spawnPositionX = Random.Range(-630f, 630f);
        spawnPositionY = Random.Range(-340f, 340f);

        spawnVector = new Vector2(spawnPositionX, spawnPositionY);

        Instantiate(enemy, spawnVector, Quaternion.identity);
    }
}

As you can see, it's nothing too complex. I just refer to a game object (which I linked by the way) and then create some variables that will hold the x and y positions in which the enemy will spawn at random. Then when I call the function, those positions get set and stored into a bi-dimensional vector to then be used with the instantiate function.

This... works... kinda? When I run the game, the instance of the enemy gets made, I can see the clone in the hierarchy and I can select it and see that it's indeed moving, but it's like... not there? I can't actually see it on the screen and it's not invisible as I can't interact with it either. It's really weird and I have no idea what's going on.

I tried to put the script on the camera, on the canvas, on a new empty object, nothing. I also checked that the prefab and the instance that's being spawned are indeed active. I thought about the coordinates being out of bounds, but when I check my player coordinates they are inbounds, so that can't be it either. I'm completely lost on this one, thoughts? Thanks.


texts:
I have this problem: I'm trying to create new RelativeLayout over whole screen - which also contains SurfaceView in the middle - and display some things on this RelativeLayout (in my case Imageview containing animation). Almost everything is working ok - Imageview is displayed, animation is working... but SurfaceViews drawings (Bitmaps) are on the top of my RelativeLayout with Imageview, which I'm trying to appear it on top.

Calling bringtofront() doesn't work. Although I've created RelativeLayout with ImageView after SurfaceView, it's still below it.

So my question is: how to bring this RelativeLayout with ImageView to the top of SurfaceView?

In Activity:

// Layout, on which I'm adding Surfaceview programmatically
RelativeLayout layout = (RelativeLayout) findViewById(R.id.middle_layout);
layout.addView(new SurfaceView((getApplicationContext())));

// Layout which should be top over everything
RelativeLayout topLayout = new RelativeLayout(getApplicationContext());
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
                                 RelativeLayout.LayoutParams.MATCH_PARENT,
                                 RelativeLayout.LayoutParams.MATCH_PARENT);
topLayout.setLayoutParams(rlp);

// Although I'm adding SurfaceView first and Relative second, no hierarchy order is visible...
layout.addView(topLayout);
// OR
root_layout.addView(topLayout);
// ^ Both attempts are displayed under SurfaceView

SurfaceView class:

public class SurfaceView extends SurfaceView implements SurfaceHolder.Callback
{
    public SurfaceView (Context context)
    {
            super(context);

            getHolder().addCallback(this);

            this.setZOrderOnTop(true);

            getHolder().setFormat(PixelFormat.TRANSPARENT);

            setFocusable(true);
    }

    ...
}

PS: I need to create SurfaceView programmatically.

Thanks for any help!


texts: How do I use the dot product to get an angle between two vectors?

texts:
I am learning to use normalized vectors in my games.

I've learned that in order to know the angle between two vectors, I can use the dot product. This gives me a value between -1 and 1, where

1 means the vectors are parallel and facing the same direction (the angle is 180 degrees).
-1 means they are parallel and facing opposite directions (still 180 degrees).
0 means the angle between them is 90 degrees.

I want to know how to convert the dot product of two vectors, to an actual angle in degrees. For example, if the dot product of two vectors is 0.28, what is the corresponding angle, between 0 and 360 degrees?


texts: Rotate an object on itself, from one random Quaternion to another

texts:
I have a situation:
I have a 3D object in the world. let's say a sphere.
I have 2 random directionnal vector: vector A, and vectorB:

My question is: How to I rotate over time my object, from A to B ?
The vector A is important: I don't want to simply rotate the forward of the object from current forward to B.

I know I can use the function vector3 C = Vector3.SmoothDamp(...) in unity to lerp between my 2 vectors A & B.

but then ok, I have vector3 C, how do I apply the rotationof my object to C ?
if don't want to do:
gameObject.transform.forward = C;

I want something like:
gameObject.transform.rotation = SomeQuaternion(C, initial rotation A).
or something.

Thank you for help !

PS: I don't want to parent / unparent gameObject or something like that, i want the math answer, using Quaternion.


texts: Higher order splines for use with pathfinding

texts:
In this page, Amit explains that splines can be used to achieve movement on a found path.

In the picture below, he explains that:

  The blue paths use splines, with dark blue being low order splines and
  light blue being a higher order spline.

What are exactly high order splines? How to achieve the light blue movement?


texts: How do I make educational games engaging not boring?

texts:
We make educational games for school students, age 7-18; we can't have any violence or blood in them.

I have scoured Google Play and YouTube for good examples of educational games.

So far I found this math game. The cannon fires at number-enemies, to score, the player should bring their values to exactly zero.
As levels advance, the bigger numbers occur - 10, 20, 30, etc.

Why is it hard to make educational games that are not boring? It seems violence is what attracts most young people nowadays!
One big exception could be puzzles.


texts:
I've made a chips bag model for my game:

http://imgur.com/JcumRF4

And I textured it like this:

http://imgur.com/wpyeACZ

and I googled on how to make lightmaps all of them say "Smart UV project" but when I do that, texture on my model gets broken, so thats why I dont want to use smart uv project

Is there another way?, it has to be.


texts: Limiting interaction between certain RigidBodies

texts:
I'm developing a 2D game in Unity and have been tasked with building a particular feature I'm not sure how to accomplish with Unity's physics engine. To simplify, a bunch of objects of type X and O are filled into a pit:

XXXXXXXXXXXX
XXXXXXXXXXXX
XXXXXXXXXXXX
XXoXXXoXXXoX

Both objects have Rigidbody2Ds and colliders. Objects of type X have normal gravity and should settle into place. Objects of type O have inverse gravity and should float.

However, O should not be able to push X, and X should not be able to push O. Another way of looking at it is that O should only be able to move upward, and X should only be able to move downward. If we remove some of the Xs directly above an O, the O should float upwards as the Xs fall downwards until the Xs settle on top of the O and everything stops moving:

XXXXXXXXXXXX        XX XXXXXXXXX
XX XXXXXXXXX   -->  XXXXXXXXXXXX
XX XXXXXXXXX   -->  XXoXXXXXXXXX
XXoXXXoXXXoX        XX XXXoXXXoX

(In the actual game Xs and Os can be different sizes; their movement is continuous and they are not constrained into rows or columns).

The Os should be able to support the weight of any arbitrary number of Xs without sinking.

XXXXXXXXXXXX
XXXXXXXXXXXX
XooooooooooX
X          X

Lastly, the Os should be able to float diagonally if there is a space available:

XXXX XXXXXXX      XXX       XX
XXXXX     XX  --> XXXXX   XXXX
XXXX    XXXX  --> XXXXoXXXXXXX
XXXo XXXXXXX      XXXX XXXXXXX

I can't solve this problem simply by adjusting the mass of the Xs or Os since the number of Xs on top of an O may vary. I can't use the built-in RigidBody constraints since they don't allow you to disable only one direction along an axis (e.g. saying an object can move upward but not downward).

What's the proper way to handle this? I could do something like this:

void FixedUpdate() {
    if (movementDirection == Direction.UP) {
        if (transform.position.y < lastYCoordinate) {
            Vector3 position = transform.position;
            position.y = lastYCoordinate;
            transform.position = position;
        }
    }
    lastYCoordinate = transform.position.y;
}

but that feels hacky to me and I suspect it will keep the objects from sleeping. Are there better solutions here?


texts: Can one draw a cube using different method/drawing mode?

texts:
I've just started learning gamedev (in particular android EGL based) and have ran over a code from Pro Android Games 2 that looks as follows:

  /*  * Copyright (C) 2007 Google Inc.
  *  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.  * You
  may obtain a copy of the License at  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *  * Unless required by applicable law or agreed to in writing, software  *
  distributed under the License is
  distributed on an "AS IS" BASIS,  *
  WITHOUT WARRANTIES OR CONDITIONS OF
  ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and  *
  limitations under the License.  */

  package opengl.scenes.cubes;

  import java.nio.ByteBuffer; import
  java.nio.ByteOrder; import
  java.nio.IntBuffer;

  import javax.microedition.khronos.opengles.GL10;

  public class Cube {

public Cube(){

    int one = 0x10000;
    int vertices[] = {
            -one, -one, -one,
            one, -one, -one,
            one,  one, -one,
            -one,  one, -one,
            -one, -one,  one,
            one, -one,  one,
            one,  one,  one,
            -one,  one,  one,
    };

    int colors[] = {
            0,    0,    0,  one,
            one,    0,    0,  one,
            one,  one,    0,  one,
            0,  one,    0,  one,
            0,    0,  one,  one,
            one,    0,  one,  one,
            one,  one,  one,  one,
            0,  one,  one,  one,
    };

    byte indices[] = {
            0, 4, 5,    0, 5, 1,
            1, 5, 6,    1, 6, 2,
            2, 6, 7,    2, 7, 3,
            3, 7, 4,    3, 4, 0,
            4, 7, 6,    4, 6, 5,
            3, 0, 1,    3, 1, 2
    };

    // Buffers to be passed to gl*Pointer() functions
    // must be direct, i.e., they must be placed on the
    // native heap where the garbage collector cannot vbb.asIntBuffer()
    // move them.
    //
    // Buffers with multi-byte datatypes (e.g., short, int, float)
    // must have their byte order set to native order

    ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length*4);
    vbb.order(ByteOrder.nativeOrder());
    mVertexBuffer = vbb.asIntBuffer();
    mVertexBuffer.put(vertices);
    mVertexBuffer.position(0);

    ByteBuffer cbb = ByteBuffer.allocateDirect(colors.length*4);
    cbb.order(ByteOrder.nativeOrder());
    mColorBuffer = cbb.asIntBuffer();
    mColorBuffer.put(colors);
    mColorBuffer.position(0);

    mIndexBuffer = ByteBuffer.allocateDirect(indices.length);
    mIndexBuffer.put(indices);
    mIndexBuffer.position(0);
}

public void draw(GL10 gl)
{
    gl.glFrontFace(GL10.GL_CW);
    gl.glVertexPointer(3, GL10.GL_FIXED, 0, mVertexBuffer);
    gl.glColorPointer(4, GL10.GL_FIXED, 0, mColorBuffer);
    gl.glDrawElements(GL10.GL_TRIANGLES, 36, GL10.GL_UNSIGNED_BYTE, mIndexBuffer);
}

private IntBuffer   mVertexBuffer;
private IntBuffer   mColorBuffer;
private ByteBuffer  mIndexBuffer;}

So it suggests to draw a cube using triangles. My question is: can I draw the same cube using GL_TPOLYGON? If so, isn't that an easier/more understandable way to do things?


texts:
I know about several of path-finding algorithms that exist: depth-first search, Dijkstra's algorithm, A* etc.

Now I would like an algorithm that gives me the N paths with lowest cost. Can this be obtained by some simple modification of one of the above? Or is a different algorithm needed, and if so which?


texts:
We currently have a simple slot machine in our online virtual world game.

You set the amount you want to bet (in virtual money) and pull the lever, and depending on the 3 figures (there's only one line) you get a reward, a free round, lose some more money, or most of the time, get nothing at all. You can instantly pull the lever again. The previous bet will be maintained.

At the moment this slot machine isn't really fun to play. The chances of winning something are pretty low (though when you win, you can win a lot). When you pull the lever, the result is determined (though not shown) immediately, so there's also no way influence the outcome of the wheels.

How can it be made more fun?


texts: How can I render a shiny, metallic surface?

texts:
I am creating a game for which I want to render a kind of shiny black metallic surface with some refection property in it. I know that there would be something related to masks involved with it. But somehow I am not able to get started on it.

So could someone give me insight in the matter or give a link to a good tutorial?


texts: How to create reproducible probability in map generation?

texts:
So for my game, I'm using perlin noise to generate regions of my map (water/land, forest/grass) but I'd also like to create some probability based generation too. For instance:

if(nextInt(10) > 2 && tile.adjacentTo(Type.WATER))
    tile.setType(Type.SAND);

This works fine, and is even reproduceable (based on a common seed) if the nextInt() calls are always in the same order. The issue is that in my game, the world is generated on demand, based on the player's location. This means, that if I explore the map differently, and the chunks of the map are generated in a different order, the randomness is no longer consistent.

How can I get this sort of randomness to be consistent, independent of call order?

Thanks in advance :)


texts:
In OpenGL (ES 2.0), there are many functions that can be called in any order, and still others that must be called after other functions had been called and not before.
For example, attaching a shader to a program requires a valid program so glAttachShader must be called after a call to glCreateProgram().  glCreateProgram() must be called after GL initialization etc.
Any functions that assume a certain "current" state, depend on the functions that set this state previously (defaults notwithstanding).
Such a dependencies necessary conditions for correct functioning (but not necessarily sufficient).

Is there a document or diagram somewhere that explicitly shows these dependencies and independencies?
All I found were the occasional implicit mention in the texts.

This would be very helpful for debugging, learning and understanding the framework structure and also for developing higher-level tools that abstract away some of the low-level complexity.


texts: How can I implement a "Nyan Cat" rainbow?

texts:
I'm currently making a game similar to this Nyan Cat flash game, although I'm using cocos2d. I'm having a hard time trying to make the rainbow effect:

Currently, every update call I add a piece of rainbow on screen and move it back, having also added it into a special array. When a player changes its y coordinate I rotate all the added spites by a certain calculated value.

Honestly, it looks... not perfect and I've been wondering if there is better way?


texts: Spaceship interiors: How to approach, implementation-wise?

texts:
I'm creating a 3D space game using Ogre3D for graphics with C++ and one of the features is to be able to freely wander around spaceship interiors, but I am lost with how to implement it. Here is what I can think of so far:

A single model of the spaceship that has an interior modelled too, but somehow double-sided and double-normalled? Not sure if this is possible!
Two models, one of the spaceship outside and one of the interior with flipped normals, when in game the interior model is placed inside the spaceship mesh, but that wouldn't be very flexible (different spaceship sizes, hull thickness etc)
Two models, when a player enters the space ship the screen fades and their view is switched to the inside model where the windows are live render textures of their respective place on the outside part of the spaceship, but it wouldn't be very optimised (rendering to several textures) and wouldn't have the gameplay aesthetic of smoothly entering or exiting (possibly via explosion) the ship

So, GameDev, how would you approach this?


texts: ASP.NET MVC & SQL Server vs. PHP & MySql

texts:
I'm going to develop a strategy browser-based game with ASP.NET MVC and SQL Server.

However, as I explored the web to get some ideas and patterns from existing games, I found out that none of them developed by .NET tools.

So, it made a question for me that what's the reason behind this...:

1) Is there any big draw back for microsoft technologies in this area?

2) Why all of games in this field are developed with PHP & (maybe1?) MySql?

3) Is there any performance issue with above mentioned microsoft technologies in this area?

Thanks in advance


texts:
I'm struggling to make the sprites avoid each other and other obstacles in the field. To achieve something like this:

To do so I decided to have a 3D environment with an Orthographic camera. It all looks as I wanted.

I have set up a plane. My sprites have a 3dCollider and a rigidbody as I want them to be affected by physics.

I move the sprites using RigidBody.MovePosition.

I checked the collisions, how far they where from their target position, etc...

I've tried also a few scripts that intend to do something like this, but I think they are not suitable from what I am doing as after adapting them they don't work.

Can somebody give me some guidance on a simple way to do this? I don't want to use a A* pathfinding system as I think it's too complex to what I want to do, but if I have to use one I will... I just need some guidance on this...


texts: iOS game integrated with Facebook - Random game

texts:
How could I implement a random game for iOS via Facebook.  I registered my game with Facebook and done everything so far... Can Facebook do such a thing?

EDIT

I connected my app to Facebook, I can send requests, publish open graphs etc. But i need to connect players to play online via Facebook, such as Bubble Galaxy with Buddies. Do they use Facebook for this? Any tutorial or idea ?


texts: Interaction between GUI and character(s)

texts:
This is more a question about architecture. Not sure if there's a right or wrong:

Let's assume I have some gameobjects:

GUI: A menu containing some elements like "Go to position". It's opened when right clicking in the game
Main Camera
Characters: Characters in the game which can be controlled by the player

Now I was thinking about the following scenarios:

A character is clicked. It's highlighted yellow. This should definitely be done in the script of the character.
When a character is highlighted (or selected) and the right mouse button is clicked, the GUI will be shown. Where does this have to be implemented when talking about clean code? In the character? But then the character has to know about the GUI. I'm not sure if this is clean. In the GUI? Then then the GUI has to know if a character was highlighted (or selected). Doesn't feel clean too.


texts: 3D rotation tool. How can I add simple extrusion?

texts:
The 3D rotation tool is excellent but it only lets you rotate 2D objects, this means my object is wafer thin.

Is there any way to add simple extrusion or depth to a symbol?

I don't really want to use any 3rd party libraries like Away3D or Papervision, this is overkill for my simple 2D game. I only want to do this creating a couple motion tweens if possible.

More Details:

Below is what my symbol looks like (just with a bit more color). The symbol does a little 3D rotation and then flies away, it's just for something like a scoreboard within the app.


texts: Updating connected states in a "build the pipeline" puzzle game

texts:
I'm trying to make the pulse system in a "build the pipeline" puzzle game to check if tiles are connected to the starting tile.

There is a weird bug that prevents tiles on the right and tiles on the top of any powered up tile (including starting one) to change state, but it works fine with tiles on the left and bottom.

I tried to log this and it happened that the cycle is going trough these tiles, but their state doesn't change. Here is an example:

Here is the code. If I remove this bit:

 else
              p.GetComponent<piece>().ConnectedToStart = false;

then it is changing the state as it should, but I have no idea how to disable tiles that should be unpowered in any other way. Also, the question is still there - why does it only work for the tiles on the left and bottom?

    public class Puzzle
    {

        public int winValue;
        public int curValue;

        public int width;
        public int height;
        public piece[,] pieces;

    }

        public Puzzle puzzle;

        GameObject[] pieces;
    void Start()
    {
        pieces = GameObject.FindGameObjectsWithTag("Piece");
    }

    void Update()
    {
        CheckForStartConnections();
    }

    public void CheckForStartConnections()
    {

        foreach (var p in pieces)
        {
            if (p.GetComponent<piece>().StartPiece)
                Pulse((int)p.transform.position.x, (int)p.transform.position.y);
            else
              p.GetComponent<piece>().ConnectedToStart = false;
        }
    }

    void Pulse(int w, int h)
    {
        puzzle.pieces[w, h].GetComponent<piece>().ConnectedToStart = true;
        //compares left
        if (w != 0)
            if (puzzle.pieces[w, h].values[3] == 1 && puzzle.pieces[w - 1, h].values[1] == 1)
            {
                if (!puzzle.pieces[w - 1, h].GetComponent<piece>().ConnectedToStart)
                    Pulse((int)puzzle.pieces[w - 1, h].transform.position.x, (int)puzzle.pieces[w - 1, h].transform.position.y);
            }
        //compares bottom
        if (h != 0)
            if (puzzle.pieces[w, h].values[2] == 1 && puzzle.pieces[w, h - 1].values[0] == 1)
            {
                if (!puzzle.pieces[w, h - 1].GetComponent<piece>().ConnectedToStart)
                    Pulse((int)puzzle.pieces[w, h - 1].transform.position.x, (int)puzzle.pieces[w, h - 1].transform.position.y);
            }
        //compares top
        if (h != puzzle.height - 1)
            if ((puzzle.pieces[w, h].values[0] == 1 && puzzle.pieces[w, h + 1].values[2] == 1))
            {
                if (!puzzle.pieces[w, h + 1].GetComponent<piece>().ConnectedToStart)
                {
                    Pulse((int)puzzle.pieces[w, h + 1].transform.position.x, (int)puzzle.pieces[w, h + 1].transform.position.y);
                }
            }
        //compares right
        if (w != puzzle.width - 1)
            if (puzzle.pieces[w, h].values[1] == 1 && puzzle.pieces[w + 1, h].values[3] == 1)
            {
                if (!puzzle.pieces[w + 1, h].GetComponent<piece>().ConnectedToStart)
                {
                    Pulse((int)puzzle.pieces[w + 1, h].transform.position.x, (int)puzzle.pieces[w + 1, h].transform.position.y);
                }
            }
}
```


texts: Apple App Store: Publish your game under your organization name

texts:
I am in the process of building a mobile game targeting Apple App Store. This is a co-op work done by me and my teammate. We do not want to publish the game under my personal Apple developer account, but rather use our fantasy org name (let's call it a game dev studio).

Is there a way of doing this without going through the hassle of founding a company? Do I need to get another Apple account type (other than individual person)?


texts: Error CS1585: Member modifier 'private' must precede the member type and name

texts:
I've been knocking errors out of my script after working thoroughly through them but this one has me stumped, even though I'm sure it's something really simple. This is the following error that I'm getting:

  Assets\Scripts\Movement_Scripts\FirstPersonCharacter\Scripts\FirstPersonController.cs(44,9):
  error CS1585: Member modifier 'private' must precede the member type
  and name

From my script:

using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
using UnityStandardAssets.Utility;
using Random = UnityEngine.Random;
using MouseLook = UnityEngine.MouseLook;

public class FirstPersonController : MonoBehaviour
{
    [SerializeField] private bool m_IsWalking;
    [SerializeField] private float m_WalkSpeed;
    [SerializeField] private float m_RunSpeed;
    [SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten;
    [SerializeField] private float m_JumpSpeed;
    [SerializeField] private float m_StickToGroundForce;
    [SerializeField] private float m_GravityMultiplier;
    [SerializeField] private MouseLook m_MouseLook;
    [SerializeField] private bool m_UseFovKick;
    [SerializeField] private FOVKick m_FovKick = new FOVKick();
    [SerializeField] private bool m_UseHeadBob;
    [SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob();
    [SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob();
    [SerializeField] private float m_StepInterval;
    [SerializeField] private AudioClip[] m_FootstepSounds;    // an array of footstep sounds that will be randomly selected from.
    [SerializeField] private AudioClip m_JumpSound;           // the sound played when character leaves the ground.
    [SerializeField] private AudioClip m_LandSound;           // the sound played when character touches back on ground.

    private Camera m_Camera;
    private bool m_Jump;
    private float m_YRotation;
    private Vector2 m_Input;
    private Vector3 m_MoveDir = Vector3.zero;
    private CharacterController m_CharacterController;
    private CollisionFlags m_CollisionFlags;
    private bool m_PreviouslyGrounded;
    private Vector3 m_OriginalCameraPosition;
    private float m_StepCycle;
    private float m_NextStep;
    private bool m_Jumping;
    private AudioSource m_AudioSource;
    readonly AudioSource AudioSource;
    public UnityStandardAssets.Characters.FirstPerson.MouseLook

    // Use this for initialization
    private void Start()   /* This is line 44 */
    {
        m_CharacterController = GetComponent<CharacterController>();
        m_Camera = Camera.main;
        m_OriginalCameraPosition = m_Camera.transform.localPosition;
        m_FovKick.Setup(m_Camera);
        m_HeadBob.Setup(m_Camera, m_StepInterval);
        m_StepCycle = 0f;
        m_NextStep = m_StepCycle / 2f;
        m_Jumping = false;
        m_AudioSource = GetComponent<AudioSource>();
        m_MouseLook.Init(transform, m_Camera.transform);
    }

    // Update is called once per frame
    private void Update()
    {
        RotateView();
        // the jump state needs to read here to make sure it is not missed
        if (!m_Jump)
        {
            m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
        }

        if (!m_PreviouslyGrounded && m_CharacterController.isGrounded)
        {
            StartCoroutine(m_JumpBob.DoBobCycle());
            PlayLandingSound();
            m_MoveDir.y = 0f;
            m_Jumping = false;
        }
        if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded)
        {
            m_MoveDir.y = 0f;
        }

        m_PreviouslyGrounded = m_CharacterController.isGrounded;
    }

...

Now I know the problem is private void Start() on line 44, and from everything I've read, it's in the wrong place (to make sure, I changed it to public void, then just left it as void, both resulting in errors) however I'm stumped as to where I should move Private Void too.

I appreciate any and all advice on this.


texts:
Recently,

I moved an app I am building from a computer with Intel & Nvidia to a computer with AMD CPU & GPU.

The problem is, that glDrawElements gives me bad access location and I can't figure out why.

The render function is the following:

template<class PositionData> void drawTexturedMesh(const PositionData &pd, const IndexedFaceMesh &mesh, const unsigned int offset, const float * const color, GLuint text)
{
  // draw mesh
  const unsigned int *faces = mesh.getFaces().data();
  const unsigned int nFaces = mesh.numFaces();
  const Vector3r *vertexNormals = mesh.getVertexNormals().data();
  const Vector2r *uvs = mesh.getUVs().data();

  // Update our buffer data passed to GPU
  glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
  glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(double) * 3 * pd.size(), &pd.getPosition(0)[0]);
  glBindBuffer(GL_ARRAY_BUFFER, 0);

  glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
  glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(double) * 2 * mesh.getUVs().size(), &uvs[0][0]);
  glBindBuffer(GL_ARRAY_BUFFER, 0);

  glBindBuffer(GL_ARRAY_BUFFER, vbo[2]);
  glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(double) * 3 * mesh.getVertexNormals().size(), &vertexNormals[0][0]);
  glBindBuffer(GL_ARRAY_BUFFER, 0);

  // Binding element array and drawing. numFaces * 3 triangles per face.
  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
  glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, sizeof(unsigned int) * mesh.getFaces().size(), mesh.getFaces().data());

  glDrawElements(GL_TRIANGLES, 3 * nFaces, GL_UNSIGNED_INT, BUFFER_OFFSET(0));

  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}

Math, vectors and matrices are from Eigen.
Any ideas or any other code part you would like to see?
Bare in mind that this exact code works fine with nVidia.

Thanks.


texts:
Most multiplayer games have some sort of way to communicate. It is usually verbal, written, or emotive gestures.

If I were to allow young children, from 11 to 13, access to a game I'm creating where anyone can type anything, what would I need to do?

The things I can think of are; hide all chat, only allow other young players to talk to each other with a list of censored words, or just allow predetermined sentences and actions to be used.


texts: How do I get GLEW to use my Nvidia GPU instead of an integrated Intel card?

texts:
I'm new to graphics programming, though not to coding generally. I've been learning opengl from the OpenGL Superbible, 6th Edition. I was trying out the shader examples from the book but couldn't get them to work. The logged error says approximately "incorrect #version". The book uses GLSL 4.3 core.

I ran glewinfo.exe and the generated text file said that the core OpenGL version on my system was OpenGL 4.0, but it was the stats of my integrated Intel GPU, not my Nvidia GT720m GPU. I'm pretty sure the nvidia gpu supports a higher opengl version.

How do I get GLEW to detect the high-performance GPU and make calls to the Nvidia drivers instead of the integrated Intel HD GPU?

A similar question has been asked there, but it concerned only running the program on the gpu. How do I tell which version of OpenGL the Nvidia GPU supports?


texts: Getting the top layer of 3D perlin Noise

texts:
I am generating 16x16x64 chunks. Afterwards I apply 3D noise to them. I want the first layer to be all grass blocks and after those I want layers of dirt.

The current problem is that I am getting some dirt blocks in my top layer.
So how do I get the entire top layer of the noise?

TArray<int32> heightMap = CalculateNoise();

    for (int32 x = 0; x < 16; ++x)
    {
        for (int32 y = 0; y<16; ++y)
        {
            for (int32 z = 0; z< 64; ++z)
            {
                int32 voxelIndex = x + (y * 16) + (z * (16*16));

                int heightmapValue = heightMap[voxelIndex];

                if (z == 30 + heightmapValue)
                    ChunkIDs[voxelIndex] = 1;
                else if (z == 29 + heightmapValue)
                    ChunkIDs[voxelIndex] = 2;
                else
                    ChunkIDs[voxelIndex] = 0;

            }
        }
    }


texts:
I am working on a game in which tanks can shoot at each other. I intend to spawn a spark particle system (particles emit to Z) when a bullet hits a surface. I want to align the Z axis of the newly spawned particle system to be

a) in a 90 degree angle to surface that has been hit
b) in a reflective angle from the original trajectory

I know that I can "fake it" by setting particle Z to World 90 degrees, however then it will do so on any angled surface, while I would like to have the particle system dynamically orient itself in a 90 degree angle away from the surface that has been hit/ or reflect into the direction away from the incoming bullet.

hope you can help me, getting quite frustrated.


texts:
Based on my reading of cube mapping tutorials so far, my understanding is that you need a direction vector, and from the direction vector we can determine the point of intersection with one of the six planes.

Is the direction vector the player's view direction?  Besides that, I do not understand how having only one ray will give us the texture to fill the whole screen.

Furthermore, what if we are looking at one of the edge of the cube?  Now we have to sample texture from two faces?

Can someone please explain what am I missing here?


texts:
As a coder, I don't have much experience in asset creation workflow. I'm trying to figure out the best way to work effectively with Unity + Blender combo. I don't export to FBX, I prefer to work directly with Blender files, with no intermediate export step.

I have parts of the map that I place in the scene: walls, decorations, whole rooms, etc - I keep them in one Blender file. I have models of collectibles, like treasures, keys and the like - I keep them in another Blender file. I have models of characters, which I keep in another one. It has worked OK so far, however I feel like it's not the best way to work. While it makes sense in Blender, it gets messy in Unity.

What is an effective way of working with this combo? Or with asset import in a larger project, in general? Should I export to FBX instead of using Blender files directly? I'd like to understand now how and why to adapt the workflow than have everyone involved being slowed down later.


texts: How do you transform a coordinate system from Cartesian to Isometric?

texts:
Apologies if my example is a bit contrived, I've been trying to figure out how to apply matrix transformations to this coordinate problem, and I'm not getting the right output. I need to understand the math for this (some pseudo code might be helpful). See graphic on bottom.

Assume a game world has four properties World => ( ORIENTATION = angle, MAP_SIZE = [mw,ml], CELL_SIZE = [cw, cl])

Now assume we have a World instance called World_A with the following properties:

World_A = ( -90, [4096,4096], [64, 64])

In other words, World_A has a 2-dimensional, 4096 x 4096 pixel map with an initial orientation of -90 degrees (inverse Cartesian plane), which can be divided by 64 x 64 named cells (denoted by their calculated subcoordinates [p,q] e.g. Cell_p_q), and an active cursor (denoted by its rendered position [x,y])

Using the coordinates of an active cursor [x,y] we can calculate which cell the cursor is over (some Cell_p_q) and designate that cell the Active_Cell which is then highlighted. Example: if the cursor is at [8,16] then we determine that it's over Cell_1_1 and Active_Cell = Cell_1_1.

Now-- let's add a special mirror world called World_B where World_B = Isometric(World_A)

Both worlds share the same Cursor with position [x,y].

How do I transform the World_A( Orientation, Map, Cells) to the isometric equivalent of World_B( Orientation, Map, Cells), such that when the Cursor is over either map, the right Active_Cell is highlighted?

Here's a quick screenshot of what I'm experimenting with; you can see in this graph that World_A is overlaying World_B coordinates. My math is brute-force contrived, but it works, what I want is to understand the matrix transformation way of doing this.


texts: LibGDX Box2D, how to play an animation once, then set the state back

texts:
So, I've got some animations in LibGDX that I want to get running. Currently, the walking animations work perfectly, but attacking doesn't. I want the attack animation to play once, then set the State back to WALKING.

I've been experimenting with attacking upward (that's why the code's different), and all it does is flash and go back to walking. The other three directions show only the last frame of the animations, and holds it there. Does anyone know how to get this to work? I've looked at the similar questions, but none of them are helping.

There's a lot of code in this method, so I apologize in advance:

private TextureRegion getFrame(float dt) {
        TextureRegion region = null;
        if (currentState == State.WALKING) {
            switch (currentDir) {
                case UP:
                    if (b2body.getLinearVelocity().x == 0 && b2body.getLinearVelocity().y == 0) {
                        stateTimer = 0;
                        region = heroWalkUp.getKeyFrame(stateTimer, false);
                        stateTimer = 1;
                    } else {
                        region = heroWalkUp.getKeyFrame(stateTimer, true);
                    }
                    break;
                case RIGHT:
                    if (b2body.getLinearVelocity().x == 0 && b2body.getLinearVelocity().y == 0) {
                        stateTimer = 0;
                        region = heroWalkRight.getKeyFrame(stateTimer, false);
                        stateTimer = 1;
                    } else {
                        region = heroWalkRight.getKeyFrame(stateTimer, true);
                    }
                    break;
                case LEFT:
                    if (b2body.getLinearVelocity().x == 0 && b2body.getLinearVelocity().y == 0) {
                        stateTimer = 0;
                        region = heroWalkLeft.getKeyFrame(stateTimer, false);
                        stateTimer = 1;
                    } else {
                        region = heroWalkLeft.getKeyFrame(stateTimer, true);
                    }
                    break;
                case DOWN:
                default:
                    if (b2body.getLinearVelocity().x == 0 && b2body.getLinearVelocity().y == 0) {
                        stateTimer = 0;
                        region = heroWalkDown.getKeyFrame(stateTimer, false);
                        stateTimer = 1;
                    } else {
                        region = heroWalkDown.getKeyFrame(stateTimer, true);
                    }
                    break;
            }
        } else if (currentState == State.ATTACKING) {
            switch (currentDir) {
                case UP:
                    region = heroAtkUp.getKeyFrame(stateTimer, true);
                    if (heroAtkUp.isAnimationFinished(stateTimer)) {
                        currentState = State.WALKING;
                    }
                    break;
                case LEFT:
                    region = heroAtkLeft.getKeyFrame(stateTimer);
                    break;
                case RIGHT:
                    region = heroAtkRight.getKeyFrame(stateTimer);
                    break;
                case DOWN:
                    region = heroAtkDown.getKeyFrame(stateTimer);
                    break;
                default:
                    region = heroWalkDown.getKeyFrame(stateTimer); //should never happen
                    break;
            }
        }

        stateTimer = currentDir == previousDir ? stateTimer + dt : 0;
        previousState = currentState;
        previousDir = currentDir;
        return region;
    }


texts:
Is there a way I can use an OTF file with libGDX.

The following throws an exception:

gameFont = new BitmapFont(Gdx.files.internal("data/font.otf"));

Caused by: com.badlogic.gdx.utils.GdxRuntimeException: Invalid padding.

This is the same error thrown if I were to try to use a non font file type as well. (i.e. .png .mp3 etc). I have been able to use .fnt files in the past. Is there anyway around this? Thanks.


texts: I tried to add a sun in the lighting setting. I have a directional light in my scene, but i can't select it as sun source in lighting setting. The light does not appear in the list. Does anyone know what is wrong ?


texts: How is entering cover animation done for cover system?

texts:
I am trying to create a cover system for my 3rd person shooter game in Unity.

My implementation is a basic one :

On Player enter Trigger
  Player move to preset cover position
  Player play Enter Cover animation (eg: dash to cover)

This is fine without root motion enabled, when it is enabled (so the movements look natural), instead of dash &
stop behind the cover, the Player will dash and stuck himself inside the cover (due to root motion). So I am curious, what is a good way to do the animation for cover system?


texts:
I'm just getting into Three.js and the camera is causing some problems. Basically, I want to implement spectator-like movement controls, so that I can move around freely in the scene. The problem is that the camera seems to have it's own coordinate system, so rotating it rotates the camera, while the system itself is left untouched. This, in turn, causes problems when moving the camera.

To better illustrate the problem, please have a look at the scene. Use the arrow keys to look around and press w to move forward.

http://jsbin.com/anarid/1/

Ideally, I'd like to apply the rotation to the 'whole' camera instead, including its coordinate system. I know that Three.js provides controls, but I'd like to implement them myself for learning purposes. I also know that a lot of people do have this problem and that there are a couple posts dealing with this. However, I mostly fail to understand the solutions. If someone could shed some light on this, I'd really appreciate it. :)

Greetings


texts: Recommended RPG game that can be used to learn game Modding?

texts:
I would like to learn game development via game modding. RPG/MMORPG is one of my favorite genres. Could someone recommend me a good and recent ( I would like to play the game as well) game to learn game modding. Something with the likes of Neverwinternights 2.

Thank you very much for the responses. Appreciate it.


texts: Copyright and patents on game design and names?

texts:
We all know that each game has elements from another game but when does one cross the line of copyright? I have a view particular questions about this since this "line" is very vague.

While looking for a name and Googling it usually return some kind of old or unknown game already with the exact same name. Can i use this name? And what about a name like Diablo, since Diablo is the commonly used name for the devil there cannot be a patent on this afaik. So would a different kind of game named Diablo be allowed?
Let's say i want to make a game of mechs like in Mechwarrior. Obviously the mech designs have copyright, the name as well since i suppose. But am i crossing any rights if i make a top down tactical squad game that include mechs of different designs/names and call it Clash of Steel?

I understand there are not much lawyers here, but how could anyone create a game these days that does not cross the lines of copyright. Like the Mechwarrior example, there are plenty of games nowadays even movies that use this concept. For what it matters Mechwarrior could have ripped the idea from the Gundam anime series. With so many titles coming out each week including the indies it is next to impossible not to infringe into someone copyright.


texts: OnTriggerExit2D called multiple times when two triggers touch

texts:
I have two GameObjects tagged "Point", each with a Collider 2D set to Is Trigger.

I have another GameObject, "pencil", which also has a Collider2D set to Is Trigger

I want to move the pencil the first point to the start drawing a line, and then stop drawing when it hits the second point.

My problem is that when the pencil hits a point, it calls OnTriggerExit2D multiple times. How can I only detect first contact with the point?

Pencil script:

private void OnTriggerExit2D(Collider2D collision)
{
    if (!collision.isTrigger)
    {
        if (collision.gameObject.tag == "Point")
        {
            writing = !writing;
        }
    }
}


texts:
TLDR: What are limitations on how many objects a single prefab can handle safely? keeping in mind that I could potentially have almost a 100 of these

I am busy creating a system to essentially load the game world in chunks as the player moves.
This means that every single object in the world will be streamed into the game through script when needed(still designed in the editor, impossible otherwise)
The problem I am having is with methods to store and load objects.

I have looked at everything I could think of or get information on. After researching all the methods I found, I started thinking that prefabs is the best solution since it can live anywhere in the project(unlike streaming assets folder, which is also not recommended for many assets, let alone every single asset). Creating Game Objects at runtime is not as easy once GO's get complex with components and settings, also I assume the performance hit from creating GO's this way is worse than using an existing prefab.

So my question is if prefabs can handle massive amounts of objects(lets say 1000) safely? testing this is hard because i would have a prefab(or a few) for each tile that gets loaded.


texts: What is more efficient: Using matrix translation to move a character, or using a vector/scalar?

texts:
In 2D or 3D, matrix transformations are used for rotation, scaling, and sheering. However, when it comes to movement, should I go out of my way to use and implement scalar/vector movement, or just stick to matrix translations?
Thanks.


texts: How can I add an IsTrigger propriety from code? Unity

texts:
I made an gameobject in my script and i made it a rigidbody, and added it a boxcollider, but I dont know how to tell the program to make it a trigger. Here's my code until now:

multi = new GameObject();
                multi.AddComponent<Transform>();
                multi.transform.position = new Vector2(1f, 1f);
                multi.AddComponent<Rigidbody2D>();
                multi.AddComponent<BoxCollider2D>();


texts: Parent and child with different Animators

texts:
I'm animating my 2D game (Unity 5.4).

Is it a good/bad practice to have parent and child gameobjects with different Animators?

Example: a 2D bug, that has sprites for every body part. On the "body container"=parent object I add an Animator and animate all parts except the head. For the head, that is a child gameobject to the body (in scene's hierarchy) I want to add a separate Animator and animate only the head.

Also is that influencing performance in any way?


texts: What are known game mechanics to disallow player to become infinitely rich still keeping it fun to progress?

texts:
I want to make an online game with a leaderboard. A player should be able to gather tools/resources to continue exploring/harvesting. The problem I want to solve is that someone can find a way to harvest things like money, food, ammo, crafting resources, etc. infinitely but I don't want it to happen, because: 1) it can potentially ruin the leaderboard 2) it potentially disconnects old players from new players because they become interested in different things having nothing to talk about to share the gaming experience. The player should sometimes to be forced to go back to start but it should be still fun.

For example, games about zombies. AFAIK, the game Project Zomboid had zombies amount growing and resouces were limited in such way that you was losing in any way. Why would it be still fun? Because there is a challenge in how many days you can survive.

Another example -- Realm of the Mad God. There you get into the leaderboard only when you die. So once you reach the goal you start from the level 1 again. You can't be in the leaderboard and keep progressing. Why doesn't it ruin the fun? Maybe because you don't lose the loot that you've saved in a "vault" and while you are now level 1 and can't use most of your loot immediatelly it's still there, not lost.

Rogue games like Nethack, Stone Soup, Cogmind -- basically the world has limited size and once you clean the level you have nothing else to do other than go to the next level. It's still fun because once you master your skills in the game the competition changes from maximizing your progress to minimizing steps you've used to reach the end goal. Like spent steps, time, abilities used, etc.

Rust -- in this one players are playing against each other and you lose almost everything when your base is raided. The base is an object in 3d world and to raid it the opponent have to make nearly a straight hole to the center. So the amount of resources you have to spend on armoring your base is X^3 where X is amount of resources needed to raid you. This makes it impossible to infinitely armor yourself and so finally you get raided anyway. Why is it still fun? Maybe because everything gets wiped once in few weeks and there are game updates that make it not boring to start again because the game will be a bit different.

There is a game mechanic in The Elder Scrolls Online that prevents trading guilds becoming infinitely rich as I understand. I'm not the guild owner and so I can be wrong but every week there is a bidding that forces guilds to pay as much as they can to win a bid to, simply saying, have a benefit during the week. AFAIK all the bids are gone and this is how the amount of money the guilds have in the MMO game with no wipes is limited.

I want my game to have some sort of "death" that would reset the progress to effectively keep players away from having infinitely large base, amount of money, etc. while still being fun to start again. What are some other game mechanics for this that I missed?


texts: OpenGL - Debug version runs faster than Release version

texts:
My Visual Studio 2019, 64-bit version of Tetris using OpenGL runs significantly faster, 3X, in Debug mode than in Release mode.
The image above shows the board.  Each cycle of the rendering or game loop redraws everything, viz., the light blue background, the grid, the individual game pieces (one shown) with the latest one added moving every 300 ms, and the text score display.  I have moved all the repetitive code out of the loop, e.g., that which sets the location in shaders for uniform constants.
The Release mode loop cycle time ranges from 0.05 to 1390.0 ms while that of the Debug mode ranges from 0.05 to 350.0 ms.
Any thoughts on what I might investigate?
Thanks.


texts: How do I make an AI that stays at a distance from the player act correctly when cornered?

texts:
I am working on a few different AIs for a tile-based game. I'm trying to figure out one where that tries to keep a certain distance from the player. So if distance becomes small, move away.

The whole game is in a pretty small are so it can't just forever move away. The movement is 4 directional.

How do I make the AI keep going at a distance, and once caught in a corner or close to a side of the room, to ignore the rule and just try to go around the player to the other side of the room?


texts: How do I prevent XNA from pausing Updates while the window is being resized/moved?

texts:
XNA stops calling Update and Draw while the game window is being resized or moved.

Why? Is there a way to prevent this behaviour?

(It causes my network code to desynchronise, because network messages aren't being pumped.)


texts: Does allocating and freeing a huge chunk of memory at startup "clean up memory?"

texts:
The book Game Coding Complete, Fourth Edition, chapter 5 (Game Initialization and Shutdown), section Checking Memory contains this interesting code sample:

bool CheckMemory(const DWORDLONG physicalRAMNeeded, const DWORDLONG virtualRAMNeeded)
{
    MEMORYSTATUSEX status;
    GlobalMemoryStatusEx(&status);
    if (status.ullTotalPhys < physicalRAMNeeded)
    {
        // you don’t have enough physical memory. Tell the player to go get a
        // real computer and give this one to his mother.
        GCC_ERROR("CheckMemory Failure: Not enough physical memory.");
        return false;
    }
    // Check for enough free memory.
    if (status.ullAvailVirtual < virtualRAMNeeded)
    {
        // you don’t have enough virtual memory available.
        // Tell the player to shut down the copy of Visual Studio running in the
        // background, or whatever seems to be sucking the memory dry.
        GCC_ERROR("CheckMemory Failure: Not enough virtual memory.");
        return false;
    }

    char *buff = GCC_NEW char[virtualRAMNeeded];
    if (buff)
    {
        delete[] buff;
    }
    else
    {
        // even though there is enough memory, it isn't available in one
        // block, which can be critical for games that manage their own memory
        GCC_ERROR("CheckMemory Failure: Not enough contiguous memory.");
        return false;
    }
}

This raises some questions.

The first part just asks the OS (Windows) how much physical RAM is available.
The curious part is the second one, which allocates a huge chunk of memory and frees it right away:

char *buff = GCC_NEW char[virtualRAMNeeded];
if (buff)
{
    delete[] buff;
}

The author goes on to explain:

  ... this function allocates and immediately releases a huge block of memory.
  This has the effect of making Windows clean up any garbage that has accumulated in the memory manager
  and double-checks that you can allocate a contiguous block as large as you need. If the call succeeds,
  you've essentially run the equivalent of a Zamboni machine through your system's memory,
  getting it ready for your game to hit the ice...

But I have my reservations on that.

"Cleaning garbage that has accumulated in the memory manager?" Really? If the game has just started, shouldn't there be no garbage?

"Making sure you can allocate a contiguous block?" In the very specific case where you are going to manage memory yourself, this would them make some sense, but still, if you do allocate a lot of memory right of the bat, you pretty much make it impossible for any other application to run in the system while yours is on.

Also, isn't this likely to force the OS to commit all that memory, and as consequence evict a lot of memory to the swap disk space, slowing your app startup a lot?

Is this really a good practice?


texts:
I'm implementing my own ray tracer as an iPad app for a school project. At the moment this is the result:

I need to add the last requirement, soft shadows, but I can't find a complete reference anywhere. If I understood well, to implement this feature I have to shoot many rays from an intersection point to mt light source. This one must be an area light. Suppose i use a sphere, my questions are:

which point on the sphere i must use to calculate the shadow ray?
how do I average the result?

Thanks for helping me.


texts: How can I implement "cut outs" for lighting in OpenGL?

texts:
So, I'm working with OpenGL (I'm not exactly sure of the version), and I want to do an old-style lighting setup by essentially drawing a black rectangle over the screen, and drawing white circles over the areas that should be lit. I already have the rectangle and the circles, but I can't figure out how to make it so that the white circles are transparent when applied to the black areas. Any ideas? I tried to use blending modes, but it still evades me...

EDIT: Here's the code that I'm using (Python).

view_buf = Buffer(GL_INT, 4)
glGetIntegerv(GL_VIEWPORT, view_buf)
view = view_buf.to_list() if hasattr(view_buf, "to_list") else view_buf.list

glDisable(GL_DEPTH_TEST)

glDisable(GL_LIGHTING)

glEnable(GL_BLEND)

if logic.lights['smooth']:
    glEnable(GL_LINE_SMOOTH)

# # Make sure we're using smooth shading instead of flat
# glShadeModel(GL_SMOOTH)

# Setup the matrices

glMatrixMode(GL_PROJECTION)
glPushMatrix()
glLoadIdentity()
gluOrtho2D(0, view[2], 0, view[3])
glMatrixMode(GL_MODELVIEW)
glPushMatrix()
glLoadIdentity()

#glAlphaFunc(GL_GREATER, 0.5)

glColor4f(0.0, 0, 0, 0.75)

glBegin(GL_QUADS);                              # Draw Black screen
glVertex2d(0.0, 0.0);
glVertex2d(view[2], 0.0);
glVertex2d(view[2], view[3]);
glVertex2d(0.0, view[3]);
glEnd()

glColor4f(1, 1, 1, 1)

degtorad = 3.14159/180.0

glBlendFunc(GL_ZERO, GL_SRC_ALPHA)

def DrawCircle(x, y, radius, fill = 1, step = 11):

    glVertex2f(x, y)

    if fill:
        glBegin(GL_TRIANGLE_FAN)
    else:
        glBegin(GL_LINE_LOOP)

    for a in range(0, 360, step):
        angle = degtorad * a
        glVertex2f(x + (sin(angle) * radius), y + (cos(angle) * radius))

    glEnd()

#for layer in range(len(logic.lights['layers'])):
#   size =
for light in logic.lights['points']:
    DrawCircle(light[0][0] * view[2], (1 - light[0][1]) * view[3], light[1], step = light[2])
    if logic.lights['smooth']:
        DrawCircle(light[0][0] * view[2], (1 - light[0][1]) * view[3], light[1], 0, light[2])

# Reset the state
glPopMatrix()
glMatrixMode(GL_PROJECTION)
glPopMatrix()


texts:
In games like city story or we farm how do they implement scrolling?

To do scrolling using UIScrollView the EAGLView size has to be bigger. In those games EAGLView size look like more than 1024*1024. But there is limitation in viewport size in iphone devices(in 3G iphone max is 1024).
I played those games in 3G iphone they are working fine.
Any idea how they implemented their scrolling mechanism?


texts: How can I preserve momentum during a jump, but cancel it when a character lands?

texts: I am attempting to code a run key for my platform game in Game Maker. I'm attempting to keep my momentum when I jump, but yet stop moving at a run speed as soon as I hit the ground if Shift has been let go during the jump. How do I go about coding this?


texts: Unity 2d - Destroying foreign object from script + seek explanation about destroying objects

texts:
I have simple emmiter which sending enemies toward player in center of screen. Player can shoot missile (also emmiter). I want to destroy enemy AND missile in same time.

Here is my code attached to Enemy

 public GameObject player;
 public GameObject missile;

 void OnTriggerEnter2D(Collider2D collider)
 {
     if (collider.gameObject.name == player.name)
     {
         Destroy(gameObject);
         Application.LoadLevel("Retry");
     }

     if (collider.gameObject.tag == missile.tag)
     {
         Destroy(gameObject);
         Destroy(missile.gameObject);
         Score.killed++;
     }
 }

But after missile hit enemy, error in unity occur

  Destroying assets is not permitted to avoid data loss.

Well... im programmer but new in unity. So my question is not that simple : i think im destroying object which is still in use. Am i right? How can i destroy both objects? When i can destroy GameObject? I tried to use this

GameObject mssle = Istantiate(missile,missile.transform.position,Quaternion.identity);
Destroy(mssle);

as was suggested by good people on unityanswers. Didnt work, missile is stil alive and my answer got rejected. Am i destroying whole prefab or what? This is little confusing for me


texts: I want to take a screenshot of the game when it's running, blur it and draw it on the screen. Could you help me with taking a screenshot and blurring it?


texts:
I'm trying to import an FBX file made in Blender into Unity so I can use the actions created in Blender in a Unity animation state machine. A lot of sites seem to suggest that simply dropping the FBX file into the assets will automatically import animation clips, but that doesn't seem to be happening. Unity does however recognize the discrete actions created.

Tutorial image:

My screen image:

I used the Blender export settings "Include Animation" and "All actions", but not "Include Default Take" as people recommend.

For reference, I'm trying to follow the animator controller tutorial at unity3d.com

How can I retrieve my animation clips from the fbx file, or is there another way to insert them into the Animator?
Thanks!


texts: How to create very simple doom like corridors in XNA?

texts: So I have seen many 3D tutorials creating heightmaps and big landscapes but I am hoping there is something simple that i can throw together. If I was to do something doom/wolfenstien-like, do i just draw a cube and texture it? I guess my question is, How should i go about creating a very simple box-like room?


texts: Pathfinding How to store data for big terrain size

texts:
I am trying to implement my own pathfinding solution in unity but cant figures out how to store data. Following is my grid class which stores height, length and neighbour tile of tile.

public class grid
{
public float XVal;
public float ZVal;
public int[] NId = new int [8];
}

With Length and Height of 1, I am creating a grid for terrain size that part of the code works nicely It creates a grid, finds its neighbours. I am saving data in Array

grid[] MyGrid ;

The problem occurs when terrain size is big ex 1024*1024 so for creating a grid, Considering row and column of terrain total elements of grid becomes row(1024)*column(1024) approx. 1 million. As creating such a big grid while running game is impossible So I created custom inspector and generate grid graph and populate array in the editor. But while loading game as Mygrid array size is 1 million game stucks while loading, To fix that I created subsystem which basically divides Mygrid array in multiple arrays which seems working but is there any other way to efficiently store grid data as dividing array adds complexity in code


texts:
I'm looking for ways to generate random biome borders (like what Minecraft has).

One technique involves choosing specific biomes based on (eg) a rainfall map and a temperature map. But that just determines which biome to place, not where the borders between biomes are.

I don't want to use quantized Perlin noise directly; that would generate certain quantized values strictly within other zones, whereas I'd like finer control over which biomes can abut others. For example, in Minecraft one can see mountainous terrain, forests, plains, or deserts right next to the ocean.

Many of the solutions to "the biome problem" propose computing the whole universe in a heuristic manner. I want to generate infinite terrain, and to me that suggests the algorithm be strictly functional: given an X,Y value (and a world seed) the algorithm can easily spit out a biome value.

So, my question: what are some techniques for identifying random, non-trivial-sized, contiguous chunks of terrain to be of a given biome?


texts: Can LWJGL support multiple displays either as separated windows or as part of an AWT Window?


texts: Scrolling in 3d Shmup with 32Bit era effects

texts:
How can I create a scrolling effect like in Ikaruga, where the background is on Rails and the foreground is fixed with the player in Unity?

https://www.youtube.com/watch?v=H6d0PkEPKSk

Some more features would be:

Phases where the background scrolling is infinite: https://youtu.be/H6d0PkEPKSk?t=97
Transitioning from one background to another by changing the camera: https://youtu.be/H6d0PkEPKSk?t=57
Supporting side view, top down and starfox-like perpectives and changing between them seamlessly like in Asterbreed: https://youtu.be/c0-1RWnqoSk?list=PLPrREYqN5Wqa0Yvjq2YsTR8pgQXet5Lim&t=56
Being able to use the Unity Editor as Leveldesign tool liek in this tutorial:
https://pixelnest.io/tutorials/2d-game-unity/parallax-scrolling/

Also would I work with mesh, skybox and terrains to create a similar effect or would that be something like a Big Sphere/Cube and using textures diarama-like as they did back in the days of playstation 1 and saturn.


texts: Understanding math used to determine if vector is clockwise / counterclockwise from your vector

texts:
I'm reading Programming Game AI by Example by Mat Buckland.  In the Math & Physics primer chapter there's a listing of the declaration of a class used to represent 2D vectors.

This class contains a method called Sign. It's implementation is as follows

//------------------------ Sign ------------------------------------------
//
//  returns positive if v2 is clockwise of this vector,
//  minus if anticlockwise (Y axis pointing down, X axis to right)
//------------------------------------------------------------------------
enum {clockwise = 1, anticlockwise = -1};

inline int Vector2D::Sign(const Vector2D& v2)const
{
  if (y*v2.x > x*v2.y)
  {
    return anticlockwise;
  }
  else
  {
    return clockwise;
  }
}

Can someone explain the vector rules that make this hold true?

What do the values of y*v2.x and x*v2.y that are being compared actually represent?

I'd like to have a solid understanding of why this works rather than just accepting that it does without figuring it out.  I feel like it's something really obvious that I'm just not catching on to.

Thanks for your help.


texts: How would I check the range against the entirety of an enemy object, and not just it's transform.position?

texts:
I want to be able to do range checks against the entirety of an enemy object, and not just it's transform.position. The enemy object can have it's side or nose within range, but range detection will not determine if it's close enough to be targeted unless it's transform.position is within range.

Right now I run a quick check against all nearby units to determine their distance from a turret on the friendly unit.

I was thinking raycasts, but I imagine raycasts every frame for up to 10 detected enemies per unit (Each unit will at max hold onto references of 10 nearby enemies. I could have 100 friendly units within range of 100 enemies) would chew up a fair bit more CPU than just checking their cached transforms.

Suggestions, ideas, or comments?

Edit: More Detail

Currently a Unit has a trigger spherical collider that defines it's view range. Any enemy unit within this view range is added to a collection based on priority, with a maximum of 10 objects referenced per collection (each Unit can only be aware of 10 enemy objects). From there, each turret on ship checks the distance from itself to each of the enemies within that collection. When the distance is <= it's attack range, it will fire upon whichever enemy object gets within it's attack range first.

I used to use spherical colliders for each turret, which of course would detect the enemy as soon as any part of the enemy entered the trigger collider. The issue was the massive performance loss due to OnTriggerStay() begin called by hundreds of units, tens of thousands of times per frame when I have no need for the method. So I discarded the extra trigger colliders for a more performance friendly approach.

The issue is that the range check is that is checks the transform.position of the enemy. This does not take into account the collider that makes up the enemies shape, and will only trigger when the center of the object enters within range.


texts:
When a texture (2D) is supplied to a shader as a 'uniform' input, it is first uploaded to OpenGL using glTexImage2D() and then using glUniform1i() it is associated to shader uniform.

eg code :

Texture data

glTexImage2D(): is used to transfer texture data to the server side

glGetUniformLocation(): is used to access shader uniform handle

glUniform1i(): associates the data pointed by texture unit to the shader 'uniform'

but when we pass matrix (eg matrix4x4) to a shader as a 'uniform' input, when don't use any specific function to upload it to OpenGL.

(we just used to glUniform..() to associate the data with the shader input which we also used in the case of texture data)

Matrix data

glGetUniformLocation(): to access shader uniform handle

glUniformMatrix4fv(): to associate matrix data to the shader uniform input.

Where does the matrix data live in each step in the process of passing it to a shader as a uniform input?

Does matrix data always live on client side/ CPU accessible memory and fetched every frame by server side?
If it is uploaded to OpenGL:

which step/function call uploads the data?
where does the data live in OpenGL memory?
how its memory location is pointed?


texts:
I am working on 2-player 2d sidescroller.

How should I implement the physics on the server? Use one world for every game or use a big world in which I add every 2 player that start a game?

I have looked into some source code of multiplayer games and I saw that they don't implement any kind of game loop on the server, instead they work with events. If the game has physics handled by the server shouldn't the server use a game loop to call the step method?


texts: Unreal - Where should I put my 'Save System Controller'

texts:
Making a save game system for a single player platformer game in Unreal.

Needs to be accessible from the Main Menu
Cannot be a component on the player.

Where is the best place to put/store this functionality?

GameMode?
GameState?
PlayerState even?


texts: How can I use the graphics pipeline to render volumetric data based on a density function?

texts:
Both graphics APIs (OpenGL and DirectX) devise a well defined pipeline in which several stages are programmable. These programmable stages require to take a fixed minimum amount of data and are supposed to do a well defined range of operations on it, and output some defined minimum output, so that data can be passed on to the next stage correctly. It seems as if these pipelines are designed to work with only a limited amount of types of geometric data, which in the case of both D3D and OGL are vertex data and texture co-ordinates.

But, if given a case when the application I plan to make doesn't use vertices ( or even voxels ) to represent its geometric data and does not exactly do transformations or projections or rasterisation or interpolation or anything like that, such limitations of the APIs or the pipeline make things difficult.

So, is there a way in which we can change graphics pipeline in a way so that the functionality of what each stage does to the data and the type of data that is outputted in each stage is changed to my advantage? If not, then is there a way by which I can use the 'raw' API functions to construct my own pipeline? If not, then please mention why it isn't possible.

EDIT : My Application uses density functions to represent geometry. The function has a value at each point in space. I divide the frustum of the camera into a 3d grid, each block can be projected as a pixel. On each block, I integrate the density function and check if its value is more than a required value. If yes, then its is assumed that something exists in that block and that pixel corresponding to that block is rendered.
 so, now in my renderer, I want to pass the function ( which i represent with a string ) to the graphics hardware instead of vertex data in vertex buffers. this also implies that the vertex shader won't have vertices to transform into homogeniouse clip space and the fragment shader doesn't get pixel info. instead, now most of the looking up and evaluation happens per pixel.


texts: How to compute the forward facing direction from three angles and then translate along it?

texts:
Given:

float yaw, pitch, roll;

How does one compute the forward direction:

vec3 forward = computeForwardFromEulers(yaw, pitch, roll);

Next, I would like to use this information to translate an object along this axis / heading / forwardDirection.

// move 1 unit forward
forward.?? = 1.0f?


texts: Why does the lighting change the objects color?

texts:
I have a code that draws a sphere. Without lighting it is white, but if I enable lighting, it's drawn in gray.

I don't know why the sphere changed it's color

#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>

void init(void)
{
    GLfloat mat_specular[] = { 1.0, 1.0, 1.0, 1.0 };
    GLfloat mat_shininess[] = { 50.0 };
    GLfloat light_position[] = { 1.0, 1.0, 1.0, 0.0 };
    glClearColor (0.0, 0.0, 0.0, 0.0);
    glShadeModel (GL_SMOOTH);

    glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
    glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
    glLightfv(GL_LIGHT0, GL_POSITION, light_position);

    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glEnable(GL_DEPTH_TEST);
}

void display(void)
{
    glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glutSolidSphere (1.0, 20, 16);
    glFlush ();
}

void reshape (int w, int h)
{
    glViewport (0, 0, (GLsizei) w, (GLsizei) h);
    glMatrixMode (GL_PROJECTION);
    glLoadIdentity();
    if (w <= h)
        glOrtho (-1.5, 1.5, -1.5*(GLfloat)h/(GLfloat)w,
                 1.5*(GLfloat)h/(GLfloat)w, -10.0, 10.0);
    else
        glOrtho (-1.5*(GLfloat)w/(GLfloat)h,
                 1.5*(GLfloat)w/(GLfloat)h, -1.5, 1.5, -10.0, 10.0);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

int main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH);
    glutInitWindowSize (500, 500);
    glutInitWindowPosition (100, 100);
    glutCreateWindow (argv[0]);
    init ();
    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutMainLoop();
    return 0;
}


texts:
I am new to Game Development and using NGUI plugin free version. There are few sprite images in my game. I made them prefab and instantiated at runtime. then I created NGUI Texture and Made it background. When I play my game. sprite prefabs instantiate behind the NGUI Texture Background. I want to place them  front of NGUI Texture.I also changed camera Setting, now mainCamera depth is -1, and NGUI Camera depth is 1.  changed both of them. But, could n't find solution. I have tried in several ways.

Any suggestions will be highly appreciated. Thanks


texts: XNA effect lighting like basic effect lighting

texts:
Is it possible to make lighting in a normal effect work like the lighting in the basic effect?

With a basic effect it's really easy:

BasicEffect effect;
effect.EnableDefaultLighting();


texts: Why can't I create a D3D12 Device with the highest performance adpater retrieved by EnumAdapterByGpuPreference?

texts:
IDXGIAdapter* higher_performance_adapter;
    dx_result = dxgi_factory->EnumAdapterByGpuPreference(0, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE,
                                                         __uuidof(IDXGIAdapter),
                                                         (void**)&higher_performance_adapter);
    if(SUCCEEDED(dx_result))
    {
      UINT output_index = 0;
      IDXGIOutput* output;
      while(higher_performance_adapter->EnumOutputs(output_index, &output) != DXGI_ERROR_NOT_FOUND)
      {
        DXGI_OUTPUT_DESC output_description = {0};
        output->GetDesc(&output_description);

        ++output_index;
      }

      ID3D12Device* device;
      dx_result = D3D12CreateDevice(higher_performance_adapter,
                                    D3D_FEATURE_LEVEL_12_1,
                                    __uuidof(ID3D12Device),
                                    (void**)&device);
      if(SUCCEEDED(dx_result))
      {

          ...

I'm trying to create a D3D12 device selecting the GPU with the higher performance because passing null to the adapter parameter at D3D12CreateDevice gets the first adapater from EnumAdapters, which is the Intel integrated GPU. But, when I got a IDXGIAdapter object of my dedicated GPU, the EnumOutputs function failed, as well as the D3D12CreateDevice. Why is that? Why these functions fails when using the dedicated GPU, which in my case is a NVIDIA, ?
The returned dx_result is "0x887a0004 : The specified device interface or feature level is not supported on this system. "
That don't makes sense, since my system supports DirectX12.


texts:
This may be a "best way to" question, so may be susceptible to opinion-based answers (which is ok for me). But I would also like if there are any tutorials , research papers , etc.

I'm trying to make a 3D free kick game, and I want to decide on the Goalkeeper algorithm.

Usually (and in my game) the shot is a function of direction , power and swerve. Maybe wind can be a factor too. So the shots trajectory is pre-deterministic, i.e., the point that intersects the goal (or out) plane is determined as soon as the shot fires.

So what could be a good approach for the goalkeeper to jump (or walk) ?

I have two approaches in mind :

1- determine the point, and jump to there.
2- when the ball is closer than a threshold distance, estimate the point by the ball's velocity vector, and jump to there.

The problem with the first approach is, goalkeeper will always save the shot, which I want to prevent. So there should be some kind of randomness, or the goalkeeper's ability to jump and walk will be restricted.

The problem with the second approach is, when there is a high amount of swerve, the goalkeeper will always fail to save the shot.

So how could these approaches be better?

Thanks for any help !

Edit:

if you want to play the game, click here


texts: Deferred Rendering and skeletal animation

texts:
I am working on a deferred rendering engine and just finished skeletal animation in the vertex shader, but soon realized that this was only updating the rendered geometry and not the shadows, as the animation was only done in the VS of the deferred rendering step, and not in the VS of each light.

I assume this means I should just calculate the animation on the cpu, as otherwise it will be done #oflights + 1 times in the gpu, which seems like a huge waste of cycles.

Is this how it is typically done?

Edit:  As a note, I am currently implementing this in OpenGL


texts: How to create a normal map for my dice texture?

texts:
I have this simple dice texture and would like to create a normal map for it where the black dots are are dents and the edges are trimmed(like on a actual dice)
I'm using unity5. I need a explanation on how to create the normal map in PhotoShop CS5 or a code solution. Thanks in advance.

Here is the dice texture I'm using.


texts: Why doesn't SDL_Surface rendering work in SDL2?

texts:
I have done the following using C++:

1) I used SDL_CreateWindow() to create an SDL window

m_window = SDL_CreateWindow("My First Side-scroller
    SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH,
    SCREEN_HEIGHT, SDL_WINDOW_SHOWN);

2) I used SDL_CreateRenderer() to create a renderer for the SDL window

m_renderer = SDL_CreateRenderer(m_window, -1, SDL_RENDERER_PRESENTVSYNC);

3) I used SDL_CreateTexture() to create a texture

m_texture = SDL_CreateTexture(m_renderer, SDL_PIXELFORMAT_RGBA8888,
        SDL_TEXTUREACCESS_STATIC, SCREEN_WIDTH, SCREEN_HEIGHT);

4) I created a buffer of type Uint32 to hold texture information which is passed to the SDL_Texture

m_buffer = new Uint32[SCREEN_WIDTH * SCREEN_HEIGHT];

5) I created a custom pixel drawing function which is use to draw pixels at a low level and pass it to the buffer.

void Screen::setPixel(int x, int y, Uint8 red, Uint8 green, Uint8 blue) {
    // Checking for pixels  off screen
    // This is sufficient because the rand function can generate a negative number
    if (x < 0 || x >= SCREEN_WIDTH || y < 0 || y >= SCREEN_HEIGHT) {
        return;
    }

    Uint32 colour = 0;

    colour += red;
    colour <<= 8;
    colour += green;
    colour <<= 8;
    colour += blue;
    colour <<= 8;
    colour += 0xFF;

    m_buffer[(y * SCREEN_WIDTH) + x] = colour;
}

6) I used 5) along with other functions to help draw pixels on random locations in the window and make them move vertically and loop from the top of the window to the bottom of the window (like moving stars).

Stars::Stars()
{
    m_x_star=((2.0*rand())/RAND_MAX)-1;
    m_y_star=((2.0*rand())/RAND_MAX)-1;
}

void Stars::moveStar(){
    // starSpeed is the desired change in co-ordinate position for each pixel plotted
    double const starSpeed = 0.001;

    if(m_y_star<-0.998 && m_y_star>-1) {
        m_y_star=0.995;
    }

    m_y_star-=starSpeed;
}

1) to 6) works with no-error

So, onto my issue: Blitting an image using SDL_BlitSurface seems to require that the window is created using SDL_Surface() for its third flag. I want to load a .png image of a spaceship I drew. Here is the code I use to load the image.

void Screen::update_spaceShip() {
    SDL_Surface *Image;
    Image= IMG_Load("spaceship_stock2.png");
    SDL_BlitSurface(Image,NULL,m_window,NULL);
}

Error message:

  cannot convert 'SDL_Window*' to 'SDL_Surface*' for argument '3' to 'int SDL_UpperBlit(SDL_Surface*, const SDL_Rect*, SDL_Surface*, SDL_Rect*)'

What am I doing wrong?


texts: How do I efficiently generate chunks to fill entire screen when my player moves?

texts:
In my game I generate chunks when the player moves. The chunks are all generated on the fly, but currently I just created a simple flat 8X8 floor.  What happens is that when he moves to a new chunk the chunk in the direction of the player gets generated and its neighboring chunks.

This is not efficient because the generator does not fill the entire screen. I did try to use recursion but its not as fast as I would like it to be.

My question is what would be an efficient way of doing so? How does minecraft do so?
When I say this I mean just the way it PICKS which chunks to generate and in what order. Not how they generate or how they are saved in regions, just the order/way it generates them.

I just want to know what is a good way to load chunks around the player.


texts: detect asset change while running in unity editor?

texts: Is it possible to detect asset change while running in the unity editor.  When I update my model, I see it change but the xml data associated with it does not change.  So it would be nice to detect that and reload the xml data while running in the unity editor.


texts: Only 1 TextMeshProUGUI being affected by coroutine

texts:
I have a prefab m_wordContainer which is empty other than having a TextMeshProUGUI as a child (I did this so that I could position this container freely not being bugged by an animation played by the TMPUGUI object). At the start of the program I start a coroutine (SpawnWordPopups) which splits the words in a sentence, making a copy of m_wordContainer and assigning that word to the text property of its TMPUGUI, spawning such m_wordContainer in a random location within the screen, and then starting a coroutine (FadeText) that fades in the text of every TMPUGUI.
The problem is that only one of the TMPUGUI has its text faded, even though the FadeText coroutine is called seemingly correctly.
All words are shown as expected, only thing missing is the fading effect on all but the first word that fades.
If I called FadeText like this: if (i > 0) { yield return FadeText(true, tmpText, 2); } then only the second word will be faded.
 [SerializeField] private GameObject m_wordContainer;

    void Start()
    {
        yield return StartCoroutine(SpawnWordPopups("test foo bar"));
    }

private IEnumerator SpawnWordPopups(string l_line)
    {
        string[] words = l_line.Split(' ');
        List<Vector3> wordPositions = new List<Vector3>();
        for (int i = 0; i < words.Length; ++i)
        {
            Vector3 spawnLocation = new Vector3(Random.Range(m_wordScreenDistanceOffset, Screen.width - m_wordScreenDistanceOffset), Random.Range(m_wordScreenDistanceOffset, Screen.height - m_wordScreenDistanceOffset), 0);
            if (IsWordOverlapping(wordPositions, spawnLocation))
            {
                --i;
                continue;
            }
            wordPositions.Add(spawnLocation);
            GameObject wordContainer = Instantiate(m_wordContainer, transform.parent);
            wordContainer.transform.position = spawnLocation;
            TextMeshProUGUI tmpText = wordContainer.GetComponentInChildren<TextMeshProUGUI>();
            tmpText.text = words[i];

            yield return FadeText(true, tmpText, 2);
        }
    }

    private IEnumerator FadeText(bool l_fadeIn, TextMeshProUGUI l_textBox, float l_time)
    {
        float time = Time.time;
        float until = Time.time + l_time;
        int alphaFrom = l_fadeIn ? 0 : 1;
        int alphaGoal = l_fadeIn ? 1 : 0;
        Color textColor = l_textBox.color;
        textColor.a = l_fadeIn ? 0 : 1;
        l_textBox.color = textColor;

        while (time < until)
        {
            textColor = l_textBox.color;
            textColor.a = Mathf.Lerp(alphaFrom, alphaGoal, Time.time / l_time);
            l_textBox.color = textColor;
            time += Time.deltaTime;
            yield return null;
        }
        textColor.a = l_fadeIn ? 1 : 0;
        l_textBox.color = textColor;
    }

Could anyone shed some light into this issue I'm having? Why are not all the words being faded?


texts:
I am Trying to show Image as background, but it doesn't fit to the screen.
When I use this class as the start screen it fit the screen properly but when I call this class after winning the level, the image becomes bigger than the device screen and only part of it is shown
but when I divide the width and height on 2 the image is becomes smaller than the screen :game.batch.draw(background, 0, 0, Gdx.graphics.getWidth()/2,Gdx.graphics.getHeight()/2);
this is the code :

public class Celebration  implements Screen {
    private Fruits game;
    private OrthographicCamera gamecam;
    private Viewport gameport;

    private Stage stage;
    private World world;
    private static float temp;
    private float level;
    private Texture background;
    private Texture start;
    private Texture loading;
    private float counter;

    public Celebration(Fruits game, float level)
    {
        this.game=game;
        this.level=level;
        gamecam=new OrthographicCamera();
        gameport=new StretchViewport(820/Fruits.PPM,580/Fruits.PPM,gamecam);
        stage=new Stage(gameport,((Fruits) game).batch);
        background=new Texture("Wining.jpg");

        gamecam.position.set(gameport.getWorldWidth() , gameport.getWorldHeight() , 0);
        temp=0;

        counter=100;
        world=new World(new Vector2(0,-10),true);
    }
    @Override
    public void show() {

    }
    public void handleinput(float dt)
    {
        if (counter<0)
        {
            game.setScreen(new PlayScreen(game,level));
        }
    }
    public void update(float dt)
    {
        handleinput(dt);
        world.step(1 / 60f, 6, 2);

        gamecam.update();
    }
    @Override
    public void render(float delta) {
        float level;
        update(delta);
        Gdx.gl.glClearColor(0, 0, 0, 0);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        counter--;
        game.batch.begin();
        game.batch.draw(background, 0, 0, Gdx.graphics.getWidth()/2,Gdx.graphics.getHeight()/2);

        game.batch.end();

    }

    @Override
    public void resize(int width, int height) {
        gameport.update(width, height);

    }

}


texts: Unity Collaborate Error: "It looks like you don't have any data yet"

texts:
On the Unity Developer page, my partner has added me to his team. I can see his project. I clicked Go to Collaborate:

That brings me to the "Assets" tab, saying "It looks like you don't have any data yet."

Clicking on the provided link just brings me back to the main page, where no detailed instructions can be found.

Has anyone successfully used the new "Unity Collaborate" feature yet?


texts: How can I create and animate 2D skeletons for HTML5 Javascript games?

texts:
I'm trying to make a 2D fighting game in HTML5(somewhat like street fighter). So basically there are two players, one AI and one Human. The players need to have animations for the body movements. Also, there needs to be some collision detection system. I'm using createjs for coding but to design models/objects/animations, I need some other software.

So I'm looking for a software that can:

easily make custom animation of 2d objects. The objects
structure(skeleton etc.) will be same once defined but need to be
defined once.
Can export the animations and models in a js readable
    format(preferably json)

Collision detection can be done easily after
the exported format is loaded in a game engine.

For point 1, I'm looking for some generic skeleton based animation. Sprite-sheet based animations will be difficult for collision detection.


texts: Transition between normal and slow motion

texts:
I have a game (C++) in which I want to transition between two speeds of motion. For illustration, the player raises their weapon to aim, and whilst this is in progress over a known duration, time should slow down incrementally until it reaches the target rate.

Slowing it down linearly is easy. We have a start speed (e.g. 1.0), an end speed (e.g. 0.2), and can determine where we are in the fixed-length transition (e.g. 2000ms)

However if I slow it down linearly, the look and feel is just wrong. I suspect that to feel 'right', it should slow down quickly early in the transition, and then at a decreasing rate towards the end.

My maths is less than brilliant; it's been a long time since I graphed a function, and I rarely if ever introduce this kind of stuff into code. At a guess, using part of a 1/x or x^2 curve might give me what I want, but I'd still have to parametrise it to suit.

This or something like it must be a regularly-solved problem, so what's the simplest approach I can use here?


texts: How can I get all DontDestroyOnLoad GameObjects?

texts:
I need to Destroy all DontDestroyOnLoad GameObjects.  But in order to do this, I first need to find them all.  I would prefer to automate this, opposed to having to manually reference each one.

DontDestroyOnLoad GameObjects seem to all be in the shared scene, "DontDestroyOnLoad".  So I tried collecting all root GameObjects from this Scene, but it says it is an invalid scene.

private void DestroyDontDestroyOnLoadGameObjects()
{
    var dontDestoyOnLoadScene = SceneManager.GetSceneByName("DontDestroyOnLoad");
    var dontDestroyOnLoadGameObjects = dontDestoyOnLoadScene.GetRootGameObjects();
    foreach (var dontdestroyGameObject in dontDestroyOnLoadGameObjects)
    {
        Destroy(gameObject);
    }
}

How can I Destroy all of the GameObjects that have DontDestroyOnLoad called on them?


texts: I am looking to track many in-game events, e.g. the score of each move, how many moves are taken, what types of moves, etc. A lot of stats can simply be tracked with a counter. In some cases I need to aggregate data in order to calculate the value (e.g. most common move). How are you tracking in-game stats for your games? How do you avoid creating a class with tens or hundreds of fields? How do you avoid littering the code with tracking invocations? How do you abstract the aggregate data so as to avoid rewriting it for each scenario?


texts: Unity Inspector Not Showing Serialized Variables Of Child

texts:
So I'm new to using Serialaiziblewtfever(I just cannot remember the correct spelling). In the Unity editor it works fine if I have something like:

[System.Seriliabizblewtfever]
Public class BaseClass{
    public ChildClass showvariables;
}
[System.serializable]
Public class ChildClass{
    public float nipz;
}

With that I can see the variables "nipz" in the inspector when I click the drop-down arrow. However, I want ChildClass to be an actual child class so I can manipulate variables inherited from the parent. So if I change it to:

Public class ChildClass:BaseClass

It stops working. It doesn't matter what class the "BaseClass" is. In the inspector it shows me "showvariables", but then has the field like how you can drag objects, transforms, etc, but no drop down list of any variables. Is there something I'm missing?