texts: Handling various frame layouts in Android

texts:
I am trying create a Contra or the old TMNT game (but a simple one) like game for Android. For the game I decided to divide my main screen in three parts - upper for stats, mid for the game and lower for controls.

My main.xml is

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<FrameLayout
    android:id="@+id/upper_bar"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1" >
</FrameLayout>

<FrameLayout
    android:id="@+id/fl"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="0.5" >
</FrameLayout>

 <FrameLayout
    android:id="@+id/low_bar"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="0.85" >
</FrameLayout>

</LinearLayout>

So I have created the gameview and gameloopthread classes for the mid surface(which is pretty standard). My problem is I don't know how to draw in the upper and lower frame layouts. Should I make new classes for view and thread for each layout, should I do all this in the gameview class itself or is there any better way to implement this?


texts: Improve mouse movement in first person game

texts:
In my current FPS game, I have the mouse setup in a way, that it always forces the position of the mouse to be centered at the screen. This gets the job done, but also gets very annoying, since the mouse is "fixed" at the center of the screen.

Here is what I am doing:

get mouse current position
find offset from center of the screen
set mouse current position to center of the screen
apply difference to m_pTransformation (transformation matrix of the player)

Is there a better way to deal with this ?


texts: XNA Textures dissappear when game window is resized

texts:
[SOLVED] - See linked post in the P.S.

I have a set of Texture2Ds generated in the Load method with this function:

Texture Generation:

