texts: How can I rotate an object with random speed with some delays?

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

public class Turn_Move : MonoBehaviour {
    public int TurnX;
    public int TurnY;
    public int TurnZ;

    public int MoveX;
    public int MoveY;
    public int MoveZ;

    public bool World;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        if (World == true) {
            transform.Rotate(TurnX * Time.deltaTime,TurnY * Time.deltaTime,TurnZ * Time.deltaTime, Space.World);
            transform.Translate(MoveX * Time.deltaTime, MoveY * Time.deltaTime, MoveZ * Time.deltaTime, Space.World);
        }else{
            transform.Rotate(TurnX * Time.deltaTime,Random.Range(3,300) * Time.deltaTime,TurnZ * Time.deltaTime, Space.Self);
            transform.Translate(MoveX * Time.deltaTime, MoveY * Time.deltaTime, MoveZ * Time.deltaTime, Space.Self);
        }
    }
}

This is the random part :

Random.Range(3,300)

but sine it's changing the random numbers too quick the changes are almost not visible. I want somehow to make that if for example the next random will stay for example 5 seconds at this speed number then move to the next random number and again stay at this number 5 seconds and so on.

Tried this :

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

public class Turn_Move : MonoBehaviour {
    public int TurnX;
    public int TurnY;
    public int TurnZ;

    public int MoveX;
    public int MoveY;
    public int MoveZ;

    public bool World;

    private bool IsGameRunning = false;

    // Use this for initialization
    void Start ()
    {
        IsGameRunning = true;
        StartCoroutine(SpeedWaitForSeconds());
    }

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

    }

    IEnumerator SpeedWaitForSeconds()
    {
        var delay = new WaitForSeconds(3);//define ONCE to avoid memory leak
        while (IsGameRunning)
        {
            if (World == true)
            {
                transform.Rotate(TurnX * Time.deltaTime, TurnY * Time.deltaTime, TurnZ * Time.deltaTime, Space.World);
                transform.Translate(MoveX * Time.deltaTime, MoveY * Time.deltaTime, MoveZ * Time.deltaTime, Space.World);
            }
            else
            {
                transform.Rotate(TurnX * Time.deltaTime, Random.Range(3, 300) * Time.deltaTime, TurnZ * Time.deltaTime, Space.Self);
                transform.Translate(MoveX * Time.deltaTime, MoveY * Time.deltaTime, MoveZ * Time.deltaTime, Space.Self);
            }

            yield return delay;//wait
        }
    }
}

but that just rotate the object once each 3 seconds. and not rotating it all the time with speed changing every 3 seconds.

but now it's not rotating for 3 seconds it rotating every 3 seconds.

better to describe what I want is like intervals. The object should spin all the time nonstop like i Update but then each 3 seconds to change for a random speed.

for example spin at speed 5 ....after 3 seconds spin at speed 77 ....after 3 second spin at speed 199


texts:
I am trying to rebuild the fur effect in Viva Pinata.

Here each square becomes a pattern of fur

I imagine the process to be like this...

U lift one end of the triangles.

Now I need to achieve "lifting one end of square". I can do either vertex, fragment, geometry shader. However I am clueless when it comes to determining which vertex is "end of square", so that I know which vertex to lift up.


texts: Why does applying force to a game object apply force to children, as well?

texts:
I have a script on my player to move.  I do not have root motion applied because, root motion does not work perfectly so I'm manually adding velocity to the player.

The player is holding a ball and the ball is a child of the player.  However, when I apply force to the player it seems to apply force to the ball so he stops holding it and it is just floating around instead.

My player and my ball both have rigidBodies and I'm applying force like this.

    var velocityX = horizontal * HorizontalSpeed * Time.deltaTime;
    var velocityZ = vertical * VerticalSpeed * Time.deltaTime;

    rigidBody.velocity = new Vector3(velocityX, 0f, velocityZ);

I know as a hack I can apply a late update to the ball, but I'd rather understand what is going on.

Can anyone help me figure this out?


texts: How do I differentiate between the two Vive motion controllers?

texts:
I am working with a Vive Pre (devkit) and I have most everything working the way I want it to. However I am wondering how do I refer to or even know which motion controller is which? From what I can tell the headset is ALWAYS assigned first into a list, and the others are seemingly randomly assigned.

So how do I differentiate between the two or refer to one separately?


texts: Should I implement anti-aliasing by rendering large and scaling down?

texts:
Having read about anti-aliasing, I came to realise that I could render my scene 8× the original size of the screen, then shrink it to render it on my original screen to improve the effect that I have rendered on the screen.

Is this a good idea? How can I do this? Do I need a shader?


texts:
I'm trying to rotate my characterController around with the mouse movement.
I've tried to do so with this:

rotLeftRight = Input.GetAxis("Mouse X") * MOUSESENSIVITY * Time.deltaTime;
 rotUpDown = -Input.GetAxis("Mouse Y") * MOUSESENSIVITY * Time.deltaTime;

It works fine when I just move the mouse, but Input.getAxis returns 0 if you don't move the mouse, even if it's already on a corner of the screen. Is this normal?

What I need is something that returns 0 only when the mouse is in the center of the screen. I don't know if that is posible using Input.GetAxis or I should use another function.

Anybody can help me with this?


texts: How can I detect if a gameObject has collided with two other specific objects at the same time?

texts:
How can I detect if a gameObject has collided with two other specific objects AT THE SAME TIME?

This is what I intend to do but it does not work:

void OnCollisionEnter (Collision col)
{

if(col.gameObject.name == "object1" && "object2")
{
    Destroy(gameObject);
}
}

How can I correct this piece of code?


texts: Legal issues for a "fangame" of a commercial franchise?

texts:
I've played around in the past of the 2D Flash fan-made version of the popular Valve game Portal.  It has basically the exact same mechanics, but as a 2D side-view flash game.

Lately I've toyed around with creating a simplified flash version of some of my favorite franchises (such as Zelda, Mario, Splinter Cell, etc.).  Of course, nothing is "stopping" me from just using the same mechanics and just changing the name to something not copyrighted.

I have witnessed projects that have tried to directly port a 3D game into a 2D simplified version, with the exact same plot and puzzles (Ocarina of Time in 2D comes to mind), and I have seen them being shut down.  But I am not likely going to exactly duplicate any game...just borrow some of the source material and basic underlying mechanics.

For example, if I were to make a Zelda-influenced fan game, I would have items such as the Hookshot, Boomerang, and all other sorts of ones from the Gameboy Zeldas; just with a custom plot and dungeons.  With likely the same mechanics.

What are the legal issues involved in this?  I used to think it was a "Don't do this ever; it's a bad idea."

But then I've seen the Portal clone, and now I'm curious.


texts: Setting up cube map texture parameters in OpenGL

texts:
I see alot of tutorials and sources use the following code snippet when defining each face of a cube map:

for (i = 0; i < 6; i++)
    glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, InternalFormat, size, size, 0, Format, Type, NULL);

Is it safe to assume GL_TEXTURE_CUBE_MAP_POSITIVE_X  + i will properly iterate the following cube map targets, GL_TEXTURE_CUBE_MAP_NEGATIVE_X, GL_TEXTURE_CUBE_MAP_POSITIVE_Y, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y etc?


texts:
I have a game idea with lots of pretty lights (literally) in mind that I would really love to implement, but I have essentially zero experience with shadow mapping, deferred rendering, the lot of it. I've done some research into 2D shadow-casting, and I think I might try a method similar to this, but I haven't a fathom how to create a virtual rectangular manipulation of a polar image (from the point-light's perspective on the map).

My question: How can I create a virtual rectangular manipulation of a polar image whose process is quick enough that it can be run twice per frame every time a light moves in-game?

I'd like to be able to handle at least 4 dynamic lights on-screen at any time, but I'll take what I can get. I've started to learn OpenGL, so hopefully this isn't too high above my skill level.


texts: How do I generate a random map with islands (like the Earth), using Perlin Noise, on a tilemap in Unity?

texts:
EDIT: I've tried this with Perlin Noise with no success, then with Voronoi diagrams, and now I'm editing the question to reflect the issues I had with Perlin Noise, trying again.

I'm developing a game in Unity and trying to build a map generator that is capable of creating random maps like the Earth, on a 2D tilemap. The map should contain 2 types of tiles (let's call them grass and ground), while the grass should be the "main" tile, and there should be islands of ground on top of the grass.

This was already asked here. My purpose is to create something like the second picture in the question (that picture is showing water and grass, but it doesn't really matter).

This blog post suggested a simple way to fill a map (2d array) with Perlin Noise values (float numbers between 0-1), which I did. Eventually each value was rounded to 0 or 1 to present a grass or ground tile.

What I can control now is the frequency of the noise, but it's not enough.

The map generated by the code below: (frequency of 0.3)

The problems with this method:

No randomness. I know Perlin Noise is NOT a random function, so how can I add random factors to generate a different map each time?
How can I control the number of islands (e.g.: with a factor that can determine "more islands" or "less islands", not an approx. number)?
How can I control the size of each island (again, with a factor. I don't care about exact size)?

My code: (C#)

using System;
using UnityEngine;
using UnityEngine.Tilemaps;
using Random = UnityEngine.Random;

namespace TankMayhem {

    public class GroundTilemapGenerator : MonoBehaviour {

        private const string TilesPath = "Tiles";
        private Tilemap tilemap;
        private TileBase[] possibleTiles = new TileBase[2];

        private void Awake() {
            tilemap = GetComponent<Tilemap>();
            var tiles = Resources.LoadAll<Tile>(TilesPath);

            possibleTiles[0] = Array.Find(tiles, tile => tile.name == "ground");;
            possibleTiles[1] = Array.Find(tiles, tile => tile.name == "grass");

            int i;
            int j;
            int[, ] map = new int[tilemap.size.x, tilemap.size.y];

            const float Frequency = 0.3f;
            PerlinNoiseCave(map, Frequency);

            float[] probabilities = new float[2];

            foreach (var position in tilemap.cellBounds.allPositionsWithin) {
                i = position.x;
                j = position.y;

                var tile = possibleTiles[map[i, j]];
                tilemap.SetTile(position, tile);
            }
        }

        private static int[, ] PerlinNoiseCave(int[, ] map, float frequency) {
            for (int i = 0; i < map.GetUpperBound(0); i++) {
                for (int j = 0; j < map.GetUpperBound(1); j++) {
                    // Generate a new point using Perlin noise, then round it to a value of either 0 or 1
                    map[i, j] = Mathf.RoundToInt(Mathf.PerlinNoise(i * frequency, j * frequency));
                }
            }
            return map;
        }
    }
}


texts: Black stripes at the junctions of road segments

texts:
I made a simple runner where the road is dynamically generated, and the sphere together with the camera moves with the help of Rigidbody velocity, but the problem is that black bars appear at the joints between segments, and if you add an AddForce sphere, then the sphere at the joints jumps which should not be. How to solve this problem

I checked the positions of the segments, they fully correspond to the desired ones, that is, there are no gaps between them, I use the standard shader

Segments 10.4 units in size. Imported from Blender, but if you take the standard cube model then the same thing (black bars), so that’s not the point. Positions between these segments:

The segment before (on which the sphere in the screenshot)

and the next segment

Road Material Settings:


texts: Why does the volume not decrease when I move away from the AudioSource?

texts: I created a simple scene with an audio source and a player that can move. The main camera is a child object of the player. I set the audio source volume rolloff to "logarithmic rolloff". As far as I understand, this means that the sound should become weak very fast when the main camera moves away from the audio source. But this does not happen: as I move the player (with the camera) away from the audio source, the volume remains the same. I see, in the rolloff graph of the audio source, a line denoted by "Listener", which moves to the right as the camera moves away from the source. But still, the volume remains the same. Why?


texts:
I am trying to create dialogue boxes that contain the profile picture of the speaking character in them. As such, I want the profile pic to be attached to the object itself. If I understand this right, the following creates a variable space for profilePic that I then populate within the GUI.

using UnityEngine.UI;

public class NPC : Character {

[SerializeField] private Image profilePic;
}

Then over in my dialogue script I have the following:

using UnityEngine.UI;

//This currently only allows for one sided conversations
//this can be later modified to add profile picture as well as several iterated conversations

public class Dialogue : MonoBehaviour {

    [SerializeField]
    private UnityEngine.UI.Text dialogueText;

    [SerializeField]
    private GameObject dialoguePanel;

    [SerializeField]
    private UnityEngine.UI.Image profilePic;

    private string[] dialogue;
    private int dialogueIndex;

    public void StartDialogue(string[] dialogue)
    {

        dialogueIndex = 0;
        this.dialogue = dialogue;
        dialoguePanel.SetActive(true);
        //This is what actually affects the GUI
        dialogueText.text = dialogue[dialogueIndex];
        this.profilePic = profilePic;

    }

The dialogue functions work. It should be taking the contents of this.profilePic and putting them into the UI.image profilePic component, right? The text works. The panel pops up. Just no picture.

Anyone have any thoughts?


texts: How can I duplicate a GameObject with the correct number of copies?

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

public class FormationsManager : MonoBehaviour
{
    public GameObject squadMemeberPrefab;
    public int numberOfSquadMembers = 20;
    public int numberOfSquads = 1;
    public int columns = 4;
    public int gaps = 10;
    public Formations formations;

    private int numofmembers;
    private int numofsquads;
    private GameObject squadToClone;
    private List<GameObject> SquadMembers = new List<GameObject>();

    // Use this for initialization
    void Start()
    {
        squadToClone = GameObject.Find("Squad");
        numofmembers = numberOfSquadMembers;
        numofsquads = numberOfSquads;
        formations.Init(numberOfSquadMembers, columns, gaps);
        GenerateSquad();
    }

    // Update is called once per frame
    void Update()
    {
        if (numofmembers != numberOfSquadMembers)
        {
            numofmembers = numberOfSquadMembers;
            formations.Init(numberOfSquadMembers, columns, gaps);
            GenerateSquad();
        }

        if (numofsquads != numberOfSquads)
        {
            numofsquads = numberOfSquads;
            for (int i = 0; i < numberOfSquads; i++)
            {
                Instantiate(squadToClone);
            }
        }
    }

    private void GenerateSquad()
    {
        GameObject go = squadMemeberPrefab;
        List<GameObject> newSquadMembers = new List<GameObject>();

        int i = 0;
        for (; i < formations.newpositions.Count; i++)
        {
            if (i < SquadMembers.Count)
                go = SquadMembers[i];
            else
                go = Instantiate(squadMemeberPrefab);
            go.transform.position = formations.newpositions[i];
            go.tag = "Squad Member";
            go.transform.parent = gameObject.transform;
            newSquadMembers.Add(go);
        }

        for (; i < SquadMembers.Count; i++)
            Destroy(SquadMembers[i]);

        SquadMembers = newSquadMembers;
    }
}

In the Update I duplicate the squad:

if (numofsquads != numberOfSquads)
            {
                numofsquads = numberOfSquads;
                for (int i = 0; i < numberOfSquads; i++)
                {
                    Instantiate(squadToClone);
                }
            }

The problem is that if for example when running the game there is 1 squad and then I'm changing the value of numberOfSquads to 3 then instead duplicating more 2 squads it will duplicate more 3. And then if I will change the value of numberOfSquads from 3 to 4 it will add more 4 squads instead only 1.

And I also want to make that if I change the value of numberOfSquads to be lower then destroy the last squad/s.


texts: What algorithm can I use to distribute energy between connected nodes?

texts:
I'm creating a game where every user has a network of connected nodes that each have a specific amount of energy. The nodes will try to distribute energy evenly amongst themselves. If a node has more energy than the average, it should deliver to the network. If a node has less than the average, it should receive from the network. An example network would be this, where + means more than average and - means less than average:

Now the one question I've been trying to solve for a while now: how can I calculate the cumulative amount of energy that flows through every edge until all nodes have the same amount of energy? For example we know that the node in the top left will in the end distribute 7 energy to the network, but will it give 5 down and 2 to the right? Or something else?

Is there any algorithm we could use to solve that problem? Could we potentially represent this problem as an electric circuit and solve it like that?


texts:
I need to build some sort of engine that can take a multivariable function such as

f(x,y) = cos(x) + y

and produce it's graph in 3D space.

Is there a recommended method of doing that?


texts: MonoGame SetRenderTarget is wiping the backbuffer

texts:
In my Monogame (XNA) Windowed App, compiled for Windows PC, running on Windows 7, I have

public RenderTarget2D renderTarget = null;

In the Inititate() function I have

renderTarget = new RenderTarget2D(graphicsDevice, 200, 200, false,
                           graphicsDevice.PresentationParameters.BackBufferFormat,
                           graphicsDevice.PresentationParameters.DepthStencilFormat);

My drawing is as follows

public override void Draw(GameTime gameTime)
{
    base.Draw(gameTime);

    // POSITION A

    // draw some stuff to the back buffer
    graphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer,
                         backgroundColor, 1, 0);

    SceneRoot.Draw(gameTime);    // draw some 3d primitives

    spriteBatch.Begin();
    spriteBatch.Draw(...some things...);
    spriteBatch.End();

    // POSITION B

    spriteBatch.Begin();
    spriteBatch.Draw((Texture2D)renderTarget, new Vector2(5f, 200f),
                     new Rectangle(0, 0, renderTarget.Width, renderTarget.Height),
                     Color.White);
    spriteBatch.End();
}

If I put the following code to draw to the renderTarget in POSITION A then I can see the stuff drawn between POSITION A and POSITION B, with the stuff drawn to the renderTarget on top, as expected.

If I put the following code in POSITION B then I can't see anything drawn between POSITION A and POSITION B, just the stuff drawn to the renderTarget.

graphicsDevice.SetRenderTarget(renderTarget);
graphicsDevice.Clear(Color.Red);
spriteBatch.Begin();
spriteBatch.Draw(...some things...);
spriteBatch.End();
graphicsDevice.SetRenderTarget(null);

With the above code for insertion, I can even reduce it to

graphicsDevice.SetRenderTarget(renderTarget);
graphicsDevice.SetRenderTarget(null);

and still get the same result (only see what is drawn to the renderTarget, which is now nothing, ie a blank screen). I've tested, and it's the SetRenderTarget(renderTarget) that's causing the problem, seemingly by wiping the backbuffer.

Oh, and none of the sprites drawn cover the whole display, so it's not the sprites displaying wrong, I don't think, as I should still see the 3d stuff.

I've looked and I don't see anything in SetRenderTarget about wiping the backbuffer. Can anyone help? Is it something else, like something to do with the RenderState or the Effects? I can provide more of my code if need be.


texts:
I'm trying to get the mouse click position on a terrain geometry, but multiple times in each frame; doing it on the CPU was way too slow, so I'm trying to do it with a compute shader. I can't seem to get a valid result back. I guess it's somehow related to my raydirection/rayorigin vectors, because I tried 4 different written DirectX HLSL solutions, but none of them works for my case; though, I did have to modify them. Anyway, this is my code to generate the ray vectors:

XMFLOAT3 RayOriginFloat = m_Camera->GetPosition(); //The eye position of the camera. I use this vector in the compute shader.

XMVECTOR worldPos;
XMVECTOR RayOrigin = XMLoadFloat3(&RayOriginFloat);
DirectX::BoundingFrustum frustum;

// I use the DirectXMath XMVector3Unproject method to project the mouse coord to worldspace.
ScreenToWorld(m_mouseX, m_mouseY, &worldPos);

XMVECTOR RayDir = worldPos - RayOrigin;
RayDir = XMVector3Normalize(RayDir); //And finally the normalized direction vector

And this is the HLSL code:

cbuffer RayBuffer
{
    float3 RayOrigin;
    float3 RayDir;
    matrix view;
};

struct ComputeInputType
{
    float3 position : POSITION;
    float2 tex : TEXCOORD;
    float3 normal : NORMAL;
};

struct ComputeOutputType
{
    float distance;
    float3 position;
};

static const uint ThreadSize = 32;

StructuredBuffer<ComputeInputType> BufferIn : register(t0);
RWStructuredBuffer<ComputeOutputType> BufferOut : register(u0);

[numthreads(ThreadSize, ThreadSize, 1)]
void PickingCSMain(uint3 dispatchThreadID : SV_DispatchThreadID)
{
    float result;
    float3 vertices[3];
    float3 edge[2];

    if (dispatchThreadID.x < 64 && dispatchThreadID.y < 64)
    {
        vertices[0] = BufferIn[(dispatchThreadID.x + dispatchThreadID.y * ThreadSize * 2)].position;
        vertices[1] = BufferIn[(dispatchThreadID.x + (dispatchThreadID.y + 1) * ThreadSize * 2)].position;
        vertices[2] = BufferIn[(dispatchThreadID.x + 1 + (dispatchThreadID.y + 1) * ThreadSize * 2)].position;

        edge[0] = vertices[1].xyz - vertices[0].xyz;
        edge[1] = vertices[2].xyz - vertices[0].xyz;

        float3 normal = normalize(cross(edge[0], edge[1]));
        float b = dot(normal, RayDir);

        float3 w0 = RayOrigin - vertices[0].xyz;
        float a = -dot(normal, w0);
        float t = a / b;

        result = t;

        float3 p = RayOrigin + t * RayDir;
        float uu, uv, vv, wu, wv, inverseD;
        uu = dot(edge[0], edge[0]);
        uv = dot(edge[0], edge[1]);
        vv = dot(edge[1], edge[1]);

        float3 w = p - vertices[0].xyz;
        wu = dot(w, edge[0]);
        wv = dot(w, edge[1]);
        inverseD = uv * uv - uu * vv;
        inverseD = 1.0f / inverseD;

        float u = (uv * wv - vv * wu) * inverseD;
        if (u < 0.0f || u > 1.0f)
        {
            result = -1.0f;
        }

        float v = (uv * wu - uu * wv) * inverseD;
        if (v < 0.0f || (u + v) > 1.0f)
        {
            result = -1.0f;
        }

        BufferOut[(dispatchThreadID.x + dispatchThreadID.y * ThreadSize * 2)].distance = result;
        BufferOut[(dispatchThreadID.x + dispatchThreadID.y * ThreadSize * 2)].position = vertices[0].xyz;
    }
}

The result is always -1.0f. I don't get it; I might have made a big mistake, but I can't find where.

Why does my triangle ray intersection test always return -1.0f?


texts: How to annotate a BinaryFormatter packet with a header describing its length?

texts:
I am working on a project that is sending data from pc to tablet via usb, using android adb. To serialize the data, we are using BinaryFormatter. The problem I'm running into is that the client is sending packets of size 1161 bytes.
Now I could hard code in 1161 as the length of the byte array on the receiving in, and this would fix my problem. But what I would rather do is put the length in the header of the packet being sent, so the receiving end can check that and create the packet according to the size, just incase we get a different packet type of a different size.
However, BinaryFormatter also encodes the names of the fields, so as far as I can tell, you can't determine the length the object will be before serializing it, at which point, it's too late to set the length property in the header.
Does any one know a solution to this that will elegantly handle different packet sizes, and packets over the size of 1024 bytes? Thank you!


texts: RPC's in Legacy Unity, what to use in Unity 5.1?

texts:
I have created a small experiment in 5.1, a server has an AI character pathfinding around a map over a grid, so its a straight line node to node before it reaches the end.

I would like for the client to also view this pathfinding character.

Using the networking scripts built in it sends fine, however the client see's a stuttering character and not something smooth like the server sees. So my solution to this is that when the server calculates the new node for the character to go to that the location of this node is sent to the client, the client moves its character to the node and so on. So instead of constant transform data being sent, the clients AI can go to the node and wait for the next node location to be sent, therefore being smooth.

In previous versions of Unity I would've used RPC's, but this is labelled as Legacy now, what can I use now to send a node location from the server to the client?


texts: FlashPunk + Flashdevelop - How to use sponsor provided preloader

texts:
I have developed a flash game using FlashPunk (on FlashDevelop). And now that I am trying to add a sponsor preloader and splashscreen to my game, I realize the flashpunk forums are down, and have been for over a week now :( Speak of bad timing.

I imagine some of you here do use FlashPunk. How have you managed to add such sponsor stuff to your game? I haven't had to deal with swf and fla at all until now.

The sponsor's preloader is an actual loading bar, at the end of which it also plays an animated splash screen.

Any help would be much appreciated.

Thanks!


texts: How to restart the game when pressed enter in XNA

texts:
If the following code allows the game to exit when pressed esc ..

if (gamePad.Buttons.Back == ButtonState.Pressed
    || keyboard.IsKeyDown(Keys.Escape))
{
    this.Exit();
}

Then this code should allow the game to restart when pressed enter...

if (gamePad.Buttons.Back == ButtonState.Pressed
    || keyboard.IsKeyDown(Keys.Enter))
{
    this.Reset(); //<< PROBLEM HERE!!
}

What do I put here? Because Reset is not the keyword for it...
I'm a beginner so if this is so wrong and stupid I am  sorry.


texts: PacMan character AI suggestions for optimal next direction

texts:
Firstly, this is AI for PacMan and not the ghosts.

I am writing an Android live wallpaper which plays PacMan around your icons. While it supports user suggestions via screen touches, the majority of the game will be played by an AI. I am 99% done with all of the programming for the game but the AI for PacMan himself is still extremely weak. I'm looking for help in developing a good AI for determining PacMan's next direction of travel.

My initial plan was this:

Initialize a score counter for each direction with a value of zero.
Start at the current position and use a BFS to traverse outward in the four possible initial directions by adding them to the queue.
Pop an element off of the queue, ensure it hasn't been already "seen", ensure it is a valid board position, and add to the corresponding initial directions score a value for the current cell based on:

Has a dot: plus 10
Has a power up: plus 50
Has a fruit: plus fruit value (varies by level)
Has a ghost that is frightened: plus 200
Has a ghost travelling toward PacMan: subtract 200
Has a ghost travelling away from PacMan: do nothing
Has a ghost travelling perpendicular: subtract 50
Multiply the cell's value times a pecentage based on the number of steps to the cell, the more steps from the initial direction, the closer the value of the cell gets to zero.

and enqueue the three possible directions from the current cell.
Once the queue is empty, find the highest score for each of the four possible initial directions and choose that.

It sounded good to me on paper but the ghosts surround PacMan extremely rapidly and he twitches back and forth in the same two or three cells until one reaches him. Adjusting the values for the ghost presence doesn't help either. My nearest dot BFS can at least get to level 2 or 3 before the game ends.

I'm looking for code, thoughts, and/or links to resources for developing a proper AI--preferably the former two. I'd like to release this on the Market sometime this weekend so I'm in a bit of a hurry. Any help is greatly appreciated.

FYI, this was originally posted on StackOverflow


texts: Moving a continue condition into the for loop produced something NOT logically equivalent?

texts:
I'm setting up a hex grid. The column/row system I use puts 0, 0 as the top left corner, and increasing columns (x) moves to the right but also vertically upwards. So columns run straight up and down, but rows run to the right but slanted upwards a bit.

This code...

for (j = 0; j < bd*2-1; j += 1) // bd is "board dimension", in my case 9
{
  for (i = 0; i < bd*2-1 and i < j+bd; i += 1)
  {
    if (i <= j-bd)
      continue;

    scr_ini_hex(i, j, bxo + i*hs, byo + j*hh - i*vs); // bxo and byo are arbitrary board x/y origins where the first cell is drawn, hs, hh, and vs are the gaps between cells in horizontal and vertical directions.
  }
}

produced this:

which is exactly what I want, a large hexagon with 9 smaller hexagons on each side.

So I thought I would be sophisticated and move that continue condition into the for loop. I wrote this...

for (j = 0; j < bd*2-1; j += 1)
{
  for (i = 0; i < bd*2-1 and i < j+bd and i > j-bd; i += 1) // added "i > j-bd", basically migrated the condition into this inner loop
  {
    //if (i <= j-bd)
      //continue;

    scr_ini_hex(i, j, bxo + i*hs, byo + j*hh - i*vs);
  }
}

and it produced this:

What went wrong here? I thought they were logically equivalent (except negating the condition, because the continue code was like a do until, but the for condition is like a do while).


texts:
So I’ve created a small app that is designed to be used on smartphones and tablets. Accordingly the app makes use of the sf::Touch class which determines the point on the screen of the device that the finger of the user is touching. This is required because central to the functionality of the app is that it allows the user to swipe across the screen to flick between different images. The end result should be that once a user’s finger (being pressed against the screen) has moved far enough to the left or right periphery of the screen, a swipe function is initiated and the next image moves into view. This appears in the code like so:

if (touchInput.isDown(0))
{
    sf::Vector2i currPos;
    currPos = touchInput.getPosition(0);
    if (currPos.x < 540.0)
    {
        leftSwipe(currPos);
    }
    else if (currPos.x > 540.0)
    {
        rightSwipe(currPos);
    }
    oldPos = currPos;
}

The problem is that I am testing the application on the PC and when I click the left mouse button down (which I assumed would cause the function touchInput.isDown(0) to return true) it does not appear to update the position of touchInput and was therefore wondering if touchInput should be used on the PC at all and also if it even functions with PC inputs (like a mouse)? or whether for PC testing it would be better to use sf::Mouse instead?


texts: 2D Platformer Collision/Physics Problems

texts:
I'm making a 2D platformer similar to Terraria, although I'm having some problems with some collision detection code. I'm using the code from the AppHub Platformer sample, but tweaked so it fits with my character size and tilesize. Although, I am having a few problems:

If I box myself in, and then jump. Instead of just canceling the jump it will move me through a wall (most likely to the right) and then when it can jump, it performs the jump.

Next problem I'm having is if I have a 1x1 gap above the character, I am freely able to jump through it. The character size is 2 blocks wide by 3 high.

I don't want to use a physics engine because I will not be using 95% of the features, and I don't really want to add it if i'm not going to use most of it. I just require a basic collision detection and basic physics. Honestly, I can't see anything wrong with my code and it's pretty much the same as the sample. Just by changing the tile size must have added these bugs and I'm not exactly sure how to fix it. This is my existing code.

Basically, what I'm asking is: How could I modify my current system to eliminate these bugs, or what new system could I implement to have a better, fully functional physics system without these bugs. (Without implementing a whole engine).


texts: How do I repeatedly move an image by 1 pixel?

texts:
I have a method that is moving a UIImageView called shootImg across the screen:

-(IBAction)shoot{
if (appDelegate.shootInt > 0) {
    if (direction == 1) {
            shootImg.center = CGPointMake(shootImg.center.x+1, shootImg.center.y);
            appDelegate.shootInt = appDelegate.shootInt - 1;
            shootLabel.text = [NSString stringWithFormat:@"%d", appDelegate.shootInt];
                }

This does seem to work. But it only moves shootImage 1 pixel. What I want to do is make it repeatedly move 1 pixel. I tried a while loop but that didn't seem to work. I'm not using cocos2d or anything like that and if you need to see more code just ask.

Thanks :)


texts: Can I query the Game Center APIs from C++, without Objective-C?

texts:
I am writing a game that needs Game Center leaderboards. These however, are not very extensive leaderboards. I just need the ability to submit a score automatically when the player completes a level. Then, when a player visits a specific in game screen, it queries his/her position on the leaderboard and returns the value and the position. I don't need the UI, or any achievements. Just need those values.

Is this information possible to query using C++? I am using Cocos2d-x and would like to keep all of it C++ if possible.


texts:
Soon after I press the Play button, the Unity break button automatically gets activated: Unity gets into Pause mode:

I have attached the Unity debugger to my C# code, but Visual Studio doesn't break.

How could I find out the reason why Unity goes into Break mode?

Thank you!

Edit: Per request, here is the button before pressing Play:

And here is what the console looks like after the error occured:


texts: How to iterate tiles around an index tile?

texts:
I am not exactly sure how to state this question, what I basically want to do is to seed a tile based map with some values. So I asked myself how I could spread some values outgoing from a start tile, with values being reduced the further I get away from that start tile. Does that make any sense? What algorithms are there to calculate spreading of fire for example, or pollution?

[0,0,0,0,0,0,0,0,
 0,0,0,0,0,0,0,0,
 0,0,0,0,0,0,0,0,
 0,0,0,0,S,0,0,0,
 0,0,0,0,0,0,0,0,
 0,0,0,0,0,0,0,0,
 0,0,0,0,0,0,0,0,]

[0,0,0,0,0,0,0,0,
 0,0,2,2,2,2,2,0,
 0,0,2,3,3,3,2,0,
 0,0,2,3,X,3,2,0,
 0,0,2,3,3,3,2,0,
 0,0,2,2,2,2,2,0,
 0,0,0,0,0,0,0,0,]

And what if I have another starting tile,
can the values be added?

[2,3,3,3,2,0,0,0,
 2,3,Y,5,4,2,2,0,
 2,3,5,6,5,3,2,0,
 2,2,4,5,X,3,2,0,
 0,0,2,3,3,3,2,0,
 0,0,2,2,2,2,2,0,
 0,0,0,0,0,0,0,0,]

Maybe it's like an explosion. Not sure what to look for though, I cannot find anything in my endless searches on tile based games.


texts: In unity I can create a normal map out of a black and white image (By changing the type to normal map and select create from grayscale) Im wondering if there is a way to export the normal map like it should look so I don't need to create it from grayscale when I use it in another project?


texts: What's the difference between Collision layers and Collision masks?

texts: In PhysicsBody and PhysicsBody2D in GoDot, there are two attributes called Mask (PhysicsBody| Collision| Collision and Mask). I noticed that a body collides with another body if they have a layer in common or a mask in common. But then, if there's already a collision layer, what's the purpose of the mask?


texts:
I've been playing with implementing dynamic level of detail for rendering a very large mesh in XNA.

It occurred to me that (duh) the whole point of this is to generate small triangles close to the camera, and larger ones far away. Given that, rather than constantly modifying or swapping index buffers based on a feature's rendered size or distance from the camera, it would be a lot easier (and potentially quite a bit faster), to render a single "fan" or flat wedge/frustum-shaped planar mesh that is tessellated into small triangles close to the near or small end of the frustum and larger ones at the far end, sort of like this (overhead view)

(Pardon the gap in the middle - I drew one side and mirrored it) The triangle sizes are chosen so that all are approximately the same size when projected.

Then, that mesh would be transformed to track the camera so that the Z axis (center vertical in this image) is always aligned with the view direction projected into the XZ plane. The vertex shader would then read terrain heights from a height texture and adjust the Y coordinate of the mesh to match a height field that defines the terrain.

This eliminates the need for culling (since the mesh is generated to match the viewport dimensions) and the need to modify the index and/or vertex buffers when drawing the terrain.

Obviously this doesn't address terrain with overhangs, etc, but that could be handled to a certain extent by including a second mesh that defines a sort of "ceiling" via a different texture.

The other LoD schemes I've seen aren't particularly difficult to implement and, in some cases, are a lot more flexible, but this seemed like a decent quick-and-dirty way to handle height map-based terrain without getting into geometry manipulation.

Has anyone tried this? Opinions?


texts: Mesa library vs Hardware accelerated OpenGL for my executable - it's just a linking problem?

texts:
Supposing that i have my program that is targeting a specific OpenGL version, let's say the 3.0, now i want to produce an executable that will support the software rendering with Mesa and another executable that will support the Hardware accelerated context, i can use the same source code for both without expecting any issues ?

In another words, the instrunctions in this libraries are the same for my linking purpose ?


texts: Timing - use individual timer for every task or global timer?

texts:
I'm writing a game, where a player controls a spaceship.
It regenerates energy over time. So I need to make a little timer that adds certain amount of energy to the pool per second.
My enemies also shoot at me, activate different abilities. I figured I can use separate timers for these too.
But I see how this can quickly go out of hand, since I have different engines with different energy regeneration rates - will I need to replace the timer every time?
Or if I have different energy - I have to manually track all the timers and set them anew.

I thought, maybe I can use some global singleton method that can handle all the timing in my game? It can update everything in the game, and when something new happens (like new enemy spawning) I can just send my singleton information about that object and it will handle all the timing for it?

Is this a good approach? Can I read up something about this somewhere?
Maybe you have some experience with this?


texts: How can I procedurally render irregularly shaped health bars?

texts:
The issue of the traditional rectangular or heart-based health bar is something well-understood and easily solved. But what is the accepted solution for more "creatively-shaped" health bars, like the mockup I've made below?

The obvious way to do this would be to have "in-between" sprites, so the third image would be its own sprite, along with many other transitions for different levels of health. But that seems really inelegant and the number of in-betweens needed to create a smooth transition between health states would be large.

The only other idea I can come up with is to overlay the "full health" sprite on top of the "empty health" sprite and pre-bake sets of pixel coordinates to represent each tick of health and then make them opaque or transparent as health goes up or down.

I intend this question to be language and platform agnostic but feel free to provide a concrete sample in any language/library/framework if it helps the answer.


texts:
I'm thinking of writing a game in the vein of BeatHazard (where the music you're listening to affects the game), and after researching the subject of music analysis in programming, I know enough to know that it's a very complex subject.  So here are some questions:

What concepts do I as an engineer need to know about to do this?  What concepts do I probably not need to know about?
What kinds of analysis are simple, robust, and efficient enough to be used in a game (and preferably in that order - I would greatly prefer simplicity over efficiency and can trade some correctness if it keeps things simple)?
What cross-platform open source libraries exist that are easy to build and include?  I'm using MonoGame, but I'm willing to use p/invoke for a good library.  I've read about aubio, clam, and marsyas, and I'm not quite sure which I'm looking for.


texts:
I am attempting to make a global MaterialAssign script that I can assign to anything and have an enum selector in the inspector to assign a material type.  This would then drive hitFX and soundFX variation in other scripts.
My selector script MaterialAssign.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MaterialAssign : MonoBehaviour
{
    public enum MatSelection
    {
        defaultMat,
        metalEnemy,
        metalWall,
        dirtWall
    }
    public static MatSelection currentMat;
}

Attempt at usage in another script:
if (MaterialAssign.currentMat == MaterialAssign.MatSelection.metalEnemy)
{
    selectedHitFX = bulletMetalEnemyFX;
}
else if (MaterialAssign.currentMat == MaterialAssign.MatSelection.metalWall)
{
    selectedHitFX = bulletMetalWallFX;
}

I have no errors in the console BUT the enum selector doesn't show up in the inspector, so I'm assuming no value is ever passed. I read that enums can't have a static value, but not sure how to handle that.
Any assistance would be most appreciated or alternate approaches welcome! I'm purposely trying to stay away from tags, but can go down that path if needed.


texts:
I'm trying to increase the frame rate of my game from 60FPS to 100 FPS because of reasons. But i can't seem to get it higher than 60 frames. This is the count I'm using. I can slow down the frame rate by setting TargetElapsedTime = new TimeSpan(0, 0, 0, 0, 16);

to a higher value, but settings it lower won't increase the frame rate, according to the counter. Anyone have any idea what's going on?


texts: Interactively edit UV mapped, textured mesh in Cinema 4D without distorting texture?

texts:
I'm fairly new to Cinema and I'm building a rigged flat (2d) character out of illustrated pieces. I want the meshes to have an efficient number of polys but sufficient resolution where they'll bend most, so I'm starting with planes and mostly knifing away. Part of this process is roughly following the contour of the piece (say, an arm) with the edge of the mesh. I'm fine with the modeling, but I think I may be doing the texturing in a somewhat roundabout way, and I'm wondering if you can suggest a better technique.

My pipeline requires that all the textures be UVW mapped with no offset or scale. (I'm exporting to Unity through FBX)

Basically it's like this:

Set the texture tag to Flat projection
Modify the mesh (moving vertices, adding and removing vertices, etc)
Go back to UVW projection
In BodyPaint's UV Manager, in UV Poly Edit Mode, choose Flat projection fitted to object system.

The only problem with this is that if I have to tweak the mesh later, I'll have to go back into Flat projection so that moving the mesh vertices doesn't stretch the texture... and for some reason, after I've made a bunch of edits, the frontal mapping ends up requiring scale and offset to align again. Of course, I have to zero these out again when I'm satisfied and go back to UVW mapping. It really seems like an awful workaround to what should be a simple task.

Is there a better way to do this? Can I interactively move the vertices around while keeping a flat UV mapping, without switching back and forth in the Texture tag?


texts: How to avoid 2d enemy to see through walls

texts:
I am using RayCastCallback to detect the line of sight. So I the enemy avoid seeing the player through walls, problem is there's a limited field of view. So I added another two rays to the left and right side, with a total of 3 rays. Another problem is when the distance is longer the rays can't handle to see the player, so I added another more rays to fill the field of view. I don't know if this kind of idea is good or there is a better way without using rays?

Look in the below image, it seems the there is a circular sensor or like a radar. I am trying to achieve this kind of enemy sight (enemy sight demo ).


texts: How do I apply 2 rotations about different points to a single primitive using OpenGL

texts:
I'm working on a 2D top-down shooter game that has a rotation feature like Realm Of The Mad God such that if you press e the camera rotates around the character in a clockwise direction and q rotates the camera around the character in a counterclockwise direction.  I have this working with my floors and walls by translating to the character, doing the screen rotation, and drawing everything with the character as the origin.  The problem arises when I shoot projectiles which need to both rotate around the character and rotate around themselves (shooting uses the mouse cursor so I can shoot at any angle).  For example, if the screen is not rotated and I'm shooting rectangular projectiles, I want them to face in the direction I'm shooting (rotation around themselves).  However if I only do this rotation, when I then rotate the screen the projectiles will always shoot at the same position because my cursor position does not change.  Therefore I need to also either rotate the projectiles around the character or rotate the mouse cursor position to get the correct position (which would then totally screw up all of the collision detection).  Likewise if I only do the screen rotation on projectiles, the rectangles will always be facing the same way and they would only look correct if I were shooting straight up or straight down.

So my question is, how can I perform 2 rotations on a primitive around 2 different points?  The only way I can think of is to translate to the character and do the screen rotation, then somehow calculate the translation required to move back to the middle of the projectile (seeing as how my axes are now rotated) and do its rotation.  Or am I thinking about this in the wrong way and there is a different solution to accomplishing this effect?


texts: Type of 3D Rotation Animation used in this video

texts:
http://youtu.be/IUZqinlhono

I have referred to an application for interactive rotation in 3D space. The same is uploaded on youtube for your reference.
I am having difficulty in understanding the rotation of the axis. In the reference app, axis of model moves in bernoulli's lemniscate path. When we swipe horizontal or vertical, it rotates complete 360 degrees
however when the angle of swipe is changed (not exactly parallel to X-axis or Y-axis) model's axis moves in lemniscate path and comes back to starting position.

I am not abel to understand the concept and functioning behind this action. I am really stuck and have tried really hard to understand but failed. I will be obliged if anyone helps me understand this.

http://youtu.be/IUZqinlhono


texts:
I'm looking to achieve a two finger smooth pan system in my project.
However, the code below does not work, any interaction with the screen doesn't change to position of the camera.

I am unsure where did I go wrong as I'm quite new to Unity.

Any help will be greatly appreciated.

void Update () {

    //Detect If there are a) two fingers, b) touching the screen.

    if (Input.touchCount == 2 && Input.GetTouch(0).phase == TouchPhase.Began)
    {
        if (Input.GetTouch(0).phase == TouchPhase.Began && Input.GetTouch(1).phase == TouchPhase.Began)
        {
            if (Input.GetTouch(0).phase == TouchPhase.Stationary && Input.GetTouch(1).phase == TouchPhase.Began)
            {
                if (Input.GetTouch(0).phase == TouchPhase.Moved && Input.GetTouch(1).phase == TouchPhase.Began)
                {

                    Vector2 defaultCamera = transform.position;

                    Touch touchZero = Input.GetTouch(0); //Get locality of first touch.
                    Touch touchOne = Input.GetTouch(1); // Get locality of second touch.

                    Vector2 originalMid = Vector2.Lerp(touchZero.position, touchOne.position, 0.5f);

                    // Find the position in the previous frame of each touch.
                    Vector2 touchZeroPrevPos = touchZero.position - touchZero.deltaPosition;
                    Vector2 touchOnePrevPos = touchOne.position - touchOne.deltaPosition;

                    Vector2 touchMid = Vector2.Lerp(touchZeroPrevPos, touchOnePrevPos, 0.5f); //Get locality of midpoint between touches.

                    // Find the magnitude of the vector (the distance) between the touches in each frame.
                    Vector2 finalTouch = touchMid - originalMid;

                    transform.position = defaultCamera + finalTouch * Time.deltaTime; //transform camera using the new vector.

                }
            }
        }
    }


texts: Animation works, but Unity doesn't realize it

texts:
I have an animation which plays once, and it played once just fine.  I want to Invoke a method as soon as the animation finishes.  I have been researching and experimenting for over an hour now, but without the result I want.  I try to get the animation from the Animator, but Unity says my animation is not attached.  The thing is, I don't care if it's attached...I just want to know how long it is, not actually do anything with it.  How can I achieve this?  Here is the code which results in the error:

CODE:

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(PolygonCollider2D))]
[RequireComponent(typeof(Animator))]
public class Construction : MonoBehaviour
{
    // Use this for initialization
    void Start()
    {
        Invoke("EnableObstacleState", GetComponent<Animator>().animation.clip.length);
    }

    private void EnableObstacleState()
    {
        GetComponent<PolygonCollider2D>().enabled = true;
    }
}

ERROR:

MissingComponentException: There is no 'Animation' attached to the "Barricade(Clone)" game object, but a script is trying to access it.
You probably need to add a Animation to the game object "Barricade(Clone)". Or your script needs to check if the component is attached before using it.
Construction.Start () (at Assets/Scripts/Construction.cs:11)


texts: Mob generation design - is creating a class for each mob efficient?

texts:
I'm working on an RPG game for my coursework project. Everything is going fine but I've reached a stage where I do think that my project's code is not the most efficient.

Here I have a constructor of my class AbstractMob

public AbstractMob (String name, int hp, int attack, int defense, int magicAttack,
                        int magicDefense, int expBound, int goldBound, String folder, String idleAtlas, String attackAtlas) {

        abilities = new ArrayList<>();
        //setting variables
        this.attack = attack; //and so on

        idleAnimation = new Animation<>(
                0.070f, new TextureAtlas(Gdx.files.internal(
                        "sprites\\mobs\\" + folder)).findRegions(idleAtlas),
                Animation.PlayMode.LOOP);

        attackAnimation = new Animation<>(
                0.070f, new TextureAtlas(Gdx.files.internal(
                        "sprites\\mobs\\"+ folder)).findRegions(attackAtlas),
                Animation.PlayMode.LOOP);
    }

And here is an example of a class that inherits AbstractMob

public class FireElemental extends AbstractMob {
    public FireElemental() {
        super("Fire Elemental",
                400,
                12,
                10,
                18,
                15,
                50,
                20,
                "fireElemental\\fire.atlas",
                "firesprite",
                "firesprite"
        );
        //from AbstrctMob, declares any abilities the mob has
        abilities.add(new Fire()); //same design pattern as these mob creations,
        //I have a separate class for Abilities, and subclasses such as Fire
        //that inherit from Abilities

        setAbilities(abilities);
    }
}

Now, my question is - does it make sense to create a multitude of separate classes (i.e make more classes like FireElemental for different mobs) for each entity (whether that be abilities or mobs) for this game? How about utilising files/scripts to load them?

Thank you so much!


texts: What is the edge glow shading technique used in Super Mario called?

texts: What is this Super Mario shading technique (the edge glow) called? It can best be seen on the legs.


texts:
Hope you bear with me, I'm a beginner! Maybe I should've paid better attention to the tutorials but they all seem to use public variables/game objects that we can then drag into using the Unity Editor. However, if I have a private Game Object, how can I reference that programatically? I have the following:

private GameObject menuCanvas;

void Start()
{
menuCanvas = GameObject.Find("menuCanvas");
menuCanvas.SetActive(false);
}

Where the menuCanvas is named such in the Unity editor. However, I usually get the following error:

"The variable menuCanvas of myScript has not been assigned."

myScript is attached to a different GameObject in the scene, but not attached to menuCanvas. What am I doing wrong? Thanks for the help!

Edit: another question - which is generally better to use?

Edit 2: Hi guys, I figured it out. I had to move some code around to the Awake() function, so it looked like this:

private GameObject menuCanvas;

void Awake()
{
menuCanvas = GameObject.Find("menuCanvas");
}

void Start()
{
menuCanvas.SetActive(false);
}

And that worked. I realized that myScript was attached to multiple objects, which would cause the menuCanvas to be set inactive more than once (but it could not be referenced inactive).

S. Tarık Çetin's answer worked just as well! Thanks for the help

Edit 3: As Jesse Williams answered, an internal definition keeps the variable hidden from the editor, but it can still be assigned via code.


texts: Update android game with new levels without replacing database

texts:
So I've published a game for android users containing 400 levels and 2k users have completed or are playing it since. Now I'm going to update the game with 600 levels, but I don't want current users to lose their info in database. I just want to add more levels to the database if it exists in their phone.

I'm using this code not to let database get replaced if it exists.

public DataService()
{

        const string databaseName = Constants.DbName;

#if UNITY_EDITOR
        var dbPath = string.Format(@"Assets/StreamingAssets/{0}", databaseName);
#else
        // check if file exists in Application.persistentDataPath
        var filepath = string.Format("{0}/{1}", Application.persistentDataPath, databaseName);

        if (!File.Exists(filepath))
        {
            Debug.Log("Database not in Persistent path");
            // if it doesn't ->
            // open StreamingAssets directory and load the db ->

#if UNITY_ANDROID
            var loadDb = new WWW("jar:file://" + Application.dataPath + "!/assets/" + databaseName);  // this is the path to your StreamingAssets in android
            while (!loadDb.isDone) { }  // CAREFUL here, for safety reasons you shouldn't let this while loop unattended, place a timer and error check
            // then save to Application.persistentDataPath
            File.WriteAllBytes(filepath, loadDb.bytes);
#elif UNITY_IOS
                 var loadDb = Application.dataPath + "/Raw/" + databaseName;  // this is the path to your StreamingAssets in iOS
                // then save to Application.persistentDataPath
                File.Copy(loadDb, filepath);
#elif UNITY_WP8
                var loadDb = Application.dataPath + "/StreamingAssets/" + databaseName;  // this is the path to your StreamingAssets in iOS
                // then save to Application.persistentDataPath
                File.Copy(loadDb, filepath);

#elif UNITY_WINRT
        var loadDb = Application.dataPath + "/StreamingAssets/" + databaseName;  // this is the path to your StreamingAssets in iOS
        // then save to Application.persistentDataPath
        File.Copy(loadDb, filepath);
#else
    var loadDb = Application.dataPath + "/StreamingAssets/" + databaseName;  // this is the path to your StreamingAssets in iOS
    // then save to Application.persistentDataPath
    File.Copy(loadDb, filepath);

#endif

            Debug.Log("Database written");
        }

        var dbPath = filepath;
#endif
        _connection = new SQLiteConnection(dbPath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create);
       // Debug.Log("Final PATH: " + dbPath);

}

Also I've created a filed in database keeping database version to check what version the user has (like the version with 400 levels, the one with 600 levels or maybe more).

What I don't know is what is the best solution to add more records to an existing database.
Has anyone got a solution?


texts: is mvc design pattern good for developing video games?

texts:
how mvc design structure works in game development and specially in unity game development.

I know what mvc is and how it works but in coding structure for game development specially in unity I don't know how it really works.

as you may know is it a good structure for developing video games? if its a yes, why and how it should be used?

thank you for helping


texts:
I'm using TexturePacker in one of my games, though when packing a bunch of textures their extension is kept in the data file. So when I want to find a texture I need to search for "image.png" instead of just "image". Is there an option to let texture packer ignore the extensions of my source images in the data file?

Solved:

So if anyone else wants this, here's the exported I made: https://www.box.com/s/bf12q1i1yc9jr2c5yehd Just extract it into "C:\Program Files (x86)\CodeAndWeb\TexturePacker\bin\exporters\UIToolkit No Extensions" (or something similar) and it should show op as an exporter.


texts: What's the difference between variables defined with and without the 'var' keyword?

texts:
I've been making my way through several tutorials on GameMaker: Studio at this point, and I've been trying to keep track of various aspects of the code used in them. One thing, however, confused me.

I have noticed that it's possible to define new variables in GM:S either with or without using the var keyword. I'm aware that you can use the var keyword to define multiple variables in one line, for example var xx, yy; (and, of course, defining null variables), but other than that, is there a particular reason why some variables don't need to use var? Is it all to do with functionality, or what? When, in that case, should I use var other than the example provided?


texts: Unity - How do I make non-convex Meshes collide with physics?

texts:
Whenever I add a Rigidbody component to an object with a non-Convex Mesh, Unity throws this error:

  Non-convex MeshCollider with non-kinematic Rigidbody is no longer supported in Unity 5.
  If you want to use a non-convex mesh either make the Rigidbody kinematic or remove the Rigidbody component. Scene hierarchy path "Ship/BlockHolder/MeshHolder [0]", Mesh asset path "" Mesh name "MeshHolderTemplate(Clone)"

https://docs.unity3d.com/Manual/class-MeshCollider.html

After doing some research, it appears that I need to either enable the "Convex" setting for the Mesh Collider (which is NOT what I want - my objects require concavity)

or enable the "Is Kinematic" option for the Rigidbody component (which is NOT what I want either - from what I can see, Kinematic objects cannot be pushed by other objects)

The end goal is this: https://www.youtube.com/watch?v=O_UXKce9-OY&t=41s

(I can add the destruction later, for now, I just want the objects to be able to move and not intersect with each other)

How do I do this? I am completely lost here. Is this impossible in Unity?


texts: How can I append geometrical objects over a circle LibGDX

texts:
I want to draw geometric shapes over circle with using the graphics library in LibGDX like that;

As you see from image, I want to append blue shapes to black circle. Any advice ?


texts: Who should respond to collision: Unit or projectile?

texts:
In an RTS if a projectile hits a unit. Who should handle the collision?

If projectile handles the collision, it must be aware of all possible types of units, to know what damage to inflict. For example a bullet will likely kill a human, but it will do nothing to a tank.

The same goes if unit handles a collision. So either way one of them should be aware of all possible types of the other.

Of course the 'true' way would be to do full physics simulation, but that's not an option for an RTS with 1000s of units and projectiles...

So what are the common practicies in this regards?


texts: Why use this equation to get a percentage?

texts:
In an XNA book I read that this code does an action with a 0.2% of probability
but I don't' understand why:

float chance = 0.2f;

if((float)rand.Next(0,1000) / 10 <= chance)
{
...
}

I understand the statement, but not the reasoning for that equation. Can anyone explain me, please?


texts: Assigning function to button in foreach loop causes all buttons to have the same argument value

texts:
I have a script that generates buttons based on a list of assets. Each button is intended to to add the asset's resource path to a variable called SpawnGlobals.CurrentSelection. When printing the asset resource name of all button within the loop, the different resoruce paths are shown. When printing the value in the select function, the value is always the last item in the asset_register list.

I do not understand why this is happening. Am I using the foreach loop or lambda incorrectly?

void Start () {

    //Add Foundry Assets Here:
    SpawnGlobals.asset_register.Add (new FoundryAsset ("Test Sphere", "sphere_obj"));
    SpawnGlobals.asset_register.Add (new FoundryAsset ("Building Block 10x10x10 01", "BuildingBlock10x10x10_01"));
    SpawnGlobals.asset_register.Add (new FoundryAsset ("Building Block 10x10x10 02", "BuildingBlock10x10x10_02"));
    SpawnGlobals.asset_register.Add (new FoundryAsset ("Building Block 10x10x10 03", "BuildingBlock10x10x10_03"));
    foreach (FoundryAsset asset in SpawnGlobals.asset_register) {
        SpawnGlobals.buttons.Add(Instantiate(button_prefab));
        GameObject current_button = SpawnGlobals.buttons.Last ();
        current_button.transform.SetParent(master.transform, false);

        current_button.GetComponentInChildren<Text>().text = asset.AssetName;

        print (asset.AssetName);
        current_button.GetComponentInChildren<Button>().onClick.AddListener (delegate {
            select(asset.ResourcePath);
        });

    }

}
public void select(string selected)
{
    print (selected);
    SpawnGlobals.CurrentSelection = selected;
}


texts:
i tried to make thing to show menu up by doing VK_MULTIPLY and close it by doing VK_MULTIPLY, but this does not work..
Anyone can help :) ?

        if (IsKeyPressed(VK_MULTIPLY))
        {
            Menu::MenuLevelHandler::MoveMenu(SubMenus::NOMENU);
        }
        else if (IsKeyPressed(VK_MULTIPLY)) //????
        {
            Menu::MenuLevelHandler::BackMenu();
        }


texts:
I have been reading many different posts and articles about timesteps and while I now understand that fixed timesteps are generally considered superior, I'm having a bit of difficulty implementing one in XNA.

Apparently XNA uses a fixed timestep where the update method is called 60 times per second by default. However, I'm not really sure how to reconcile this fact with what I have been reading here, here, and here.

Do I need to supply my physics stepping with some sort of delta variable? Should I even be using GameTime.ElapsedGameTime anywhere in my code?

I guess I'm just a bit confused in regard to how much XNA is actually doing for me. Is it advisable to turn off the fixed timestep in XNA and instead make my own loop like the one from this post?


texts: How to get and change a mesh-renderer component in unity?

texts:
I've been making a simple brick-breaker game using unity 4.3 (In C#). I'm currently trying to make the blocks, which are stored in an array, all start with random colour properties. The colours are working correctly, but I want the blocks to start invisible, and then be assigned the various colours. I have researched, and found similar questions on changing the mesh-renderer component, but, as yet, they haven't worked. Here is my code:

EDIT: To put it simply: how do you make objects invisible, test if they are invisble or not and make them visble again.

using UnityEngine;
using System.Collections;

public class BlockInitialiser : MonoBehaviour {
    GameObject[] blocks;
    // Use this for initialization
    void Start ()
    {
        blocks = GameObject.FindGameObjectsWithTag ("Brick");
        StartCoroutine (blockColour ());
    }

    IEnumerator blockColour()
    {
        foreach (GameObject block in blocks)
                {
                        block.renderer.material.color = new Color (Random.value, Random.value, Random.value);
                        yield return new WaitForSeconds (0.1F);
                }
    }

Thanks in advance, guys.


texts: Increase speed with each enemy destroyed?

texts:
I need some help with coding this idea: "For each Target destroyed, increase the Gunner's speed by (speed variable)". The idea is that the Gunner is automatically moving, and I want it to become more frantic with each target hit.

Here's the relevant code I have so far:

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

    void Update () {
            Gunner_Move ();
    }

    //gives me the error "Assets/_Scripts/MovementPathScript.cs(60,83): error CS0200: Property or indexer `System.Array.Length' cannot be assigned to (it is read only)"
    void Gunner_Move(){
            if (GameObject.FindGameObjectsWithTag ("BulletProgressionObject").Length -= 1)
                Gunner_SpeedIncrease ();
    }

void Gunner_SpeedIncrease(){
         //behavior that I'm not sure how to make
   }

    //for the bullets colliding with target's parent object
        void OnTriggerEnter(Collider other){
            if (other.gameObject.CompareTag ("BulletProgressionObject"))
                Destroy (other.gameObject);

I think it's a foreach loop, but the issue I'm having is properly implementing it. Any suggestions or referrals would be greatly appreciated.


texts:
Hi, This is what I am trying to achieve: TextMeshPro with double outline.
So far I have tried these combinations:

TextMeshPro + Outline[int the mid] + Underlay [external]. It is close, but not the one I am trying to make. The problem in here: The outer shadow Underlay's Y offset is limited and can't go down below -1.

Then I tried to add built-in Shadow component but it did nothing.

Is there any way I can achieve this? I don't want to use 2 TextMeshPros. I haven't tried to achieve this in code because I am a super beginner in unity and open to any guidance on that.
Thanks


texts: Why use convex polygons and not concave ones in path-finding?

texts:
I read in Unity's path-finding documentation that they use convex polygons because there won't be any 'obstruction' between 2 points. Then they add their vertices as nodes along with starting and ending points and traverse them using A* algorithm to reach the required destination.
However, I do not understand what they mean by "no obstruction between 2 points". I tried to check the differences between concave and convex polygons but only the angle differences come up (in convex the interior angles must be less than 180 degrees)


texts: Why do I get this error with FB.LogInWithPublishPermissions?

texts:
I don't know what's wrong. I know that FB.Login is already deprecated. I don't know what syntax to use.

public class FBholder : MonoBehaviour {
    void Awake(){
        FB.Init (SetInit, OnHideUnity);
    }

    private void SetInit()
    {
        Debug.Log ("FB Init Done");

        if (FB.IsLoggedIn) {
            Debug.Log ("FB Logged in");
        } else {
            FBlogin ();
        }
    }

    private void OnHideUnity(bool isGameShown)
    {
        if (!isGameShown) {
            Time.timeScale = 0;
        } else {
            Time.timeScale = 1;
        }
    }

    void FBlogin()
    {
        FB.LogInWithPublishPermissions ("user_about_me, user_birthday", AuthCallback);
    }

    void AuthCallback(ILoginResult result)
    {
        if (FB.IsLoggedIn) {
            Debug.Log ("FB Logged in worked");
        } else {
            Debug.Log ("FB Logged in failed");
        }
    }
}

and I'm getting this error

  Assets/FBholder.cs(40,6): error CS1502: The best overloaded method match for `Facebook.Unity.FB.LogInWithPublishPermissions(System.Collections.Generic.IEnumerable, Facebook.Unity.FacebookDelegate)' has some invalid arguments

and this

  Assets/FBholder.cs(40,35): error CS1503: Argument #1' cannot convertstring' expression to type `System.Collections.Generic.IEnumerable'


texts:
Okay, someone tasked me to make a leaderboard for their game. However, the one I have right now is really insecure. All it does is check if someone is in the top 100, and if they are, post the score to the server, where the server will completely trust the client to give a real score.

My question is: How would I make it harder, or better, impossible, to send a fake high score, because right now they can just post a value to an easy-to-find endpoint.

Clarifications: The game is running in an interpreted environment, therefore obfuscation is not practical, and the game has a lot of input (an hour's worth at least), so sending that to the server is also impractical.


texts: Unity - protect MonoBehaviour-derived classes from instantiating via new in C#

texts:
When the class hierarchy grows and you deal with a lot of custom types in your project, it sometimes becomes hard to remember which types are allowed to be created via new and which types are derived from MonoBehaviour and therefore can't be created via new but must instead be attached to the GameObject as a Component.

Is it possible to have some safety-mechanism for this? The goal would be to have two base classes to control the ability to use new on a certain type. Ideally resulting in a compile-time error instead of an easy to miss warning in the console ("You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. Blah blah.").

My attempt to make the constructor protected, like this

public class UnCreatableBase : MonoBehaviour {
    protected UnCreatableBase() {
        // using new should be not allowed
    }

    public static T Create<T>() {
        // instead this method allows object creation
        return GameObject.Instantiate (Resources.Load ("Prefabs/" + typeof(T).Name) as GameObject).GetComponent<T>();
    }
}

public class CreatableBase {
    public CreatableBase() {
        // new is ok here
    }
}

still allows me to write:

var whyDoesThisWork = new UnCreatableBase();

I can access the protected constructor even from an outside scope.

Now, the obvious solution would be to make constructors of MonoBehaviour-derived classes private. Manually. All of them. Manually. I was wondering if there's a way of achieving the same in a more generic way.


texts:
I want to write a Unity app that doesn't use the Editor. That's the goal. Please don't ask why or tell me the Editor "is really great, you should try it", I know all that, I love the Editor, I'd personally love to WORK on the Editor (at Unity). That's not how this particular project goes, however.

The goal is a 3D prototyping app. In the app, you make design changes to a set of 3D models, and the changes you make show up "live" in a Unity app. When you're done, you "bake" the changes into an actual Unity app, complete w/ the Unity project source code, so you can open it and further refine it. Sounds goofy, I know, I was assigned this project from somebody else.

I know that for the live changes shown in Unity, I could of course make a nearly blank Unity project, and add GameObjects at runtime, and set their attributes. That much is obvious.

What's not obvious is how to add C# script behaviors at runtime. If the Unity "live" app is running all the time, and I'm adding GameObjects at runtime, how then do I add compiled C# dlls at runtime, so the dynamically created GameObjects use the newly compiled C# code?

I'm thinking the GameObjects would call out to a C# dll by some kind of name-binding, each time the C# code is updated, the dll is written out with a GUID/hash, and in the GameObject code, it dynamically looks for that Dll and loads it, then steps into it. seems tricky and complicated, right?

Has anybody done this and had some insight into it?
Before anybody references "Futile", keep in mind I don't care much about looking into a 2D only answer for this, and don't want to dig though that 2D code even if it has the answer in it. I'd like to discuss the answer here, on this forum, about thoughts about how to approach this, in the hopes it may help other people too.

Goals:
1. I provide 3rd party users a prototyping app that throws together an "editor" or a "prototyper" which shows on one winodw, with live in-Unity results in another window. Let's say the "prototyper" object in question is a GIANT terrain, populated with houses, trees, humans, etc. You can move around, see what the generated stuff looks like. Then, when you're happy with the look, you press "bake" and out pops a Unity project that you can go edit and flesh out.
2. I need the live Unity view to accept c# code (over some kind of communication mechanism) that will get compiled and run by the live view. Examples for why might be trees in the scene waving in the wind, running waterfalls, etc.

Thoughts?


texts: How to do smooth sprite movement on WP7 XNA

texts:
What's the correct technique for getting smooth sprite translations with XNA?

I've been developing the WP7 version of an app for a startup, so when we heard Angry Birds got ported today we wanted to check it out and compare. Angry Birds on WP7 had the sub-pixel blur problem with the bird sprites, whereas iPhone, Android, and Chrome all had smooth movement.


texts: Why does Unity's MeshCollider only use SharedMesh?

texts:
For components like MeshRenderer, Unity uses two references to mesh through script--mesh, and sharedMesh. My understanding as of yet that setting a "sharedMesh" will affect every GameObject that uses that component, whereas "mesh" alone will only affect a particular instance of that component. Same goes for "material" and "sharedMaterial".

However, for MeshCollider, the only thing available is "sharedMesh". The field "mesh" does not exist. I can work with this, but from a policy standpoint it seems very strange to me. Is there a reason that MeshCollider is treated differently?

I may be overlooking something obvious, but a Google search didn't help me.


texts: How to make UI image bounce back and forth inside another UI image?

texts:
I've been trying to create a battle system for my game, and I've been trying to get a UI image to bounce back and forth inside another image, but for some reason, the UI image goes out of the other UI and bounces back, like so:

Here's the script I add to the moving arrow image, in order to make it bounce:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class JumpSystem : MonoBehaviour
{
    private Vector2 startPosition;
    public int speed;

    // Start is called before the first frame update
    void Start()
    {
        startPosition = transform.position;
    }

    // Update is called once per frame
    void Update()
    {
        transform.position = new Vector2(startPosition.x + Mathf.Sin(Time.time * speed), transform.position.y);
    }
}

Is there any way I can prevent this incident from occurring? Please help me understand this and thank you in advance.


texts: Global PostProcess in UnrealEngine 4.10.2

texts:
I am new to UnrealEngine and following few tutorials to get started with.

I am trying to find "Global PostProcess" (in World Outliner) in UnrealEngine 4.10, but I am not able to find it. Has it been changed compared to previous version of UnrealEngine? If so whats the alternative of it?

Thanks.

Update

This is what I have:

And it doesn't look anything like whats there in this link (see Assigning to a Post Process Volume)

https://docs.unrealengine.com/latest/INT/Engine/Rendering/PostProcessEffects/PostProcessMaterials/PostProcessDemoMaterialOverview/index.html


texts: I am trying to create an HDRI SkyBox out of 6 textures but after I create the cubemap with Assets → Legacy → Cubemap and drag it in the HDRI Sky I get an all white environment. Is this a problem with the textures or maybe I am missing some setting?


texts: Need Help in Restricting Player Movement to Only 2 Axis,

texts:
I am creating a 2.5D Side Scrolling type Game. For the most part I am using a 3rd Person Character controller. The Major Problem that I am facing is how I can limit the motion of my Player Character to Just 2 Axis. I want to make a Fully Fledged Game so Climbing Ropes and Jumping Rocks etc everything will be there. I am not quite experienced with Unity. Although I have created few 2D. For the 3D World it’s Just a different Universe.
There are Zillions of things out there on internet and I have researched allot and read, understood and done so many things to get my task done. But I am unable to achieve what I am looking for.
I want my character controller to Use Mechanim, It is creating issues for me because almost All of the tutorials that I am focusing are Legacy Animation Oriented.
Please Help me so I may proceed.
I am not asking for spoon feeding and Kindly excuse me if I am doing wrong by posting.


texts: drawing of heightmap gives weird single pixels

texts:
I'm working on a game where I want to generate a heightmap, however it draws a bunch of random white dots in a mostly black background, the function I have looks as following:

void heightmap::layer1(int viewx,float freq1){

    for(int depth=1;depth<80;depth=depth+5){

        for(int x=0;x<screenWidth-1;x=x+5){

            glBegin(GL_QUADS);
                glColor3f(0.4, 0.2, 0.1);

                float h2=getCoord(viewx+x-5,depth+5,freq1);
                glVertex3f(viewx+x-5,h2,depth+5);

                 h2=getCoord(viewx+x,depth+5,freq1);
                glVertex3f(viewx+x,h2,depth+5 );

                 h2=getCoord(viewx+x,depth,freq1);
                glVertex3f(viewx+x,h2,depth );

                 h2=getCoord(viewx+x-5,depth,freq1);
                glVertex3f(viewx+x-5,h2,depth);

            glEnd();
    }
}

where get getCoord returns the height which takes a value between 0 and 800. However when I run this I get only darkness, any idea what I'm doing wrong?

The problem also exists for the code

    for(int depth=1;depth<10;depth=depth+5){

            glBegin(GL_TRIANGLE_STRIP);
        for(int x=0;x<screenWidth-1;x=x+20){

                glColor3f(1, 1, 1);

                float h2=getCoord(viewx+x,depth,freq1);
                glVertex3f(viewx+x,depth,h2 );

                 h2=getCoord(viewx+x,depth+5,freq1);
                glVertex3f(viewx+x,depth+5 ,h2);

    }
            glEnd();
}

When I force the values to be between

However I fixed the getCoords function to now simply return depth/80.0f. Meaning that I would expect a square not this shape, how do I fix this so that it will actually generate a terrain with the heigh given by the getcoords function?


texts: Keep balls in the box and prevent intersection

texts:
I'm coding a one-dimentional elastic collision animation (demo) with balls. I've used fixed position values when testing and now I want to use random values.

The problem with random values is that at the beginning (no animation, initial setup), balls might intersect. If this happens between two balls and in the middle of the container, current collision detection handles this kind of intersection. But if the balls are at the ends of the box and one intersects with both the wall and the other, this causes a problem.

For example, examine the below image.

One ball is randomly assigned a position and is in the middle.
Again, one ball is randomly assigned a position and it overflows to the left. It is repositioned to stay in the container.
Two balls are randomly assigned a position (no intersection) and are in the middle.
Two balls are randomly assigned a position (they intersect) and are in the middle. They're repositioned to touch each other.
Two balls are randomly assigned a position (they intersect) and one of them overflows to the left. Both should be repositioned with respect to each other and to the left wall. (demo)

Currently, I don't know how to handle the fifth case. I'll also increase the number of the balls, so the solution should be appliable to multiple balls.

If I can't find an easy solution, I'm gonna try empty space detection and reposition the balls starting from the farthest to the wall.

Most relevant parts:

var balls = [
    new Ball(25, 25, 25, 0, 0),
    new Ball(25, 50, 25, 0, 0, "blue"),
    // new Ball(25, random(0, 400), 25, 0, 0, "purple"),
];

function draw() {
    context.clearRect(0, 0, canvas.width, canvas.height);
    trackCollisions();
    balls.forEach(function(ball) {
        ball.draw();
    });
}
draw();

function trackCollisions() {
    // wall collisions
    balls.forEach(function(ball) {
        if (ball.intersectingWithWall()) {
            ball.snap2wall();
            ball.wrframe();
        }
        else if (ball.collidingWithWall()) {
            ball.flash("red");
        }
    });
    // ball collisions
    for (var i = 0; i < balls.length; i++) {
        for (var j = i + 1; j < balls.length; j++) {
            if (balls[i].intersectingWith(balls[j])) {
                balls[i].snap2ball(balls[j]);
                balls[i].wrframe();
                balls[j].wrframe();
            }
            else if (balls[i].collidingWith(balls[j])) {
                balls[i].resolveCollision(balls[j]);
                balls[i].flash("lime");
                balls[j].flash("lime");
            }
        }
    }
};

I've decided to share this experiment I'm working on here in case people came across similar problems or just want to know more about collisions:  https://github.com/akinuri/bouncing-balls


texts: How do I alert enemies to my presence when I make a sound?

texts:
I am working on a raycast-based 3D game, using Lua with Löve2D, and I am now currently working on the AI for the enemy. I want to make it like how "DOOM" did it, but I don't know how to handle how and when an enemy can hear your gunshot so they can "wake up" and become alert.

The map format is a simple grid, where 1 represents solid, and 0 represents open area. How did "Wolfenstein" and "DOOM" do it?


texts:
I want to develop a procedural galaxy / starfield generator.

A rather simple approach would be to use some pseudo-random algorithm to repeatedly create a star and its properties (such as position, mass, luminosity, density, and so on...). But in doing that, I would be quite limited in terms of the total number of stars. They would all be created at startup, and kept in memory, even the ones which are totally out of the player's range.

I do not want to end up with millions of star instances.

What I need is some way to only generate the stars which are near to the player and, therefore, being rendered. On the other side, I want the player to be able to return to stars, once they disappear due to being too far away.
Take Space Engine for example, it also does not generate all its trillion stars at the start of the simulation.

What would be a suitable approach to this kind of problem?


texts:
I need to port my game project from Android (written in C, OpenGL ES 2.0, thanks to NDK) to Windows and Linux platforms. Of course I will need to rewrite some platform dependent code, but for now I'm stuck with the question of which library to use for creating OpenGL context and handling input.

Just a quick googling gives me 3 candidates:

FreeGLUT - rewritten and free good old GLUT.
SDL - most well know one lib, used in many games.
GLFW - some kind of newer library, but simple and functional.

I'm quite new to PC development and don't see any significant differences between them.
Can you help me with the choice? I need only core mouse/keyboard input and creation of OpenGL context. I'll be using GLEW to load OpenGL functions.


texts:
I understand SGV images are used in 2D games to store shape data for the physics engine of the game. I'm unsure though, should the raster sprite also be stored in the SVG or should it be separate?

Also, what about animated sprites? In a non-skeletal-based animation system, how should the shape of the character be handled? Is a simple rectangle enough?


texts: Duplicating and adding sprites at runtime in Unity

texts:
I am trying to create a 2D game in Unity in which objects keep falling from top and the player has to dodge them. Suppose I have created a sprite which serves as a single enemy that the player has to dodge.Now I have to create multiple such sprites at runtime so that they can keep on spawning from random positions.Despite searching on the net for quite some time i could not find a clear answer.

I am just a newbie and I am just starting to learn game development in Unity so answers in detail will be very helpful.

Thanks in Advance.


texts: How can I add acceleration to the movement of an object in a game

texts:
Below is the code that I'm using to move an object:

let XX = 0
let YY = 0
let maxSpeed = 100;

if(keyDown.w) {
    XX += Math.sin(angle*Math.PI/180)*moveSpeed;
    YY += -Math.cos(angle*Math.PI/180)*moveSpeed;
}

I'm trying to implement acceleration in moving.  How can I do that?


texts: Unity3D: Change Background Image on a GUI Skin

texts:
So I'm testing with GUI Skins and trying to make something cool, and I want to change the background image of the application background. This is what I mean

In the screenshot above, the background is just blue, i'd like to change that to an image so it looks a lot better. Anyone know how to do this?


texts: Typical Applications of Linear System Solver in Game Developemnt

texts:
I am going to write a custom solver for linear system.

I would like to survey the typical problems involved the linear system solving in games. So that I can custom optimization on these problems based on the shape of the matrix.

currently I am focus on these problems:

B-Spline editing (I use a linear solve to resolve the C0, C1, C2 continuity)
Constraint in Simulation (especially Position-Constraint, cloth)

Both of them are Banded Matrix.

I want to hear about some other applications of a linear system in games.

Thank you.


texts: How to sync a LineRenderer in a multiplayer game?

texts:
After a lot of searching online, I have come here as a last resort for my problem.

The question says it all. How to sync a LineRenderer?

One answer I found was to use a ClientRpc. I tried it with no effect.

Below is the snippet of my code,

    IEnumerator laserBeam()// This is called through another method on the click of a button
        {
            Beam = GetComponent<LineRenderer> ();
            Beam.SetVertexCount (2);
            Beam.material = BeamMaterial;
            Beam.SetWidth (0.07f, 0.07f);
            Beam.enabled = true;
            Beam.SetPosition (0, gameObject.transform.position);
            Beam.SetPosition (1, target.position);
            RpcDrawLines (gameObject, target.position, true);
            yield return new WaitForSeconds (1.0f);
            Beam.enabled = false;
            RpcDrawLines (gameObject, target.position, false);
        }

    [ClientRpc]
    public void RpcDrawLines(GameObject start, Vector3 end, bool isOn)
    {
        LineRenderer beam = start.GetComponent<LineRenderer> ();
        if (isOn) {
            beam.SetVertexCount (2);
            beam.material = BeamMaterial;
            beam.SetWidth (0.07f, 0.07f);
            beam.enabled = true;
            beam.SetPosition (0, start.transform.position);
            beam.SetPosition (1, end);
        }
        else
            {
                beam.enabled = false;
            }
        }

So, this is the code. Works fine on the Server but no effect in the client. I know I am doing something wrong in the client rpc. But I have no idea what it is. Any way of help would be appreciated. Thanks

Note: I am using UNET


texts: HLSL : Offset and length were out of bounds

texts:
//Vertex Shader Constants
float4x4 World; float4x4 View; float4x4 Projection; float4x4 WorldViewIT;

//Color Texture
texture Texture;

//Normal Texture
texture NormalMap;

//Specular Texture
texture SpecularMap;

//Albedo Sampler
sampler AlbedoSampler = sampler_state
{
    texture = <Texture>;
    MINFILTER = LINEAR;
    MAGFILTER = LINEAR;
    MIPFILTER = LINEAR;
    ADDRESSU = WRAP;
    ADDRESSV = WRAP;
};

//NormalMap Sampler
sampler NormalSampler = sampler_state
{
texture = <NormalMap>;
MINFILTER = LINEAR;
MAGFILTER = LINEAR;
MIPFILTER = LINEAR;
ADDRESSU = WRAP;
ADDRESSV = WRAP;
};

//SpecularMap Sampler
sampler SpecularSampler = sampler_state {
texture = <SpecularMap>;
MINFILTER = LINEAR;
MAGFILTER = LINEAR;
MIPFILTER = LINEAR;
ADDRESSU = WRAP;
ADDRESSV = WRAP;
};

//Vertex Input Structure
struct VSI {
float4 Position : POSITION0;
float3 Normal : NORMAL0;
float2 UV : TEXCOORD0;
float3 Tangent : TANGENT0;
float3 BiTangent : BINORMAL0;
};

//Vertex Output Structure
struct VSO {
float4 Position : POSITION0;
float2 UV : TEXCOORD0;
float3 Depth : TEXCOORD1;
float3x3 TBN : TEXCOORD2;
};

//Vertex Shader
VSO VS(VSI input) {
//Initialize Output
VSO output;

//Transform Position
float4 worldPosition = mul(input.Position, World);
float4 viewPosition = mul(worldPosition, View);
output.Position = mul(viewPosition, Projection);
//Pass Depth
output.Depth.x = output.Position.z;
output.Depth.y = output.Position.w;
output.Depth.z = viewPosition.z;

//Build TBN Matrix
output.TBN[0] = normalize(mul(input.Tangent, (float3x3)WorldViewIT));
output.TBN[1] = normalize(mul(input.BiTangent, (float3x3)WorldViewIT));
output.TBN[2] = normalize(mul(input.Normal, (float3x3)WorldViewIT));

//Pass UV
output.UV = input.UV;

//Return Output
return output;
}

//Pixel Output Structure
struct PSO {
float4 Albedo : COLOR0;
float4 Normals : COLOR1;
float4 Depth : COLOR2;
};

//Normal Encoding Function
half3 encode(half3 n) {
n = normalize(n);

n.xyz = 0.5f * (n.xyz + 1.0f);

return n;
}

//Normal Decoding Function
half3 decode(half4 enc) { return (2.0f * enc.xyz - 1.0f); }

 //Pixel Shader
PSO PS(VSO input) {  //Initialize Output
PSO output;

//Pass Albedo from Texture
output.Albedo = tex2D(AlbedoSampler, input.UV);
//Pass Extra - Can be whatever you want, in this case will be a Specular Value
output.Albedo.w = tex2D(SpecularSampler, input.UV).x;

//Read Normal From Texture
half3 normal = tex2D(NormalSampler, input.UV).xyz * 2.0f - 1.0f;

//Transform Normal to WorldViewSpace from TangentSpace
normal = normalize(mul(normal, input.TBN));

//Pass Encoded Normal
output.Normals.xyz = encode(normal);
//Pass this instead to disable normal mapping
//output.Normals.xyz = encode(normalize(input.TBN[2]));

 //Pass Extra - Can be whatever you want, in this case will be a Specular Value
output.Normals.w = tex2D(SpecularSampler, input.UV).y;

//Pass Depth(Screen Space, for lighting)
output.Depth = input.Depth.x / input.Depth.y;

//Pass Depth(View Space, for SSAO)
output.Depth.g = input.Depth.z;

//Return Output
return output;
}

//Technique
technique Default {
pass p0 {
    VertexShader = compile vs_3_0 VS();
    PixelShader = compile ps_3_0 PS();
}
}

This is my current shader… it is producing a "Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection" argumente axeception… I don't understand what's wrong with it….

Any help is appreciated.


texts:
I am creating a 2D farming game using XNA - just today I have tried applying full screen to it, and I realized I failed badly with something. It cuts off a bit of the lower part [item hotbar and a piece of character status area]

I have just started learning C# and XNA, I just totally rewrote the engine and changing everything with rendering all over again is not an option - honestly I have no idea myself how does it all work anymore [I'm using some crazy camera class thing with an array of rectangles for displaying tiles / moving them around when the player moves etc] :-P

In the previous version of the engine I used the default XNA window size and the full screen worked just fine, this time I changed it to something more ... comfortable, and it does not work anymore. Changing the preferred buffer width does nothing at all in full screen, it's still cut off, and still the same height. I have no idea what matrices or viewports are, and everything I seem to find on google refers to them and some crazy complicated stuff

The screen size I am using is 800 x 640

My screen is very long sideways [whatever the name for such screens was :|]

Is there a way to fix that without rewritting everything?


texts: How to make sound play when button is pressed

texts:
I'm using Game Maker Studio 2.

When I press the "Z" key I need audio to play, but I can't seem to get it to work.

I'm using the following code inside an object's Key Press event:

if keyboard_check_pressed("Z")
{
   audio_play_sound(snd_menu_selection,1,false);
}