private Texture2D[,] createTextureSet(TileInfo[,] map)
    {
        Texture2D[,] texSet = new Texture2D[map.GetLength(0), map.GetLength(1)];

        using (SpriteBatch sprb = new SpriteBatch(GraphicsDevice))
        {
            for (int row = 0; row < map.GetLength(0); row++)
            {
                System.Threading.Thread.Sleep(10);
                for (int col = 0; col < map.GetLength(1); col++)
                {
                    RenderTarget2D renderer = new RenderTarget2D(this.GraphicsDevice, 300, 300);
                    System.Threading.Thread.Sleep(2);
                    GraphicsDevice.SetRenderTarget(renderer);
                    renderer.Name = map[row, col].buildings[0].buildingType;
                    GraphicsDevice.Clear(Color.Transparent);
                    sprb.Begin(SpriteSortMode.Immediate, BlendState.NonPremultiplied);
                    sprb.Draw(TextureFromFile(resourceDirectory + @"Images\Tile Backgrounds\" + map[row, col].tileType + @"\" + map[row, col].tileBackground + ".png"), renderer.Bounds, Color.White);
                    sprb.Draw(TextureFromFile(resourceDirectory + @"Images\Buildings\" + map[row, col].buildings[0].buildingType + ".png"), (Vector2)map[row, col].buildings[0].pointWithinTile, Color.White);
                    sprb.End();
                    texSet[row, col] = renderer;
                }
            }
        }

        GraphicsDevice.SetRenderTarget(null);
        return texSet;
    }

The tiles are drawn on the screen using the following code:

Texture Rendering

for (int tx = -1; tx < 2; tx++)
        {
            for (int ty = -1; ty < 2; ty++)
            {
                gameSpriteBatch.Draw(mapTextureSet[gameCharacter.characterTile.tileX + tx, gameCharacter.characterTile.tileY + ty], determinePositionToDrawTile(gameCharacter, map[gameCharacter.characterTile.tileX + tx, gameCharacter.characterTile.tileY + ty], tx, ty, resizeX, resizeY), null, Color.White, 0f, Vector2.Zero, new Vector2(resizeX, resizeY), SpriteEffects.None, 0f);
            }
         }

These textures are then drawn on the screen based on where on the map the player is. The game runs fine, until the game window is resized by the user. After that, only the character sprite remains on the screen during the redraws, and the screen remains the default Color.BlanchedAlmond background of my game. Any help is thanked in advance.

[ ! ] P.S. [ ! ]

Before marking this as a duplicate! I have looked at this and tried most of the applicable solutions from it, none of which have worked, so I assume that this error is deeper than that one.


texts:
I get the following error every time I run the code: error: error CS0119: Expression denotes a `type', where a `variable', `value' or `method group' was expected

void OnCollisionEnter()
{
  Stick ();
}

Can someone offer a solution?


texts: Should many constants utilize constant variables or a database?

texts:
If you decide to design some sort of in-depth customization system for the player that utilizes a ton of different options, would you be better off using SQLite or just a whole bunch of constant variables in the program?

For instance, let's say you want the player to be able to build their own weapons. For a sword, they can put together a hilt, a blade, and maybe a jewel and inscription. That's 4 parts, of which there can be many different options, and that's just for one weapon. For the sake of example, let's say there are hundreds of different parts alone, which makes for a great number of combinations. The parts themselves are of course just weapon components, and don't have any special properties that need to be programmed - just certain attributes that say how they interact with the weapons (like which ones they can be attached to) and how they interact with other parts (if there is a special effect when combined with other ones, for instance - though this is probably better off programmed).

Presumably, this would allow for a great deal of customization, so there would be an in-game system in place that would allow the player to easily search for parts of a certain type/with a certain effect/of a certain element/etc. by using search filters, which sounds perfect for a database and not-so-perfect for program variables.

As a general question, how do you know when it is time to manage all of your constants through a database as opposed to doing it through the program? Is it the number of your variables? How valuable search/sort is? Will using a database quicken or slow the performance of these customization options?


texts:
So I'm making a copy of noobtuts tutorial on Snake
I've done all their steps and am at the point of extending the game solo, however I have an issue with the basic set-up. My box colliders aren't working at all!
I have four borders each with a Box Collider 2D, nothing fancy about them, and a Snakehead with a Box Collider 2D, nothing fancy about that either. Only the food prefab I have uses the IsTrigger. The Snake head also has a Rigidbody 2D and I've experimented with putting a Rigidbody2D on the borders too but it's not solved my problem.
Basically when I have the Snakehead moves to the border, it just passes through the border! It doesn't stop, it doesn't do anything, just continues straight through the border.
I've a basic gif showing off what I mean:

The only different thing about the box colliders is that for the snake they're 0.7 in size, not 1. But even when put to 1, they don't work properly.
Why isn't it stopping the snake from moving? I've never had to tell an object that when it hits another object to not move through it from what I can remember.


texts:
I'm working with MonoGame in VB2015 - please don't give answers that involve using C#.

Anyway, I found a snippet which I converted to VB for pixel collision. The function below accepts two rectangles, then runs a pixel check on the intersection between the two.

What I can't work out is how to send my two sprites (textures) to the function as rectangles. Or if anyone has a alternative, please let me know.

  Private Shared Function IntersectPixels(rectangleA As Rectangle, dataA As Color(), rectangleB As Rectangle, dataB As Color()) As Boolean
    ' Find the bounds of the rectangle intersection
    Dim top As Integer = Math.Max(rectangleA.Top, rectangleB.Top)
    Dim bottom As Integer = Math.Min(rectangleA.Bottom, rectangleB.Bottom)
    Dim left As Integer = Math.Max(rectangleA.Left, rectangleB.Left)
    Dim right As Integer = Math.Min(rectangleA.Right, rectangleB.Right)

(No, this isn't the whole routine...)


texts: UV mapping in blender for use with Unreal Engine material

texts:
I have a room that I want to import in Unreal Engine 4.

When I do it, I apply a material to the walls (for example), and the walls look like this:

My question is, how can I map the object to the unreal engine material? I've seen some tutorials but I don't specifically know what I must do, since I only apply the material in Unreal.


texts: images loaded onto texture appear completely white

texts:
I am applying a texture to a primitive plane using ARKit and Unity like so,

IEnumerator loadSpriteImageFromUrl( string URL, ARPlaneAnchor anchor ){
    WWW www = new WWW(URL);
    while (!www.isDone)
    {
        Debug.Log("Download image on progress" + www.progress);
        yield return null;
    }

    if (!string.IsNullOrEmpty(www.error))
    {
        Debug.Log("Download failed");
    }
    else
    {
        GameObject clone = GameObject.CreatePrimitive(PrimitiveType.Plane);
        clone.transform.position = UnityARMatrixOps.GetPosition (anchor.transform);
        clone.transform.rotation = UnityARMatrixOps.GetRotation (anchor.transform);
        clone.transform.localScale = new Vector3(anchor.extent.x * 0.1f ,anchor.extent.y * 0.1f ,anchor.extent.z * 0.1f );
        clone.transform.localPosition = new Vector3(anchor.center.x,anchor.center.y,-anchor.center.z);
        Texture2D texture =new Texture2D(128,128,TextureFormat.RGBA32,false);
        www.LoadImageIntoTexture(texture);
        MeshRenderer m = clone.GetComponent<MeshRenderer>();
        m.material.mainTexture = texture;
    }

But the image applied as texture  is completely white with no colors. Can someone please point my mistake. I checked the lighting, there are no issues.


texts:
Bear with me this will take some explaining...

I'm trying to design my game as close to Model-View-Controller design principles as possible. At least in and so far as I understand those principles.

I have two relevant classes in my View and Model respectively (with an irrelevant-in-this-case playerInput class acting as the controller)

BattleSerializable (My model that handles battle logic)
BattleView (My view that handles battle display stuff)

BattleSerializable has a method called DoDamage that subtracts health from a player. BattleView has a method DoDamageView that calls the model's method (DoDamage) and then renders a number on the screen to indicate the amount of damage done.

So far so good.

But there's a friendly fire penalty! In the sense that if you do damage to an ally, you also take damage.

Ok, so now I can go one of three ways:

1) My BattleView can handle the friendly fire logic and call the DoDamage method twice in the case of a friendly fire occurrence, but this goes against what "View" is supposed to do. It doesn't make sense that BattleView should handle friendly fire logic. It should handle view logic only.

2) My BattleSerializable class can handle the friendly fire logic, but now I have to return a complex custom return object instead of a simple integer to handle all the state that changed. This seems needlessly complex or, at the very least, in-eloquent.

3) Instead of calling my model method from the view method, I could have the model run independently and, from the view, "poll" the Model every frame for changes and then render combat numbers if a change is detected. This seems inefficient and in-eloquent to me as well.

What is the preferred way to design this?


texts:
I am trying to write to a CSV file the values that I put in lists from a key press in the keyboard. It does work somehow but in my csv file I get the values 2 times. Also, when I put values to only one of the lists, I don't get any data to CSV file. How can I save the values from the lists to my csv file but to be independent from each other? This is my code:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System;

public class record : MonoBehaviour
{

public List<string> inventory = new List<string>();
public List<string> OnlyX = new List<string>();

void Update()
{
    if (Input.GetKeyDown(KeyCode.F))
    {
        inventory.Add("F");
    }
    if (Input.GetKeyDown(KeyCode.J))
    {
        inventory.Add("J");
    }
    if (Input.GetKeyDown(KeyCode.X))
    {
        OnlyX.Add("X");
    }
    string filePath = getPath();
    StreamWriter writer = new StreamWriter(filePath);
    writer.WriteLine("Inventory,OnlyX");

    for (int i = 0; i < inventory.Count; ++i)
    {
        for (int j = 0; j < OnlyX.Count; ++j) {

            writer.WriteLine(inventory[i] + "," + OnlyX[j]);
        }
    }
    writer.Flush();
    writer.Close();
}
private string getPath()
{
 #if UNITY_EDITOR
    return Application.dataPath + "/Data/"  + "Saved_Inventory.csv";
 #elif UNITY_ANDROID
    return Application.persistentDataPath+"Saved_Inventory.csv";
 #elif UNITY_IPHONE
    return Application.persistentDataPath+"/"+"Saved_Inventory.csv";
 #else
    return Application.dataPath +"/"+"Saved_Inventory.csv";
 #endif
}
}


texts: Handling User Input Based on the Current Game State

texts:
currently i'm developing a 2D game in my spare time and i'm confused on how to handle the input from the player.

Currently my game uses the state design pattern, each game state is a different object such as Inventory, Playing, Paused etc. All of these states implement an interface called State that have a Render and Input method that is called on whatever the "Current state" is in the game engine.

So my question is would you use multiple key listeners or key bindings, one for each state since the input the player will do differs dramatically between the different game states or would you use one key listener or keybinding somehow? Is there a best practice for this?

Thanks.


texts:
I'm working with Unity 5.3 with C# as code editor

These are what I have :

I have 2 scenes in my project : home and options. I have bg object on both scenes. Both bg objects have Audio Source component, which contains same background music that play on awake. I don't use any codes for these background musics, I only click the Add Component button from Unity and add Audio Source.

This is what I want :

Options scene can toggle the background music on/off for all scenes. Therefore, there are btnOn and btnOff in Options scene.

This is my code in Audio Manager.cs :

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

public class AudioManager : MonoBehaviour {
    public Button btnOn;
    public Button btnOff;

    // Use this for initialization
    void Start () {
        btnOn = GetComponent<Button>();
        btnOff = GetComponent<Button>();

        btnOn.onClick.AddListener(() => PlayAudio());
        btnOff.onClick.AddListener(() => StopAudio());
    }

    void PlayAudio()
    {
        AudioSource.volume = 0.5f;
    }

    void StopAudio()
    {
        AudioSource.volume = 0f;
    }
}

This is the problem :

I have this error : An object reference is required to access non-static member UnityEngine.AudioSource.volume. Maybe, this is because I don't write public AudioSource audioSource in my code. But, if I write this, I have to add another audio in Get Component box, and I will have double Audio Source in one scene. What should I do? Thanks


texts: How to update entity states and animations in a component-based game?

texts:
I'm trying to design a component-based entity system for learning purposes (and later use on some games) and I'm having some troubles when it comes to updating entity states.

I don't want to have an update() method inside the Component to prevent dependencies between Components.

What I currently have in mind is that components hold data and systems update components.

So, if I have a simple 2D game with some entities (e.g. player, enemy1, enemy2) that have Transform, Movement, State, Animation and Rendering components I think I should have:

A MovementSystem that moves all the Movement components and updates the State components
And a RenderSystem that updates the Animation components (the animation component should have one animation (i.e. a set of frames/textures) for each state and updating it means selecting the animation corresponding to the current state (e.g. jumping, moving_left, etc), and updating the frame index). Then, the RenderSystem updates the Render components with the texture corresponding to the current frame of each entity's Animation and renders everything on screen.

I've seen some implementations like Artemis framework, but I don't know how to solve this situation:

Let's say that my game has the following entities. Each entity have a set of states and one animation for each state:

player: "idle", "moving_right", "jumping"
enemy1: "moving_up", "moving_down"
enemy2: "moving_left", "moving_right"

What are the most accepted approaches in order to update the current state of each entity? The only thing that I can think of is having separate systems for each group of entities and separate State and Animation components so I would have PlayerState, PlayerAnimation, Enemy1State, Enemy1Animation... PlayerMovementSystem, PlayerRenderingSystem... but I think this is a bad solution and breaks the purpose of having a component-based system.

As you can see, I'm quite lost here, so I'd very much appreciate any help.

EDIT: I think the solution to make this work as I intend is this one:

  You make statecomponent and animationcomponent generic enough to be used for all entities. The data they contain will be the modifier for changing things like which animations are played or which states are available. – Byte56

Now, I'm trying to figure out how to design these 2 components generic enough so I can reuse them. Might having an UID for each state (e.g. walking, running...) and storing animations in a map into the AnimationComponent keyed by this identifier be a good solution?


texts: Does anyone have a sample for drawing a subdivided icosahedron in javascript, that they would be able to share?


texts: Simple javascript HTML5 canvas start menu

texts:
I'm currently looking for a simple and basic start screen for a game using javascript, so basically its the first function that is called and then press play which then goes into the game.

Looked online and they all seem to be advanced ones and can't seem to find any tutorials either.


texts:
I'm trying to implement a zone system into my game that randomly sets chunks (the cells) to a certain value from a list and that would effect nearby chunks. It's basically a cellular automaton in which instead of the cells being on/off, they would have multiple options, like red/green/blue/yellow/brown or such.

Do this kind of cellular automata exist?


texts: Controlling a balance wheel using a Unity script

texts:
I am working on a small demonstration project with Unity like this (screenshot from footage below).

I don't want to use Unity physics, which is too heavy. I plan to create a rotation function with ratio params for gears.  But I am not sure how to control the balance wheel rotation like that video, I tried animation tools which is hard to make the acceleration like real physics.


texts: Multiplayer client-server architecture sending input

texts:
I've got a 2D java game with an infinite generating world with a player and other entities. I wish to make this game multiplayer and have done my research. I read this article multiple times and is what I want to implement.

In short: Client acts as terminal sending input to server. Server is authoritative and controls the game, deciding the result of the input from the client and sending back the relative info. Maintaining performance the server each 100 milliseconds keeps a list of all received input from the client and only then processing it. Client predicts its own game state by its input and when it received the processed state from the server it validates if the state is correct, otherwise corrected by the server.

E.g. Player pressed D -> client sends 'move right" input to server -> client predicts its own location to avoid choppy movement -> server finishes 100ms wait and processes all received input -> server decides new location of player by received input -> server sends the decided location to client -> client validates its current predicted location by the server received one, corrects the client if neccessary.

My question: How do I properly send all the inputs to the server and in what format? And how to receive different kinds of output back?

I shouldn't just send the entire player object (which has all inputs such as if WASD keys are held down), should I? Seems way too bandwidth and CPU intensive. Also seems overkill since most properties at each update will be false. Server only needs to be aware of what happened, not what didn't happen. Can I somehow only send single commands to the server? No strings with switch statement please.

How to receive different kind of information from the server? Player needs new world chunks when it moved. Needs to validate its own world position against the server. Needs to check if client inventory is same as server.


texts: RenderPipleinManager.DORenderLoop_Internal() Taking Unusual Amount In profiler

texts: I am developing for WebGL and for optimization purposes I have converted to URP. After converting the tri count has dramatically improved but the problem is my FPS is not improving. I tried to profile and found that RenderPipleinManager.DORenderLoop_Internal() is taking 13%. Is this normal? An initial search brought that it was a bug and fixed in a later unity version. But even after converting to the latest lts 2019.4.20, i am getting the same issue.


texts: Failed to spawn server object, Unity UNET

texts:
I'm familiar with Unity and programming but I'm new to this site.

So I have an issue with clients on Unity. I start servers with no errors, flawless. But when I join a server as a client I get a bunch of the error mentioned in the title. What causes this issue? I am using the UNET networking components.

I think it's lines like these, when executed by a client:

    NetworkServer.Spawn (objectNameHere);

How can I fix it if that's the case?

Edit

After hours of having this issue I have become so frustrated that I think it's best I take a break. I'll check back on this site from time to time.


texts:
Allright so I've been doing some searches, here what I got:

SDL: It is a standard, very mature but very old. (I got posts of late 2009 where they were still waiting for the 1.3 to come up...we are still waiting 3 years later). Also it seems abandoned and old style (it's around from the '98). And also it's made in C (for this there's no downside nor upside. Someone prefers C over C++ nowadays for some reason and C can run on C++ but not viceversa).
SFML: It's a new born in the libraries. It's not very mature and lack of a lot of documentation. It was buggy till 1.6 but now the 2.0 is quitely good (it's the one I've tried). It has a lot of things built in (even the possibility to easily use OpenGL). It's in C++ and has the OOP paradigm.
Allegro: I haven't heard much about it. It gives me the idea of a toy, but it's not an opinion I count on. It is C based (like SFML) but doesn't have that large community (like SFML).

I'm considering only cross platform libraries. Now I'd like to make few questions about this situation:

Is SDL falling apart?
Why isn't SDL being update to the so awaited 1.3 (which will, they say, support iPhone and phones) in 3 years?
Is SFML gonna take SDL place?
Why people say that SFML is more abstract then SDL? It seems pretty much the same to me. You have likely all the configurations you want on both.
Allegro had a troubled story. It was only for DOS, then it was ported for other platforms etc... Is it really cross platform?
How stable is Allegro?

Thanks.


texts: Some practical issues with component-based game object systems

texts:
I am creating my own game engine just for fun and brain development. I have chosen various free and open-source libraries to integrate and now I have come to the engine architecture.

I intend to use server-client architecture and I prefer to be more "data-driven" so I can organize my game state in MySQL database. I recently read about a component based design which plays nicely with data-driven systems. The idea is that game object components are bare properties and the behavior is implemented in so-called subsystems. Each subsystem (like Physics, Render, Animation, Sound) "knows" only about related components and also is able to tie itself to other systems if needed. Those subsystems are singletons (single instances).

I can use the observer pattern so each subsystem can subscribe to property changes which are important for the particular subsystem. The subsystems subscribe to prop change events in some particular order thus creating subscription chains. But this can create one problem: SystemA detected change in propA and needed to change some propB, but SystemX is listening to propB changes and affects propA .. and we have an infinite loop. Is this a common weakness of such systems or I have wrong implementation ideas?

The last system in the subscription chain could be the NetworkSystem, which sends out a small package on every subscribed property change ... or it is a bad idea and I should pack more changes together?.

I guess, rendering and physics will be separate threads where RenderSystem (client-side only) is polling the entities for their properties which have changed since last frame and PhysicsSystem is modyfing properties on each iteration; InputSystem (client-side only) and NetworkSystem also are modifying properties and WorldClockSystem could modify some properties on timer events.

But the major problem is when I think how to implement custom scripting in such systems. Let's say, users are allowed to upload their custom logic and animation script called Respect which has one property called goodDeeds with a rule "if a person with goodDeeds>100 passes by, I run some RespectAnimation". So I would install a global RespectSystem which subscribes to position changes of every character and checks for the Respect component and goodDeeds property and then somehow tells to Animation system to run Respect animation on this object. Is this the way it is supposed to work, isn't it dangerous that the behavior now is a global object and not a property of the entity which uses it? If I think again about the problem of neverending loops of observed/modified properties, it means that one wrong xxxSystem script could stall the entire server (but from the other hand, the admin of the server should have enough sanity to see such problems before allowing the user to upload that script).

Anyway, it would be great to find some book or article which better describes how to use component-based systems where components are properties and behavior are singletons, but somehow all articles I have read, explain only the idea itself but not how to attach it to a real game engine with scripting and networking.


texts: How do I move many "static relative to each other" objects around?

texts:
I'm currently building an Elevator Bank simulator in Unity3d and I'm stuck on how to reduce the amount of objects it's going to generate when it's done. The simulator will consist of one player (for now) walking into a building, calling an elevator, picking a floor, going up/down and getting out of the elevator again.

To illustrate the problem, I'll sketch 2 scenario's. One where there's no problem whatsoever. One where I simply scale upwards and create a mess. But first, a list of what's inside the simulator (excluding the player).

One hull of elevator shafts (3D .obj model).
One elevator car per shaft (3D .obj model).
One group of hall buttons per shaft per floor (one button for the top & bottom floor, two for the rest).
One group of control buttons per elevator car (door open, door closed, etc.). At least 3 buttons.
One floor call button per elevator car per floor.
Two doors per elevator car.
Two doors per shaft per floor.

A simple set-up of 3 shafts and 4 floors will already create 75 objects of which 30 are moving. Take 20 floors, 2 rows of elevators, 3 cars per row and I'm over 600 objects already.

Now. The Empire State building has 102 floors and 73 elevators. Which means multiple banks, a whole lot of floors, a whole lot of buttons and a whole lot of cars. Scaling my current set-up to support that will create a mess at best and simply won't work at worst.

Since this is an elevator simulator, the whole point of it is to make sure every elevator is active from starting the scene to ending the scene. So no tricks like only spawning what's in range of a camera, hibernating objects, object pooling and what not are out.

Now, objects in the same elevator car are static relative to each other. If the car moves up, everything moves up the same amount. So I hope I can move them as a group. Except I have no clue how to do such a thing in Unity. Prefabs may be part of the solution, but that still won't link their movements together. I've considered linking them together like a Snake game, but the amount of objects involved is orders of magnitude more. Luckily, all moving objects (except for the player) will only move on one axis. Doors only slide open/closed, elevator cars and their buttons go up and down. All rotations are fixed.

How do I move so many objects around in a single scene without creating a mess of variables in a performance-wise good way?


texts:
I use PhysX vehicles for my vehicle simulation, however there is no idle regulator option available to use. I want to implement that to have correct overall engine behavior such as stalling and in the first place more plausible engine sound.

I have an idle RPM range I want to have as result of solution, let's say 900-1000.
By changing throttle value I get change in calculated RPM value.

How would I go about creating dynamic system that changes throttle accordingly to get stable RPM value?

The only option I saw was a PID controller, but as far as I know, it changes a variable to get desired result on that same variable, whereas I need to change one variable to get desired value on a different variable.


texts: Moving while doing loop animation in RPGMaker

texts:
I made a custom class to display character portrait in RPGMaker XP
Here is the class :

class Poser
  attr_accessor :images

  def initialize
    @images = Sprite.new
    @images.bitmap = RPG::Cache.picture('Character.png') #100x300
    @images.x = 540 #place it on the bottom right corner of the screen
    @images.y = 180
  end
end

Create an event on the map to create an instance as global variable, tada! image popped out. Ok nice. But Im not satisfied, Now I want it to have bobbing-head animation-like (just like when we breathe, sometimes bob our head up and down) so I added another method :

  def move(x,y)
    @images.x += x
    @images.y += y
  end

  def animate(x,y,step,delay)
    forward = true
    2.times {
      step.times {
        wait(delay)
        if forward
          move(x/step,y/step)
        else
          move(-x/step,-y/step)
        end
      }
      wait(delay*3)
      forward = false
    }
  end

  def wait(time)
    while time > 0
      time -= 1
      Graphics.update
    end
  end

I called the method to run the animation and it works, so far so good, but the problem is, WHILE the portrait goes up and down, I cannot move my character until the animation is finished.

So that's it, I'm stuck in the loop block, what I want is to watch the portrait moving up and down while I walk around village, talk to npc, etc.

Anyone can solve my problem ? Or better solution ? Thanks in advance


texts:
This question is actually about GameEngine2D which is part of PSM SDK (for PlayStation Vita development), however as stated in documentation it's loosely based on cocos2d library. I hope that my question is generic enough to be answered by other cocos2d users, so that's why cocos2d tag. Feel free to check my question on Sony forum.

Basically I'm trying to implement "debug layer" functionality, i.e. if I press, for example, "Triangle" button some debug information (like FPS) would apper "above" current Scene.

Currently I've implemented it this way:

I have a DebugNode : Node class, that performs necessary drawing,
it's instance is created on app init, and reference is stored in a
"global-like" Game class.
On Trianle press I check Director.Instance.CurrentScene.Children, and if does not contain DebugNode instance add it, or remove otherwide (so it's a toggle).

It's working fine, but it have issue I don't like, on a scene switch new scene does not have DebugNode, and also I need to remove DebugNode from CurrentScene before scene change, because Node can't have multiple parents. The solution to this could be by having multiple DebugNode instances, but that is also solution I don't like.

I have 2 questions regarding this:
1. Is my approach to a task is generraly reasonable? Is it done if not the best way, but at least reasonable way?
2. How my approach could be improved, particularly in case of Scene switching?


texts: How to Display hints to user when he is inactive for more than 5 sec in unity?

texts:
I have made a 2D Game using unity in which user has to select objects of similar color and now i want to display hint when user is unable to select the color for more than four seconds.

I want something similar to candy crush hint displaying system in which candy crush shows hint by highlighting the possible combination if user is not able to identify any combination himself.

I cannot figure out how to find if the user is inactive so that i can display hints.

I would really appreciate if someone can help me in figuring it out. Thanks in advance.


texts:
I am trying to find the best way to correctly do normal mapping in a 2D batched sprite renderer.

For each sprite sheet (aka texture atlas) I render all sprites as a textured quads with a single glDrawElements() call. Therefore, vertex coordinates in VBO are already transformed (on CPU) according to sprite position, rotation and scale.

Unfortunately, on rotated sprites normal map texture is also rotated, leading to incorrect normals:

I did a bit of research on this subject and so far I found few possible solutions:

Pass tangents to shader. Pretty straightforward, the same way it's usually done for 3D models. While this approach would work, doing it for just simple 2D sprites seems quite wasteful.
Pass just sprite rotation in additional vertex attribute. Then I could use this attribute in the fragment shader to rotate normal vector accordingly.
Use dFdx(), dFdy() functions. It looks like I could use these functions to deduce transformation from screen to texture coordinates and then use it to rotate normals. To be honest, this approach is not entirely clear to me, and I don't fully understand its possible performance implications, especially on mobile platforms.
Use geometry instancing. I think if I use glDrawElementsInstanced() and just dump all the sprite coordinates + transformations in one giant texture buffer, I then could use this information in the fragment shader to rotate normals. But as with approach #3, I don't fully understand if it could lead to possible performance or compatibility issues on mobile platforms.

So far I think approach #2 is probably the better solution. Not only it is simple and requires minimal changes to the code, but it would also allow me to offload sprite rotation calculations from CPU to GPU. I'd still have to pass sprite rotation per-vertex (and not per-sprite), but I don't think this is to big overhead.

But maybe there is a better, more elegant or more performant solution to this problem? How this is typically done in 2D games?


texts:
I have a mesh that has holes. I found a paper, An Automatic Hole-Filling Algorithm for Polygon Meshes

It details an algorithm that uses a k-d tree for finding holes (from a manifold triangle mesh). The steps are as follows:

  Step1: Compute the center of each triangle and the correspondences between the center and three vertexes of the triangle;

  Step2: Set up the Kd-tree according the centers of triangles;

  Step3: Search the Kd-tree and check up the topological connectivity of the corresponding edges, and find the
  boundary edges;

  Step4: Distinguish the different boundary loops according to the topological connectivity of vertexes;

I do not not understand how this algorithm actually finds the hole, can some please explain this in Layman's terms so that I can implement it --- I know there are probably better way out there of finding holes but I need to understand this particular algorithm.

Please help


texts: Does Apple allow customers to play over Bluetooth?

texts:
I'm a beginner in app development so sorry if my question is cheap :(

I wanted to start developing a card game and i was wondering if apple allows customers to play over Bluetooth or not ( on multiplayer )

I asked this question because i did not want to go all the way and realize that my game does not work over Bluetooth.


texts: How to create a regular grid of triangles correctly?

texts:
I am trying to create an terrain using opentk/opengl.

I have a problem with the VBO/IBO.
I think a picture of the problem is the best way to show it:

I dont understand why the last triangle of a row connects to the first vertices of the row.

Here is the code:

int mapSize = 7;
    void CreateVertexBuffer()
    {
        Vector3[] vertices = new Vector3[(mapSize + 1) * (mapSize + 1)];
        short[] indices = new short[ ((mapSize)*(mapSize)) * 6];

        for (int x = 0; x < mapSize + 1 ; x++)
        {
            for (int y = 0; y < mapSize + 1 ; y++)
            {
                int li_offset = x * (mapSize + 1) + y;
                vertices[li_offset] = new Vector3(x / 4.0f, 0 , y / 4.0f);
            }
        }
        int index = 0;
        for (int x = 0; x < mapSize ; x++)
        {
            for (int y = 0; y < mapSize ; y++)
            {
                indices[index + 0] = (short)( x * (mapSize + 1) + y);
                indices[index + 1] = (short)(indices[index + 0] + mapSize + 2);
                indices[index + 2] = (short)(indices[index + 0] + mapSize + 1);

                indices[index + 3] = (short)(indices[index + 0]);
                indices[index + 4] = (short)(indices[index + 0] + 1);
                indices[index + 5] = (short)(indices[index + 0] + 2);

                index += 6;
            }
        }
        GL.GenBuffers(1, out vbo);
        GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);
        GL.BufferData<Vector3>(BufferTarget.ArrayBuffer,
                               new IntPtr(vertices.Length * Vector3.SizeInBytes),
                               vertices, BufferUsageHint.StaticDraw);
        GL.GenBuffers(1, out ibo);
        GL.BindBuffer(BufferTarget.ElementArrayBuffer, ibo);
        GL.BufferData<short>(BufferTarget.ElementArrayBuffer,
                               new IntPtr(indices.Length * sizeof(short) ),
                               indices, BufferUsageHint.StaticDraw);
    }

How can I make the last row of triangles properly formed like all the others?


texts:
I am trying to move a cube with my keyboard on a plane surface. However, the cube always rolling instead of moving. How could I slide the cube on the plane?

What I have done:

I added a plane game object with a mesh colider
I added a 3D cube object with a box colider and rigidbody
I appended a ControllerScript to the cube

  ControllerScript

private const float Speed = 10;

private Rigidbody rb;

void Start()
{
    this.rb = GetComponent<Rigidbody>();
}

void FixedUpdate()
{
    var x = Input.GetAxis("Horizontal");
    var z = Input.GetAxis("Vertical");

    this.rb.AddForce(Speed * x, 0, Speed * z);
}

It looks like the AddForce method upset the cube. I already tried to reduce the friction of the plane and the cube, but this only delays the problem.

How could I move the cube without rolling it? Whats the common way to do it?


texts: Compressing language for Game use to save Packets

texts:
Given ASCII is 8 bits (1 byte), UNICODE is 32 bits (4 bytes).

An idea came to my mind to support multiple language by isolating certain UNICODE Letters to support multiple language for my chat(game) program.

It will be composed of [4 bit (Language trigger)] + [8 bits (255 possible characters) x 16]

Example:

trig|message per character, each 8 bit is character depending on trigger, language changes
0001|00000000|00000000|00000000|00000000|00000000....

Trigger for characters: (example purpose only)

0001 Normal Latin
0010 European Latin
0011 Historic Latin
0100 Japanese
0101 Chinese
etc...

The characters at UNICODE not present at my list will make a special character... I'm thinking a Box (which will be present at the 0001 character list).

My in-built character table will supply the character depending on the trigger. Of course the User can only use one set of trigger and not mixed character using different triggers.

I also want to use this character for my Account Server Creation and Queries. Note that other character format do not support multi-language characters.

Result Comparison: Instead of sending 512 bits (32 bit x 16). I am actual sending 132 bits (4 bit + (8x16)) only.

Is this feasible and currently in use or am I doomed to use UNICODE? I am open for better ideas than the ones above.


texts: Javascript/html5 2d Canvas Context - Getting X, Y relative to canvas (opposed to transformed object)

texts:
I have scenario where there are several items on a the context stack and I need to get an x, y coordinate relative to the canvas itself.

The situation is I am writing a 2D game in HTML5 and I want the "character" being controlled by the user to be able to aim towards the mouse. The character is nested in transformations. There is a camera object that transforms the canvas to follow the character and perform zooms/rotations, and of course the character itself is transformed downwards, and at times rotated away from it's centre.

If I could get the position of my character relative to the canvas, I could do an atan2 to aim towards the mouse. Alternatively, if I could get the mouse coordinates relative to the centre of my character, then I could do the same.

Is there any way to do this other than to reverse all of my transform calculations?


texts: Rotate LWJGL 2 Vector4f by an angle around an axis

texts: There is a method in LWJGL 2 to get the rotation Matrix around an axis with a certain angle- Matrix4f.rotate(angle, axis, dest, src). Is there a similar way to rotate a Vector4f around a Vector3f or Vector4f? What can I do to rotate around 2 axes? I am implementing an FPS Camera


texts: What is the more appropriate way to implement a health bar in iOS?

texts: I'm building a game a pokemon like rpg game in iOS using Swift. I'm currently in the process of making graphics and is in the dilemma of either just using a health bar blank and dynamically changing the length of a health bar or should I instead use intervals (100percent.png, 90percent.png) to represent damage? Which way is more appropriate to conserve memory and is more efficient?


texts:
I been following the playlist in brackeys for unity for beginners and it gets a little fast and complicated at the end and just curious about if a script makes a reference like:

FindObjectOfType<GameManager>().EndGame();

With GameManager being a empty and EndGame being a function to another script.

It runs it but does it connect to the script through the GameManager object since it's connected to the script?

I just want to know how it's getting to the script function and that is the only mention of GameManager in the whole script.


texts:
Using pyglet, I am trying to create a UVSphere mesh, and on its surface I would like to display a mercator-projection map. In researching examples of pyglet texture mapping, I have found:

Nehe tutorial 6 in pyglet. However this uses immediate mode, and shows the entire texture on each cube face.
pyglet_obj_test, which looks like it includes texture maps. However instead of showing the chosen texture, it shows an even color.
stackoverflow question, which looks like there was an answer with a solution. However the referenced gists showing working code have disappeared.
Another implementation, referenced in the pyglet google group

Are there any simple examples of a working mesh + texture map in pyglet?

Edit: I found out the pyglet_obj_test code is looking for lines in the .obj file starting with vt in order to create texture mapping coordinates. However the Wavefront exporter in Blender apparently has no option to export this information. I exported the same mesh with each of the other available types:

COLLADA (.dae)
Stanford (.ply)
Stl (.stl)
3D Studio (.3ds)
Autodesk FBX (.fbx)
X3D Extensible 3D (.x3d)

Perhaps there's a pyglet importer for one of these formats...

Edit 2: I clearly have a poor understanding of the wavefront format. It seems vt lines are not necessary. What I was missing is full f maps.

For instance, to simplify things way down, I created a 3d mesh that was actually a single square, with a texture mapped onto it. In Blender it shows the square with distorted texture, but the built-in wavefront exporter produces a single line of texture mapping f 2//1 1//1 3//1 4//1. These should apparently instead be something like f 2/0/1 1/0/1 3/0/1 4/0/1 (note there should be a number between the two slashes).

Apparently Blender only does a full (proper?) export of these lines if a texture is UV mapped. Applying a texture without a UV Map renders properly in Blender, but I guess the wavefront exporter doesn't properly handle it. Perhaps it's time for me to submit a Blender bug report...


texts:
code below make enemy move towards player.

    //Calculate Distance formula
    double xDiff = player.x - enemy.x;
    double yDiff = player.y - enemy.y;
    double dist = Math.sqrt(xDiff * xDiff + yDiff * yDiff);

    //find angle
    angle = (int) Math.toDegrees(Math.atan2(yDiff, xDiff));
    if (angle < 0)
        angle += 360;

    xDiff = xDiff / dist;
    yDiff = yDiff / dist;
    x += xDiff * speed;
    y += yDiff * speed;

how to draw line with length 20, same direction as enemy is moving?

enemy.x2 = angle?
enemy.y2 = angle?
draw(enemy.x1, enemy.y1, enemy.x2, enemy.y2);


texts: Sketchup for modelling, Blender for lightmaps, rendering in Xna Reach profile?

texts:
This question moved from https://stackoverflow.com/questions/4319183/sketchup-for-modelling-blender-for-lightmaps-rendering-in-xna-reach-profile

Hello. I'm a programmer looking to add some 3D assets to my game. I have played around with both Blender and Sketchup, and for my limited 3D modelling experience I'm finding I can make far more interesting models/scenes in Sketchup than blender, but I couldn't find any free lightmap baking tools for sketchup, whereas my understanding is that this is available in blender for free.

So, my question is, how can I setup a workflow whereby I can do most if not all of my work in Sketchup, and only use Blender to create the lightmaps? Is there any way to define light information in Sketchup, but have blender render the light-maps? Otherwise I'm going to have to do all the modeling in sketchup and then add the lights manually in blender every time I make a change to the scene.

Also, I couldn't find information specifically about blender and the dual texture effect in Xna Reach. Does anyone have information/tutorial/etc.. for getting lightmaps calculated with blender into Xna and rendered using the dual texture effect in xna reach (i.e. on windows phone 7).


texts: Hierarchical "Select GameObject" Dialog or names with prefixes?

texts:
I am attempting to connect a series of teleporters with entrances inside a single scene. Once the player touches a teleporter he is moved to another place. I am doing this by simply connecting two game objects as shown in the following screenshot. The particle system in the center of the upper side is used as teleporter, the red line indicates the game object where the player will be transported to.

Sadly, this results in an utter mess when attempting to select a new entrance the teleporter should link to. There is no way to guess which entrance corresponds to which side and dice:

So the tl;dr of my problem would be this: The name of the object that should be selected is meaningless when isolated. It's the path to the object (or in other terms: the name of some parent) that is relevant.

I would see three possibilities to solve this, but sadly I haven't gotten around to find out how to do any of them.

Switch the "Select GameObject" Dialog to use the same hierarchical view as used in the scene viewer. Is there a hidden option somewhere in Unity that I overlooked?
Somehow prefix the names of my entrances programatically. Is there a way to include the path to a certain game object in its name?
My whole approach is backwards and I am doing something in a not Unity friendly way. But what would be the "correct" way to do this?


texts: How do I slowly decrease a float from 0.5 to 0?

texts:
I have a 2D racing game with a track, and the track is repeated with vector2. When I die, I want to slowly stop moving the track, but I do not know how.

Here is my code:.

using UnityEngine;
using System.Collections;

public class trackMove : MonoBehaviour
{
    public static trackMove Instance { get; private set; }

    public float speed;
    Vector2 offset;

    // Use this for initialization
    void Start ()
    {
        Instance = this;
    }

    // Update is called once per frame
    void Update ()
    {
        offset = new Vector2(0, Time.time * speed);
        GetComponent<Renderer> ().material.mainTextureOffset = offset;
    }
}

Here is my current Inspector view:


texts:
Hi I want to program a card game,
in my game each card can do multiple actions, depend on the situation in which the player is facing.
For example There is an "Attack" card which can attack another player, the attacked player can defend itself in multiple ways - it can use "Run Away" card, it also may use another card to rule a cube to avoid the attack etc,
The "Attack" may also be used to shot an attacker to avoid dying.
In short each card can be used in all sort of ways and I'm having trouble to code these rules,
How can I create the session between 2 players? (attacker and defender)
thanks


texts:
I am making a "Don't touch the spikes" remake in unity C#.
I want to make the effect of the dots behind the bird like in the image below. How can I do this?


texts: Creating a Simple Puzzle resolution Algorithm

texts:
I develop a (really) simple puzzle game that asks you to join a point A to a B (enter/exit) using a ball and mechanisms that you can rotate to give the correct direction to the ball in order to join the exit.

Here is screenshots of a simple level, showing clearly the purpose of the game:

1) New level started, the mechanisms are rotated in a random way:

2) Level is completed, all the mechanisms are rotated properly to give the ball the right path to join the exit:

Question:

How can I create an algorithm allowing me to automatically generate levels by taking into account the rotations and leaving only one possibility for the player to complete the level?

I'd also like to add more complexity by adding more mechanisms (to create creating difficulty levels).

I don't think it's necessary to talk about tech, but I'm using C# and Unity.

Let me know if you need more information.

Thank you!


texts: Unity error converting quaternion to euler rotation

texts:
When I try to run my game in unity, it comes up with the error:

No appropriate version of 'UnityEngine.Quaternion.Euler' for the argument list '(UnityEngine.Quaternion)' was found.

When using the update code in (written in javascript):

transform.Rotate(Quaternion.Euler(transform.rotation * Quaternion.Inverse(GameObject.Find("Main Camera").transform.rotation)));

Any help would be appreciated.


texts: Is there a good existing starting point for realistic 2d racing car physics?

texts:
I'm trying to get a realistic behaving racing car into my 2d top-down game.

Making a very simple car that drives around is straight forward but I want a reasonably sophisticated model that models Newtons laws and the forces on the car well and results in something great.

I searched the web for a good tutorial on how to do this but there doesn't seem to be much example code out there.

I followed this tutorial http://www.gamedev.net/topic/470497-2d-car-physics-tutorial/ which was very good and seems like a good starting point but if you have a play with the included demo you can see it still has a fair way to go before its a convincing racing car.

I hear that some 3d game engines like Unity come with a good starting vehicle model out of the box. Is there something like that out there for 2D?

Just want to make sure I am not missing some great existing 2d starting point I don't know about before I spend a LOT of time reading and figuring out all the correct forces etc needed to build my own from scratch.

This article seems to describe all the things you need: http://www.asawicki.info/Mirror/Car%20Physics%20for%20Games/Car%20Physics%20for%20Games.html but the source code links are broken unfortunately.


texts: How can I implement shader lookups for my material system?

texts:
I have been working on a material system and for the most part everything works just fine, however, I hard code the shader that will be used. Obviously this causes a problem when I want to have the materials be saved through the material editor.

What I ended up doing was having the material save "attributes". These attributes would know if the material is using a texture or diffuse color (that's it for now). I then have a VS/PS to render objects with a texture or a diffuse color. Then for each of those, I have shaders for either no lighting, or my lighting system. Right there that will leave eight different shaders, so you can see where the complexity comes in with which ones to pick. Also, that is only if all the objects all have the same vertex type (position, tex coord, normal). However, that is not always the case, as some times the geometry may be built differently.

My question is, how can a propery shader lookup system be written for a material system? There comes into two things I can think of

Shaders based upon different lighting models
Shaders based upon different vertex formats


texts: How to implement n-body in an Entity Component System

texts:
Recently I've been throwing problems at Entity Component Systems to see how far I can push the paradigm. One problem in particular I struggle with, which is writing an elegant implementation of the n-body algorithm.

First, let me clarify the terminology of ECS:

Component: a structure that holds data
Entity: a unique identifier used to associate and retrieve component data
System: logic executed on entities that have a specific set of components

In ECS, for every frame, each system linearly walks over the matching entities. A typical ECS implementation lays out data consecutively in memory per component, which has as advantage that it is very CPU-cache friendly.

To implement n-body, we could have three components (Location, Mass, Speed). We could then have a system called Gravity, which will update the speed of all entities that have Location, Mass and Speed. Then there could be a Move system that walks over entities with Location and Speed, and updates the locations.

For every matching entity, Gravity will have to walk over all the entities (minus one) to compute the attraction force. The first problem is, how do I efficiently get the relevant entities? A query seems wasteful since the entity set it needs is the set that Gravity is already walking over.

The second problem is when entity A computed the attraction force from entity B I'd like to reuse the computed distance when calculating the attraction force from A on B. Ideally these two computations take place in the same iteration. That, however, impacts how I iterate over the entities. If I computed A <-> B when I processed A, I don't need to iterate over A anymore when processing B.

I am not actually interested in the most practical way to implement n-body, but am curious if/how this kind of problem can be elegantly implemented with ECS.


texts:
I am new to game development.

I was trying to use this http://blog.gemserk.com/2012/07/03/drawing-a-projectile-trajectory-like-angry-birds-using-libgdx/  projectile example in eclipse android using java language

What mistake did I make? How to do.

Here my code:

import android.content.Context;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.graphics.Canvas;

import android.util.Log;

import android.view.MotionEvent;

import android.view.SurfaceView;

import android.view.View;

import com.badlogic.gdx.math.Vector2;

public class Example extends SurfaceView {

public float x;
public float y;

public static class ProjectileEquation {

    public float gravity = -10;
    public Vector2 startVelocity = new Vector2();

    public Vector2 startPoint = new Vector2();

    public float getX(float t) {
        return startVelocity.x * t + startPoint.x;

    }

    public float getY(float t) {
        return 0.5f * gravity * t * t + startVelocity.y * t + startPoint.y;
    }
    {
        Log.i("ProjectileEquation", "Create!");
    }

}

public static class Controller {

    public float power = 50f;
    public float angle = 0f;

}

public Example(Context context) {
    super(context);
    Log.i("Example constructor ", "Create!");
    Example.projectile yyy = new Example.projectile(context);
    Log.i("run", "Create!");
    this.x = yyy.x;
    this.y = yyy.y;
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    super.onTouchEvent(event);

{
        Log.i("OnTouch", "Create!");
    }

    x = event.getX();
    y = event.getY();

    return true;

}

public static class projectile extends View {
    public float x;
    public float y;
    private Controller controller;
    private ProjectileEquation projectileEquation;

    public int trajectoryPointCount = 30;
    public float timeSeparation = 1f;

    private Bitmap bmp;

    public projectile(Context context) {
        super(context);
        Log.i("Projectile constructor ", "Create!");
        this.controller = new Controller();
        this.projectileEquation = new ProjectileEquation();
        this.projectileEquation.gravity = -10;
        bmp = BitmapFactory.decodeResource(getResources(),
                R.drawable.ic_launcher);

           {
            projectileEquation.startVelocity.set(controller.power, 0f);
            projectileEquation.startVelocity.rotate(controller.angle);

        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        float t = 0f;

        float width = this.getWidth();
        float height = this.getHeight();

        float timeSeparation = this.timeSeparation;

        for (int i = 0; i < trajectoryPointCount; i++) {
            float x = this.x + projectileEquation.getX(t);
            float y = this.y + projectileEquation.getY(t);

            canvas.drawBitmap(bmp, x, y, null);
            canvas.drawBitmap(bmp, width, height, null);
            t += timeSeparation;

        }
    }

}
}


texts: What can I use to make my unique music ideas a reality?

texts:
I have several different music ideas for my game BGMs, but I do not have the musical skills nor the equipment to make them. The most I can do is beat-box them or make a drum beat (had I a drum). Is there a program or some other way to make my music real?

For instance, I've recently been trying GarageBand's Musical Keyboard to create the music but they don't have the exact beats I'm looking for, like a particular tap of a drum for example.


texts: Loss in quality on downsized sprites in Game Maker

texts:
I'm having an issue with sprites quality in Game Maker.

I have some sprites used for UI with an original size of 2048*512. I need to resize them in game to 512*128. But when I do, I got a loss in quality.

This is the original picture, resized to 512*128 with a third-party software:

This is the sprite, as it appears in Game Maker room editor (and in game) once resized to 512*128:

Are there general guidelines for this kind of situation?

By the way, it's on Windows. Though I tried launching the game on an Android device and the result was the same.


texts:
I must say that I am really confused by how a view matrix is constructed and works.

First, there are 3 terms: view matrix, lookat matrix, and camera transformation matrix. Are those 3 the same, or different things. From what I undestand, the camera transformation matrix is basically the model matrix of the camera, and the view matrix is the inverse of that. The lookat matrix is basically for going from world space to view space, and I think I undestand how it works (doing dot products for projecting a point into another coordinate system).

I am also confused by the fact that sometimes, it seems like the view matrix is built by translation and dot products, and some other times, it is built with translation and rotation (with cos and sin).

There are also quaternions. When you convert a quaternion to a matrix, what kind of matrix is this?

Can someone explain to me how it really works, or point me towards a good resource.

Thank you.


texts:
this is my first post on this SE, and I have noticed the large numbers of closed/downvoted career-related questions, so I will try to ask in a fashion most gingerly.

What would the career roadmap for a video game programmer be like? There seems to be a consensus that the video game industry is not so structured, and a roadmap would not be useful at all.

To be more specific, I understand the difference between role and title, IE there may be one person with the title "Engine Programmer", but he may do other things, and other people may do his role as well.

How would I chart out my career road map? Would it be simply moving from a junior programmer in a certain field, to a more senior position on that field, or are there certain fields which are inherently more senior than others?

Notes:

I am currently studying for a degree in video game programming
This is for an assignment, and I am told to consult real developers to be able to better perform.


texts:
Cube World uses a pretty good looking shader, I especially like the shading of the characters:

Is this soft shading? I'd like to achieve this effect in Unity 3D Free, but since the free version doesn't support dynamic shadows, guess I have to code it myself, so an article on this or the algorithm would be great.


texts: Most useful free third party Android Game libraries?

texts:
Since I have started finding a good third party libraries for game development on android platform, Im getting confused. So want to know from the people who are already using some of the game libraries themselves (no googled resources please).

So my question is : What are some of best Android Game libraries(2D/3D)?

Note: to keep this poll as useful as possible, please remember:

When adding a new library, provide a short summary of what it does / why you think it's useful. Please make sure the answers are not repeated.

One link/source per answer is preferable.


texts: Bouncing projectile off of sprite, the sides work but top and bottom do not

texts:
I'm having a problem bouncing a projectile off a sprite, we've been asked to move the projectile using the equations of motions which makes things a little more difficult but as far as I can see what I have should work.

What I'm trying to do is change the angle of the collided projectile depending on which direction it is coming from.

Here is a video that is hopefully not too laggy for you to see what is happening:

Link

When the projectile collides with the left or right hand side of the sprite everything works as expected, it just switches X direction.

When it hit's the top or bottom of the sprite however it doesn't change, it just sort of rolls along the top and the shoots off.

Here is the movement code:

float nX = get_x() + cos(nGetAngle() * 3.14 / 180) * getU() * getT();
float nY = get_y() - sin(nGetAngle() * 3.14 / 180) * getU() * getT() + 0.5 * 9.8 * getT() * getT();
set_world_position(nX, nY);

Where U is initial velocity, T is time and nGetAngle() is the angle in degrees (which is set to radians whenever the angle is set).

Here is my collision for the top of the player:

//if the projectile is colliding in any way with the player sprite

if (projectiles[currProj]->get_y() < player->get_y()) // top of player
{
    float vx = cos(projectiles[currProj]->nGetAngle());
    float vy = sin(projectiles[currProj]->nGetAngle());

    float newAngle = atan2(-vy, vx) * 180 / 3.14;

    projectiles[currProj]->nSetAngle(newAngle);
    projectiles[currProj]->set_world_position_y(player->get_y() - projectiles[currProj]->get_height() - 1);
}

and here is my collision for the left of the player:

else if (projectiles[currProj]->get_x() < player->get_x()) // left of player
{
    projectiles[currProj]->set_world_position_x(player->get_x() - projectiles[currProj]->get_width());

    float vx = cos(projectiles[currProj]->nGetAngle());
    float vy = sin(projectiles[currProj]->nGetAngle());

    float newAngle = atan2(vy, -vx) * 180 / 3.14;

    projectiles[currProj]->nSetAngle(newAngle);
}

The left side collision works, the top does not and I have no idea why.

If necessary I can post the entire project somewhere.


texts: Are there alternative game distribution methods?

texts:
According this source, publishers account for about half the cost of a game's price to consumers. Could there be an alternative means of distribution that allows people to pay game developers more directly without a publisher?

i.e.: something like peer-to-peer torrents be used for distribution, while using something like Paypal to pay for keys to unlock the games?


texts: Health zone heals player but I have a problem

texts:
Hello I am creating a special health zone that gives the player health and my current scripts health is going up super fast and I want it to go up by 2 hp per second. How would I do this?
Here is the health zone script.
{
    public PlayerHealth playerHealth;
    public float healthGain = 2f;

    void OnTriggerStay2D(Collider2D other)
    {
        if (playerHealth.currentHealth < playerHealth.maxHealth)
        {
            playerHealth.currentHealth += (int)healthGain;
            playerHealth.healthBar.SetHealth(playerHealth.currentHealth);
        }

        if (playerHealth.currentHealth >= playerHealth.maxHealth)
        {
            playerHealth.currentHealth = playerHealth.maxHealth;
            playerHealth.healthBar.SetHealth(playerHealth.currentHealth);
        }
    }
}


texts:
I have seen a lot of people think that for a 2D platformer game, Unity2D physics is not really the best approach, and recommend implementing your own physics.

I found the idea interesting, but I don't know how to approach the issue.

Using 2D Rigidbodies, and setting them as kinematic, allows you to ignore unity's physics. But how would collisions be handled without relying on Unity collision system?


texts: Alternative to JSF for browser-based 4X game

texts:
I intend to make browser based MMO game. Something from Master of Orion genre but with more accent on command ship operations.

I've done some tests and research and turns out that indeed, for dictionary type data (like technology tree nodes, inventory items, mission definitions) the XML files seem best approach. But there will be whole lot of them and they are inter-dependent so performance-wise there is no option to load them on each HTTP request.

I want system where application starts, loads definitions to dictionaries from XML and keeps it in memory for the whole time the application works. Application awaits requests and responds them with XHTML using the dictionary data from array/collection kept in memory. All the other data like players' data, alliances' data etc. comes normally from relational DB. I think this model would put much less strain on DB and whole application would be much less resource-hungry.

So PHP I know and used is not an option, right?. Is my only option some Java server technology like JSF? I coded in Java previously, but it was Java SE and it didn't make good impression on me. So are there alternatives? If not what specific Java server technology would be most suited?


texts: Why is 3D game development supposed to be so hard?

texts:
This may be kind of a dumb question. I have little experience in programming and no experience in game programming. I've only done simple "if, then" programming and simple circuit board chip programming. I do have experience with graphics software similar to  3DS Max. I was wondering what makes programming a game so difficult. All I want to create is a game world the size of a room with earth like physics such as gravity. More of a physics simulator than a true game. Would that be very difficult?

From what I've read it sounds like it would be difficult but I don't know why. I know the physics and have the graphics and rendering experience. Why is it supposed to be so difficult? Is C++ just really hard to learn or am I missing something. I'm curious because I'm considering learning C++ but don't know if it's worth it.


texts: Fishbowl effect correction in raycasting engine suggestions (pseudo 3d projection)

texts:
I'm writing a simple raycaster in golang and I have some problems understanding perspective correction. The code is simple, the main rendering loop is this:

    curVector := playerVector.NewRotated(-curFov / 2)
    rotateStep := curFov / float64(screen.Width()) // Angles per screen row
    // Traverse each row of our screen, cast a ray and render it to screen buffer
    for i := 0; i <= screen.Width(); i++ {
        curVector.Rotate(rotateStep)

        hit, distance, tile, tileP := rayCast(curX, curY, curVector, viewDistance)

        if hit {
            // distToHeight is basically linear (screen.Height()/distance)
            drawTexturedWallColumn(screen, tile, i, distToHeight(distance, screen.Height()), tileP) // Project walls on screen
        }
        // drawSpritesColumn(screen, i, curVector, distance) // Project sprites on screen
    }

So I just cast rays with even angle intervals and get this fishbowl effect:

So, I understand that the problem is with angle intervals and sphere projected rays with the same length. I found this question How can I correct an unwanted fisheye effect when drawing a scene with raycasting? and tried to implement the same logic:

leftVector := playerVector.NewRotated(90)
    // Traverse each row of our screen, cast a ray and render it to screen buffer
    for i := 0; i <= screen.Width(); i++ {
        progress := float64(i)/float64(screen.Width()) - 0.5 // -0.5 to 0.5
        stepX := (playerVector.X + progress*(leftVector.X*2)) // *2 to make 90 FOV
        stepY := (playerVector.Y + progress*(leftVector.Y*2))
        curVector := Vector{X: stepX, Y: stepY}

        hit, distance, tile, tileP := rayCast(curX, curY, curVector, viewDistance)

        if hit {
            // distToHeight is basically linear (screen.Height()/distance)
            drawTexturedWallColumn(screen, tile, i, distToHeight(distance, screen.Height()), tileP) // Project walls on screen
        }
        // drawSpritesColumn(screen, i, curVector, distance) // Project sprites on screen
    }

But the result is almost the same (FOV variable is not used here but it's around 90, it's not important at the moment). The difference is that this one has a more "linear" fishbowl effect because of evenly spaced intervals (progress variable):

So, I don't know how to fix this, I also tried to use perpendicular distance (distance*cos).


texts:
I've recently learned how to make games for Unity3d, and now I want to start making games! I can't wait to start!

However, before I can make 3D games, I need to learn 3D modeling for character design, level design, and some animation.

What is the easiest 3D modeling software, compatible with Unity3d?   I do not want to spend too much time learning the software.  From what I've heard, Blender is a bit complicated to use. Maya and 3dsMax seem very powerful.

Could someone point me in the right direction?  I don't want to spend a lot of time learning.  I know its not that easy, but you guys have experience, you guys probably know out of all which one is easier and powerful.  Could you recommend a software?

Many Thanks!


texts: How to fx low FPS in a single threaded Directx9 3D game

texts:
We're having issues with low FPS in a third-person shooter 3D game. This happens when you have too many polygons on screen. The FPS is locked to 60, and the gameplay is fine, but the moment when you have like 900 entities on screen, the FPS immediately drops to 45 or 50.

IDirect3DDevice9::DrawIndexedPrimitive is normally called 200-900 times to render the entities, however, when you render more polygons than usual, let's say 500,000 more vertices then it's called 6000-7000 times and the FPS drops to 45-50. I ran a profiler and saw this function eating up the CPU, consuming around 19% of the resources.

I have some ideas to deal this issue, but I need some advice. Possible solutions that I can think of:

Secondary thread for rendering

I'm not sure if introducing multi-threading will fix the problem, but I'm hopeful.

Upgrading to Directx11

If this can help, then can someone explain how we need to render the vertex buffers of entites? This how we do it now for every entity:

d3dDevice->Clear(0,NULL,D3DCLEAR_TARGET, D3DCOLOR_XRGB(255,255,255),1.0f,0);

// Turn on wireframe mode
d3dDevice->SetRenderState(D3DRS_FILLMODE,D3DFILL_WIREFRAME);
d3dDevice->BeginScene();

for (DWORD i=0; i<numMaterials; i++)
{
    // Set the material and texture for this subset
    d3dDevice->SetMaterial(&meshMaterials[i]);
    d3dDevice->SetTexture(0,meshTextures[i]);

    // Draw the mesh subset
    mesh->DrawSubset( i );
}

d3dDevice->EndScene();
d3dDevice->Present(NULL, NULL, NULL, NULL);

Both

Upgrade to Directx11 and use a secondary thread for rendering?


texts: Issues with OpenGL rotation matricies and shaders

texts:
I am having an issue with my rotations in my opengl shaders. My program works fine before I add in my rotation matrices. Here is an example, at YouTube. After I add rotations to my shaders, there are issues. Here is an example.

Here is my vertex shader:

    #version 130

in vec3 position;
in vec4 color;
in vec2 texcoord;
uniform mat4 view_array;
uniform mat4 end_array;
uniform mat4 projection_matrix;
uniform mat4 trans_matrix;
uniform mat4 x_rotation_matrix;
uniform mat4 y_rotation_matrix;
uniform mat4 z_rotation_matrix;

out vec4 pos;
out vec2 texture_coordinate;
//out vec4 color_value;
void main()
{
     mat4 vw_matrix = mat4(1.0);
     mat4 rotation_matrix = x_rotation_matrix * y_rotation_matrix;
     mat4 model_matrix =  trans_matrix * rotation_matrix;//
     pos = projection_matrix * vw_matrix * model_matrix *  vec4(position, 1.0);
     gl_Position = pos;
     texture_coordinate = texcoord;
     //color_value = color
}

Here are the values for my matrices:

// rotation matrices

x_rotation_matrix[0] = 1;
x_rotation_matrix[1] = 0;
x_rotation_matrix[2] = 0;
x_rotation_matrix[3] = 0;
x_rotation_matrix[4] = (float) cos(-yaw * (PI / 180));
x_rotation_matrix[5] = (float) -sin(-yaw * (PI / 180));
x_rotation_matrix[6] = 0;
x_rotation_matrix[7] = (float) sin(-yaw * (PI / 180));
x_rotation_matrix[8] = (float) cos(-yaw * (PI / 180));
x_rotation_matrix[9] = 0;
x_rotation_matrix[10] = 1;
x_rotation_matrix[11] = 0;
x_rotation_matrix[12] = 0;
x_rotation_matrix[13] = 0;
x_rotation_matrix[14] = 0;
x_rotation_matrix[15] = 1;

y_rotation_matrix[0] = (float) cos(-pitch * (PI / 180));
y_rotation_matrix[1] = 0;
y_rotation_matrix[2] = (float) sin(-pitch * (PI / 180));
y_rotation_matrix[3] = 0;
y_rotation_matrix[4] = 0;
y_rotation_matrix[5] = 1;
y_rotation_matrix[6] = (float) -sin(-pitch * (PI / 180));
y_rotation_matrix[7] = 0;
y_rotation_matrix[8] = (float) cos(-pitch * (PI / 180));
y_rotation_matrix[9] = 0;
y_rotation_matrix[10] = 1;
y_rotation_matrix[11] = 0;
y_rotation_matrix[12] = 0;
y_rotation_matrix[13] = 0;
y_rotation_matrix[14] = 0;
y_rotation_matrix[15] = 1;

z_rotation_matrix[0] = (float) cos(-pitch * (PI / 180));
z_rotation_matrix[1] = (float) -sin(-pitch * (PI / 180));
z_rotation_matrix[2] = 0;
z_rotation_matrix[3] = (float) sin(-pitch * (PI / 180));
z_rotation_matrix[4] = (float) cos(-pitch * (PI / 180));
z_rotation_matrix[5] = 1;
z_rotation_matrix[6] = 0;
z_rotation_matrix[7] = 0;
z_rotation_matrix[8] = 0;
z_rotation_matrix[9] = 0;
z_rotation_matrix[10] = 1;
z_rotation_matrix[11] = 0;
z_rotation_matrix[12] = 0;
z_rotation_matrix[13] = 0;
z_rotation_matrix[14] = 0;
z_rotation_matrix[15] = 1;

GL20.glUniformMatrix4fv(
    GL20.glGetUniformLocation(programID, "x_rotation_matrix"), true, x_rotation_matrix);
GL20.glUniformMatrix4fv(
    GL20.glGetUniformLocation(programID, "y_rotation_matrix"), true, y_rotation_matrix);
GL20.glUniformMatrix4fv(
    GL20.glGetUniformLocation(programID, "z_rotation_matrix"), true, z_rotation_matrix);

Here is my transformation matrix:

trans_matrix[0] = 1;
trans_matrix[5] = 1;
trans_matrix[10] = 1;
trans_matrix[12] = x;
trans_matrix[13] = y;
trans_matrix[14] = z;
trans_matrix[15] = 1;

What am I doing wrong?


texts: Null Reference Exception while getting Components

texts:
I'm trying to access my enemy and spawning values from two different classes into a class that is trying to change them both. Although when I do this I keep getting a Null Reference Exception error. The error is where spawnManager first gets called.

This is the code that is trying to get the two values. (And just to note I am trying to access these two values from my Welcome scene and these two values are in my Game scene but I do not know if this is affecting anything):

private EnemyAI enemy;
private SpawnManager spawnManager;

void Start() {
    spawnManager = GetComponent<SpawnManager>();
    enemy = GetComponent<EnemyAI>();
}

public void onEasy() {
    spawnManager.enemyShipWait = Random.Range(1f, 3f); <-- This line has the error
    spawnManager.randomPowerupWait = Random.Range(7f, 12f);
    enemy.speed = 2.75f;
}

These are the two pictures of my scenes:
Game Scene:

Welcome Scene:


texts: How can I avoid writing a class for each of my 800 different items?

texts:
I have a webgame written in PHP and using MariaDB for the database. I'm currently looking into ways of improving core systems.

One example would be items. Currently, there is a table data_items that lists all of the items, what category they fall into, their sale value, description, icon and so on. There is then an inventory table with foreign keys referencing users and data_items, and a quantity column. Simple, and it works.

However, some items have effects. Actually most of them do.

Currently effects are implemented in one of two ways.

The item is requested specifically by the code. For example, a particular feature requires a particular item, so that item is loaded up, its quantity is checked in the player's inventory, and the code proceeds if the user has the item. This is fine.
The item's properties are checked. For items in the "Consumables" category, there's currently a switch statement that provides different effects based on the item in question. This is horrible.

I'm considering the idea of having a class for each item. The class can then have methods such as isConsumable(), consume(), and whatever else may be needed as applicable to each item.

Should I still have the database? I assume so. There are cases when items need to be searched, eg. by category, for showing the player's inventory. In a case like this, where there are upwards of 800 items at this point, I wouldn't want to have to load 800 classes.

What kind of combination of things should I be aiming for here? Maybe have an item "prototype" that just holds data, which can be used when enumerating the items for the inventory? Then, when the item is actually used for something, check for its specific class and only load it at that point? I think that makes sense, but any advice on this matter would be very helpful indeed.

I'm facing a similar problem for the creatures within the game. Most of them have nothing special to them, so the database works fine. But some have different images based on certain factors. One in particular can be customised to have whichever pair of colours the user chooses. These are currently all handled by switch statements in the getImage() method of the generic creature object. Should this be split into classes for each (of the 1200+) creatures?


texts: Alpha blending, transparence and z-ordering

texts:
I'm making some tests with alpha blending in a projet and I don't understand something.

In my tests I've done something like that and everything look good:

Draw blue box first (depth test: true, blend alpha: none, color: 1, 1, 1, 1)
Draw left Mario (depth test: false, blend alpha: true, color: 1, 1, 1, 0.8)
Draw red box (depth test: true, blend alpha: none, color: 1, 1, 1, 1)
Draw right Mario (depth test: false, blend alpha: true, color: 1, 1, 1, 0.8)

Every tutorial say that we should:

Draw opaque object first
Order transparent object back to front then draw them.

Here is the result:

So, I'm not sure to understand how it work/what is wrong (I've read this document).

Thanks!


texts: We have managed to play audio files using SDL's Mix_PlayMusic function. The problem now we need to do some upsampling for one audio to match the other so that both have same duration. Any idea how to resolve this issue.


texts: How do I test if an AABB and concave polygon intersect?

texts:
The player's collider is an axis-aligned bounding box in my 2D platformer, but the environment can be different shapes. I already have collision-detection that prevents the player from going through colliders, but I don't have anything for getting the player out of concave polygons if he ends up inside one by for example flipping the collider when changing direction from/to left/right.

SAT doesn't work on concave polygons, so I need an algorithm that can tell me if an AABB and any polygon intersects and give me the minimum translation vector to push the shapes apart. (The velocity of the objects will not need to be considered).

BTW the game is written in C# with the MonoGame framework if that's of any relevance.


texts:
I'm not sure if this is a suitable question but I found a game that had all it is sprites and stuff saved in INA and AN format and I got curious to know which program is it.

Or is it some sort of compressing or alike and how it is usually done?

Anyone know?

Here is the content of one of the files:
http://pastebin.com/EzUsFvdG

Here is a hex dump of the above file: http://pastebin.com/CTErFBcS

The above one is the AN file and the bellow one INA.

Hex dump of a INA file which seems to be some sort of map or data file (I believe because of the layers info, etc?) http://pastebin.com/2fWn8izR


texts:
I'm creating this mesh during runtime in Unity3D.

The mesh shape is ok, but as you can see on this screenshot, the mesh is not correctly rendered: it's only rendered when the camera is looking back at the mesh, but I don't want to rotate the mesh or modify the camera position.

I know I can create a simple shader to activate backface culling... But I don't need a custom shader. I want to understand what I do wrong.

All my normals are set to -Vector3.forward:

        normals[vert_idx] = -Vector3.forward;
        normals[vert_idx + 1] = -Vector3.forward;
        normals[vert_idx + 2] = -Vector3.forward;
        normals[vert_idx + 3] = -Vector3.forward;

Are normals the only things involved in this problem? Or should I look to triangles order, vertices order or something?

Thanks.


texts: What languages are required for an mmo browser game?

texts:
What 'Things' are required for this sort of game? I understand java, c++, javascript, and objective c (iphone programming) fairly well, however I know nothing about networking programming, but I do know about networking in general (packets, mac addresses all that good stuff)

So this is my main question: for a game like Tribal wars, Evony, Shadowland online, travian, what programming languages do I need to know to take this on and finish it by myself? I'd imagine that most of it will be done in java, but for the whole connecting other players, combat, leader boards and (most importantly) making online payments for things, what languages should I learn for developing something like this?


texts:
I am currently creating a game in C++ using SDL. Many game objects and sub-systems require the use of variables such as an SDL_Renderer for drawing to the screen and delta time for updating positions and there may be more added in the future (such as a TextureManager object). In this case the code for a game object might look something like this:

void Update(float deltaTime)
{
    // ...
}

void Render(SDL_Renderer* renderer)
{
    // ...
}

However, if another variable was added as a parameter, any subclasses would have to be updated and other systems made consistent with the new parameter.

Another way of passing data around would be to have one "storage class/structure" to store these variables and pass that instead. For example:

struct Data
{
    SDL_Renderer* renderer;
    float deltaTime;
    TextureManager textureManager;
};

My question is: what a good way of passing around data in a game engine? The first example would be bothersome to update if any changes were made to the parameters and would make adding more classes difficult. What about the second example? Would it be good design to have objects depend on a single class? Are there any other design patterns for passing around data without causing dependency issues?


texts:
I am building forward + engine based off of partially http://www.humus.name/Articles/PracticalClusteredShading.pdf

If you go to page 36 on the pdf and "spot light culling section" they mention "Do plane-cone test and shrink".

However unlike pseudo code they provided for sphere shape culling, it has no more information.

Thus I am stuck drifting internet trying to find methods to achieve this.

Please guide me to the right direction.


texts: How can I rotate a camera on the X and lookat target and once looking at the target to stop slowly the rotation?

texts:
This is a screenshot showing the camera position.
I want it to rotate slowly smooth to the left and once looking at the soldier to stop rotating.

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

public class SoldierNaviFight : MonoBehaviour
{
    public Camera fightCam;
    public Transform target;
    public float speed = 2f;

    // Use this for initialization
    void Start ()
    {

    }

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

    }
}

The script is attached to a empty gameobject.
What I want to do is once the camera stopped rotating and looking at the soldier to make the soldier start moving to the right and camera should follow the soldier rotating and keep follow the soldier moving.

The main idea is to create a cut scene. The camera is position at this point just to display the cut scene.

To make the first rotation to the target I tried this:

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

public class SoldierNaviFight : MonoBehaviour
{
    public Camera fightCam;
    public Transform target;
    public float speed = 2f;
    Quaternion targetRotation;

    // Use this for initialization
    void Start ()
    {
        targetRotation = target.rotation;
    }

    // Update is called once per frame
    void Update ()
    {
        Quaternion.RotateTowards(transform.rotation, targetRotation, Time.deltaTime * speed);
    }
}

But the camera is not rotating at all.

This is screenshot of the Hierarchy and Inspector:

The script is attached to GameObject: SoldierNaviFight
The camera that I want to move is the child of SoldierNaviFight: SoldierNaviFightCamera

UPDATE:

This will rotate the camera but it's rotating it to the right instead to the left to the soldier. Not sure why:

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

public class SoldierNaviFight : MonoBehaviour
{
    public Camera fightCam;
    public Transform target;
    public float speed = 2f;
    Quaternion targetRotation;

    // Use this for initialization
    void Start ()
    {
        targetRotation = target.rotation;
    }

    // Update is called once per frame
    void Update ()
    {
        fightCam.transform.rotation = Quaternion.RotateTowards(fightCam.transform.rotation, targetRotation, Time.deltaTime * speed);
    }
}


texts: Server-side real time position calculation based on destination position - C#

texts:
What I want to achieve is to calculate the real object position based on its speed and a destination position.
In my server, I have a MapInstance that have a list of MapLayer that have MapRegions.

To resume we have:

1 MapInstance

N MapLayers
X MapRegions

Each MapInstance will update in an asynchronous task all his map layers and the common object such as NPCs and the MapLayer will update his regions of entities (monsters/items).

On the client side, when I click somewhere on the map, it sends a packet to the server with the destination position.
Then, on the server-side I receive the position and set the entity.Movable.DestinationPosition property.

As I said earlier, each map instance are updated in an asynchronous task and updates the map layers and common entities.
My problem is, my realtime position calculation formula is wrong somewhere, and I can't find where.

To understand the problem, there is some inputs:

Entity speed: 0.08 (8%)
Position and DestinationPosition are Vector3 (class) instance, where X, Y and Z are properties.

This is my code:

public void StartUpdateTask(int delay)
{
    Task.Run(async () =>
    {
        const double FrameRatePerSeconds = 0.66666f;
        double previousTime = Environment.TickCount;

        while (true)
        {
            if (this._cancellationToken.IsCancellationRequested)
                break;

            double currentTime = Environment.TickCount;
            double deltaTime = currentTime - previousTime;
            previousTime = currentTime;

            this.GameTime = (deltaTime * FrameRatePerSeconds) / 1000f;

            lock (SyncRoot)
            {
                foreach (var entity in this.Entities)
                    Walk(entity);

                foreach (var mapLayer in this._layers)
                     mapLayer.Update();
            }

            await Task.Delay(delay, this._cancellationToken).ConfigureAwait(false);
        }
    }, this._cancellationToken);
}

mapLayer.Update() method:

public override void Update()
{
    this.GameTime = this.Parent.GameTime;

    foreach (var entity in this.Entities)
        Walk(entity);

    foreach (var region in this._regions)
    {
        if (region.IsActive && region is IMapRespawnRegion respawnRegion)
        {
            foreach (var entity in respawnRegion.Entities)
            {
                Walk(entity);
            }
        }
    }
}

And the calculation formula:

private void Walk(IMovableEntity entity)
{
    if (entity.MovableComponent.DestinationPosition.IsZero())
        return;

    if (entity.MovableComponent.DestinationPosition.IsInCircle(entity.Object.Position, 0.1f))
    {
        entity.MovableComponent.HasArrived = true;
        entity.MovableComponent.DestinationPosition.Reset();
    }
    else
    {
        entity.MovableComponent.HasArrived = false;
        double entitySpeed = entity.MovableComponent.Speed * entity.MovableComponent.SpeedFactor;
        double speed = ((entitySpeed * 100f) * entity.Context.GameTime);
        float distanceX = entity.MovableComponent.DestinationPosition.X - entity.Object.Position.X;
        float distanceZ = entity.MovableComponent.DestinationPosition.Z - entity.Object.Position.Z;
        double distance = Math.Sqrt(distanceX * distanceX + distanceZ * distanceZ);

        // Normalize
        double deltaX = distanceX / distance;
        double deltaZ = distanceZ / distance;
        double offsetX = deltaX * speed;
        double offsetZ = deltaZ * speed;

        if (Math.Abs(offsetX) > Math.Abs(distanceX))
            offsetX = distanceX;
        if (Math.Abs(offsetZ) > Math.Abs(distanceZ))
            offsetZ = distanceZ;

        entity.Object.Position.X += (float)offsetX;
        entity.Object.Position.Z += (float)offsetZ;
    }
}

With this current formula, my players and monsters arrive to destination between 1-2 seconds sooner on the server side compared to the client-side...
Do you have any idea what I'm doing wrong ? Appriciate if someone could guide me and explain me how to solve my problem. :-)

Thank you


texts:
I'm trying to make a pixel art game and my resolution is 384 x 224, but when I change to fullscreen the sprites looks blurry and I don't know how I can disable bilinear filtering.

I tried SamplerState.PointClamp on spriteBatch.Begin but it didn't work, I also tried this.GraphicsDevice.SamplerStates[0] = SamplerState.PointClamp and disable PreferMultiSampling but nothing works. Someone told me that it can be fixed using renderTargets, and I tried that by myself, but that didn't work either.

I used spriteBatch.GraphicsDevice.SetRenderTarget(renderTarget) and null at draw method but it still looks blurry. How do I use renderTarget? does it replace my sprite? Does it needs to be window scale or sprite scale? Help please

PD: I'm using FNA, but it seems to monogame. Is a reimplementation of XNA


texts: What problem does double or triple buffering solve in modern games?

texts:
I want to check if my understanding of the causes for using double (or triple) buffering is correct:

A monitor with 60Hz refresh's the monitor-display 60 times per second.
If the monitor refresh the monitor-display, he updates pixel for pixel and line for line.
The monitor requests the color values for the pixels from the video memory.

If I run now a game, then this game is constantly manipulating this video memory.

If this game don't use a buffer strategy (double buffering etc.) then the following problem can happen:

The monitor is now refreshing his monitor-display. At this moment the monitor had refreshed the first half monitor-display already. At the same time, the game had manipulated the video memory with new data. Now the monitor accesses for the second half monitor-display this new manipulated data from the video memory. The problems can be tearing or flickering.

Is my understanding of cases of using buffer strategy correct? Are there other reasons?


texts:
In Java slick2d , i started printing out Delta which is supposed to be the time and it prints out is 16 or 17  forever, so how does this help me if i want to tell an object when it needs to do something, example : IF (createdtime + 60miliseconds < delta )

60miliseconds after its creation , do something


texts: Wall collision and sweep and prune algorithm

texts:
I am documenting myself on collision detection algorithms.

If I understand well, "sweep and prune" algorithm using frame coherence is powerful to detect object vs object collisions (almost as 0(n)).

I am wondering if this algo is good for object vs wall collision ?

Suppose you have a big plane wall that is tilted regarding the axes of the "sweep and prune" algorithm (in a 3D game), because it is tilted the bounding box is quite big, and the wall bounding box will be detected as colliding a lot of objects. Similarly if a room is tilted regarding the axes of the algo (and the room is not a cube, but a complex geometry), then all walls collides almost all objects in the room, and the "sweep and prune" algo is useless for this problem.

A turnaround could be to split the wall in many little faces before the algo ?
Or are there other fast specific algos to detect object vs (big)wall collisions ?


texts: How can I access a script variable from another script in Unity?

texts:
I'm creating a space shooter (think Space Invaders or Galaga) where the GameManager persists between scenes but the player and enemies don't. I need to access a boolean value from the player and enemies to define when and how the game should end. The PlayerController script contains a playerDead variable (attached to the Player GameObject) to tell the GameManager if the player has died and a enemiesDead variable to tell if all enemies have died.

Because the GameManager persists but the others don't, it loses the references when a new level is loaded. I tried to have the GameManager find the script references dynamically, to no avail. It always errors with Object reference not set to an instance of an object when a new level is loaded.

I've tried to get them with GameObject.FindGameObjectWithTag() and then using GetComponent<ScriptName>() to get the script and the variable in it. It compiles nicely and everything seems dandy, but then there's still no object reference. Am I just doing it wrong?

So how can I reference a script and get a value from it without even touching the Inspector?

EDIT:

Below is some code (everything else except the essential is scrapped) from the GameManager script, I tried to use Object.FindObjectsOfType() like this:

GameObject player;
GameObject enemies;

void Awake()
    {
        DontDestroyOnLoad (gameObject);
    }

void Start ()
    {
        Reinitialize ();
    }

void Update ()
    {
        if (enemies.GetComponent<EnemyGrid>().enemiesDead == true)
        {
            gameEnd = true;
        }

        if (player.GetComponent<PlayerController>().playerDead == true)
        {
            gameEnd = true;
        }
    }

void Reinitialize()
    {
        player = Object.FindObjectOfType(typeof(PlayerController)) as GameObject;
        enemies = Object.FindObjectOfType (typeof(EnemyGrid)) as GameObject;
    }

But there's still no object reference. My intention was to run the Reinitialize() funtion each time a new scene was loaded, so that way the GameManager would grab the new objects each time.