texts: How to assign game objects to a script without dragging and dropping into inspector?

texts:
So I have a script for getting into a car which, when mouse down is detected on the given game object it will teleport the player to the car, turn of the player's controller,  and switch the player camera to the car camera.

The problem is I don't want to have to drag and drop the car game object, the player game object, and both cameras into the inspector for it to work.

Instead I would like it to have the script assign all those game objects based on the player who clicked on the car. Those game objects being the car the player, and the two cameras(one parented to the player and the other parented to the car). I have no clue how to go about this so I appreciate any help all the more.

Here is a picture of the inspector with the player script:

Also here is my C# code:

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

public class GetInCar : MonoBehaviour {
    public GameObject player;
    public GameObject car;
    public Camera CarCam;
    public Camera PlayerCam;

    void Start ()
    {
    }

    void OnMouseDown ()
    {
        if (Input.GetKey (KeyCode.Mouse0))
        {
            player.transform.position = car.transform.position;
            print("MovedToCar");
            GameObject.Find ("Player").GetComponent<CharacterController> ().enabled = false;
            PlayerCam.enabled = false;
            CarCam.enabled = true;
        }
    }
}


texts: UE4 Blueprint Multiplayer Spawning Issue

texts:
I'm attempting to copy/modify the MultiplayerShootout project's multiplayer functionality for my own project. I'm running into issues when Player 2 joins a running session though. Finding it very hard to debug multiplayer stuff because you have to run it in standalone and toggling breakpoints doesn't seem to be illustrating any issues.
Here's the issue:
https://youtu.be/270p4YS36Pw
The first player to search for a game hosts a game, then the OnPostLogin in the GameMode fires and calls the ClientPostLogin event in the PlayerController, then the PlayerController calls the RespawnPlayer event inside the GameMode which spawns and possesses the character. The second player finds a session and joins it, but the server is not spawning a character for them on the other PlayerStart.
The logic is very much similar to the MultiplayerShootout, but I have modified it in the following ways:
The 1v1 button searches for sessions, and if it can't find any it will automatically host a session.
The ClientPostLogin event on the PlayerController and the RespawnPlayer event on the GameMode accepts a Selected Character (Actor class) variable. This is so I can get the player to select their character before they matchmake and pass it through to the PlayerController and then GameMode for spawning purposes. Would really appreciate some help on this, been stuck on it for a while.
Here's some of the blueprint scripting to make sense of it:

OnPostLogin event in the GameMode

ClientPostLogin in the PlayerController

RespawnPlayer event in the GameMode

1v1 button released event in the PlayScreen Widget

HostGame event in the GameInstance

JoinGame event in the GameInstance
Edit: I'm using UEngine version 4.24.3


texts: I need help with 2D collision response (of stacking rotating polygons, with friction and gravity, for a game)

texts:
Hi I am looking for suggestions on how to write a collision response for game programming purpose (so not a scientific simulation). I am dealing with 2D polygons that are rotating, and I want them to be able to stack. I also want friction and gravity. I have a detection mechanism that returns the separating axis, how long the polygons are overlapping, and up to 2 points of contact. For the response, I am currently using an impulse-based response, which main idea is:

find the separating axis, length of overlap, and the point of contact (if there are two, pick a random point between to simulate averaged force. i believe there are better ways than this)
separate the object (modifying their positions, taking into account of their masses. i do not separate them completely though, to keep track that they are colliding to reduce jitter)
calculate normal force based on the coefficient of restitution as if there is no friction.
calculate friction, as if there is no normal force. I also assume that the direction of the friction is the same throughout the collision.
apply the two forces (which result in a rather inaccurate result, since each force is calculated as if the other is not present. for non-rotating bodies though, this method is exact)

I am aware that this method requires the coefficient of friction to be sufficiently small due to the assumption that the direction of friction stays the same in a collision.

Also, the result is visually satisfying if gravity is not present. However, when there is gravity, objects on ground jitter and drift (even with zero coefficient of restitution)! It also happens for stacking objects. Larger coefficient of restitution and gravity increase the jittering.

I hope you can help me with this. Some things i would like to know more about is how to handle collision with two point of contacts (how to end up having an object sitting still on the ground?), how to reduce, and prevent if possible, jitter and drift (do people use the most accurate method possible, or is there a trick to overcome this?), and how to handle multiple objects collision (for example, in the case of stacking objects, how do I check collisions between all of them and keep them all stable at every frame so they don't jitter?). A total reformulation of my algorithm is also welcomed, as long as it works. Another thing to note is that I am not making a Physics game, so I only need a visually satisfying response (though a realistic response is preferable, if it is not performance-heavy). But surely jittering and drifting objects on flat ground are not at all acceptable. In addition, I am a Physics student, so feel free to talk about impulse and whatever needed.

Finally, I'm sorry for the long post. I tried to be as concise as I can. Thank you for reading it!

EDIT

It seems what I didn't manage to come up all this time is to separate resting contact as a class of its own and how to solve them. Currently reading the paper suggested by Jedediah. More suggestions on the topic are welcome :)

CASE CLOSED

After reading various papers referenced in the paper, successfully implemented simultaneous impulse method (referring to the original paper by Erin Catto, [Catt05]). Thanks maaaan!! The paper is wonderful. The current system is visibly much better than the previous.

Still haven't separated resting contact as a class of its own though, which brings me to my next question. Love you all! Haha (sorry, I'm just so happy thanks to you).


texts: How can I make the object when rotating to keep looking on the character/camera?

texts:
Not to look the character/camera direction but to look to the character/camera.

This is a screenshot of the object I'm rotating. And this is the face of the object and he is look at the camera(Looking at me).

The object is a child of a Camera and the Camera is child of a RigidBodyFPSController (1)

In the top of the script:

public float rotationSpeed;
private float x;
private int damping = 2;

In Update:

void Update()
    {
        if (Input.GetKey(KeyCode.R))
        {
            x += Time.deltaTime * rotationSpeed;
            objectToScale.transform.rotation = Quaternion.Euler(0, 0, x);
        }
        var lookPos = transform.position - objectToScale.transform.position;
        lookPos.y = 0;
        var rotation = Quaternion.LookRotation(lookPos);
        objectToScale.transform.rotation = Quaternion.Slerp(objectToScale.transform.rotation, rotation, Time.deltaTime * damping);
    }

Now when I press on R the object name NAVI is rotating but when I move the MainCamera around the NAVI object is not facing to me.

This is a screenshot when running the game first time the object is facing to me:

But when I'm pressing on R and the object is rotating it looks like the object is facing to the left and I see the object side:

Then I move the camera to the right he is rotating like I wanted facing to me:

And if I move the camera to the left when the object is rotating I see the object back:

But I want that each time the object is rotating that he will be facing to me.

The last screenshot showing the Hierarchy the RigidBodyFPSController (1) and the MainCamera as child and the NAVI as child of the MainCamera.

The script Change Scale is attached to the MainCamera and with this I'm rotating the NAVI.

The main goal what I want is simple. When I press on R rotate the object and always make the object facing to me.

I tried now in the Update when pressing R to do:

if (Input.GetKey(KeyCode.R))
        {
            x += Time.deltaTime * rotationSpeed;
            objectToScale.transform.rotation = Quaternion.Euler(0, 0, x);
            objectToScale.transform.LookAt(Vector3.forward);
        }

But now it's not rotating at all.


texts:
I'm trying to learn the UI part of Unity and the use case I want to achieve is to setup a windowed user interface which looks like Unity or Blender's one (simplified): with one or more 3D views in it + some canvas with 2D GUI.

What I've tried so far is to make it using a canvas with an image in it, which itself has a raw image component. The raw image has a render texture as 'texture'.

But doing that, the texture is stretched when the rect transform of the image is changing. So I don't know how to handle that if the size and position of the view is changing (I've seen the minimap tutorials but here the size is static).

Another way could be to limit one or several main cameras 'viewport rect'.

But so far I don't know which is the best approach in order to set it up efficiently and have no difficulties to handle camera's movements, centered in the view, etc.

What is the good way to do that?

Edit: following the advice of DMGregory, it works perfectly

The idea is to update the camera's rect with something like this:

var anchorMin = parenRectTransform.anchorMin;
var anchorMax = parenRectTransform.anchorMax;

Camera.rect = new Rect( anchorMin, anchorMax - anchorMin );

Here parentRectTransform is the rect transform of the parent of my 3D view, so that the anchor's position and size are relative to the global space (screen).

The other approach using a render texture is not possible as its size cannot be changed at run time (the only possibility was to recreate one each time).


texts: Where should I put units and items in a squad-combat ECS-based game?

texts:
So I'm working on a game where squads of varied units would explore, fight, trade and build on an overworld map. Combat would be automated more or less, and happen on the overworld. Basically, something like Mount&Blade but without the real-time hack and slash combat.

I'm using an ECS architecture, and even in MVP stages I'm running into confusion: Should each unit be an entity in the grand entity pool, with an ID pointing to the squad it belongs to? Or should they be in an array of units in the squad entity?
When they start having items, should every dagger and boot be part of a gigantic entity pool, or only exist inside units and inventories?
When it'll come to skills and enchantments, buffs... will a "+10% damage" buff float among houses and squads and knives and forests in the entity pool, or will it be part of a buff array?
If it helps
I'm using Javascript with a homemade ECS, for fast and shareable iterations, and for learning purposes too.


texts:
This seems so simple but my searching as failed to find a good result.

The idea is that you can move in 360 degrees but you aren't faster when you move in a diagonal direction. I know how to do this with trig. The problem is I I want some physics so that if you are traveling north and start traveling south you first need to slow down to zero to go south. (And if going 270 deg to 30 deg it would be a more complicated.) The character has acceleration and a max speed.

I know that vectors are the solution but I can't find how to apply them the current speed to get smooth movement.

I'm doing this in GameMaker Studio 2, but pseudocode should suffice. Here's what I have.

var h,v;
h = key_to_axis(vk_right,vk_left);
v = key_to_axis(vk_down,vk_up);

var dir = point_direction(0,0,h,v)
spd = approach(spd,max_spd,accel);
x+= lengthdir_x(max_spd,dir);
y+= lengthdir_y(max_spd,dir);

Note that this movement is shared by characters that can move in the full 360 degrees.


texts:
I am trying to create a button for my game there are lots of similar buttons so using an image for each one is a bit inefficient. So I want to load an image then copy some text over it and render that to the screen. But it just doesn't render anything, it just gives me a transparent surface.

SDL_Texture* button = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA888, SDL_TEXTUREACCES_TARGET, 200, 50);
SDL_SetRenderTarget(renderer, button);

SDL_Texture* border = IMG_LoadTexture(renderer, "border.png");
SDL_Texture* text = SDL_CreateTextureFromSurface(renderer, TTF_RenderText_Blended(font, "new race", color));

SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, border, NULL, NULL);
SDL_RenderCopy(renderer, text, NULL, &text_centered);
SDL_SetRenderTarget(renderer, NULL);

Then I do some extra stuff and finally:

SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, background, NULL, NULL);
SDL_RenderCopy(renderer, button, NULL, &position);
SDL_RenderPresent(renderer);

But it just rendered the background not the button, that indicates that the textures I tried to render to button where not rendered and it is still just a blank texture. I already set SDL_RENDERER_TARGETTEXTURE but it just doesn't work.

UPDATE:

I found out that the problem was that the format and the access where passed in the wrong way, I corrected it and now when I compile there is an access violation, this is because I pass SDL_TEXTUREACCES_TARGET as the access argument, if I pass SDL_TEXTUREACCES_STATIC there is no such violation, the problem is that I can't use SDL_SetRenderTarget if it is static, it needs to be target (which causes an access violation error).


texts: How can I design a battle algorithm for my MMORTS?

texts:
So I am actually developing a MMORTS myself, and this is getting me stuck a bit. So lets say you have two opposing armies who just started their battle. How should the code determine who is the winner? Obviously you have to take into consideration such things as...

How many troops does the army have?
What level are the troops? (tier 1, tier 2, etc)
What buffs and bonuses do they have? (increased attack and defense through research perhaps)

There are more I could list but you get the idea. There is a bit of math involved of course. Calculating all the stats and incorporating any buffs. But how should the actual fighting work? I have tried finding out via research on google, but most games keep their battle algorithms close to the table. You have all of this input from the armies, and then you put them into these mysterious algorithms and the code spits out a result. I must be missing something. I have had small glimpses of ideas.

It is weird because you are not actually controlling some character with hitboxes and a weapon. You are commanding armies of NPC units that are physically controlled by AI. Which side should attack first? Should they attack each other at the same time? How do you incorporate troops with different damage amounts and health and defense? And what about support units?

How can I make this such a battle algorithm for my game?


texts: How can I make item interactable for action?

texts:
In this script when there is a detection I'm setting the flag detect to true and using in with other scripts. And using the clickForDescription flag and OnGui to display text description for each interactable item if there is a text for it.

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

public class DetectInteractable : MonoBehaviour
{
    public Camera cam;
    public float distanceToSee;
    public string objectHit;
    public bool interactableObject = false;
    public Transform parentToSearch;
    public static bool detected = false;

    private RaycastHit whatObjectHit;
    private bool clickForDescription = false;
    private bool clickForAction = false;
    private int layerMask = 1 << 8;

    private void Start()
    {

    }

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            clickForDescription = true;
            clickForAction = true;
        }

        Debug.DrawRay(cam.transform.position, cam.transform.forward * distanceToSee, Color.magenta);
        if (Physics.Raycast(cam.transform.position, cam.transform.forward, out whatObjectHit, distanceToSee, layerMask))
        {
            detected = true;
            objectHit = whatObjectHit.collider.gameObject.name;
            interactableObject = true;
            print("Hit ! " + whatObjectHit.collider.gameObject.name);
        }
        else
        {
            detected = false;
            clickForDescription = false;
            print("Not Hit !");
        }
    }

    private void OnGUI()
    {
        if (clickForDescription == true)
        {
            ProcessOnGUI(parentToSearch);
        }
    }

    void ProcessOnGUI(Transform parent, int level = 0)
    {
        foreach (Transform child in parent)
        {
            if (child.GetComponent<ItemInformation>() != null)
            {
                ItemInformation iteminformation = child.GetComponent<ItemInformation>();
                if (child.name == objectHit)
                {
                    var centeredStyle = GUI.skin.GetStyle("Label");
                    centeredStyle.alignment = TextAnchor.UpperCenter;
                    GUI.Box(new Rect(
                          Screen.width / 2 - 50 + 20 * level, // <== INDENTATION
                          Screen.height / 2 - 25, 100, 50),
                        iteminformation.description, centeredStyle);
                }
            }

            // Process next deeper level
            ProcessOnGUI(child, level + 1);
        }
    }

    public class ViewableObject : MonoBehaviour
    {
        public string displayText;
        public bool isInteractable;
    }
}

This is the ItemInformation:

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

public class ItemInformation : MonoBehaviour
{
    [TextArea]
    public string description;
}

Once object is tagged for Interactable and the ItemInformation is attached to it it will display some description for the item.

Now I want to do something for action. For example if the item is Interactable and a script name ItemAction is attached to it do some action, For example move the object from side to side or rotate the object. The logic should be like the Information. It's just with the Action there might be many options then just displaying text.

I'm not sure how to make some logic and how to work with the ItemAction.

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

public class ItemAction : MonoBehaviour
{

}


texts:
I'm making a game some like Terraria. I have a couple of prototypes, but most of them use a "entity-component-system"(ESC) and some custom terrain implementation. Now I've reached the part where I feel like researching some multiplayer-technology. So here I am.

This is what I have so far;
 * I want to write the server in python, I don't HAVE to but I like python because I feel that I can easily change logic, and the workings of it.

Know, my first question is; the ESC, should run on the server, right? But how do I sync entities and components between the client and the server?

When the client connects to the server, how do I sync the world? The world is randomly generated as it expands. Can someone explain or link some data about how the
server entity -> client entity is done? And how to sync the terrain?


texts: How can I handle shadowing of a planet's rings by the planet itself?

texts:
I assume the most straightforward way to draw planetary rings (such as those around Saturn) is to use a texture that is transparent everywhere except for the rings, and then place the planet in the middle of the texture and that's it.

The problem with this approach is that I don't know how to shadow the area of the rings texture that is behind the planet (which isn't lit by the sun). At the moment I have a rings texture that is permanently lit and a planet that darkens in the areas where it's not lit by the sun. The planet revolves around the sun, so the lit/shadowed areas are constantly changing.

Any suggestions on how to apply shadow on the rings?


texts: How can I simulate thousands of things at high frame-rates?

texts:
I'm working on a simulation game like SimTower where I'd like to keep track of thousands of items at once.

Other games like this, appear to have hundreds or thousands of rooms with elevators with what looks like hundreds or thousands of people. I'm concerned about achieving the same thing in my game.

How can I realistically keep track of each individual person/room/elevator in the game? I assume I can only render what's on the screen, but how can I afford to constantly simulate everything that is off the screen?


texts: Drawing Colored Geometry in OpenGL using SDL

texts:
First off, I will confess I have asked the same question on stackoverflow, but I think this forum might be a better fit.

I am trying to combine 2 things using SDL:

Draw a webcam feed via an SDL_Surface (from OpenCV).
Draw some plain colored geometry on top, using OpenGL.

The problem I have is that—I think—the geometry is textured by the screen texture that I draw the webcam feed in, even if I call glDisable(GL_TEXTURE_2D) right before drawing the quad. See the screenshot below, the square in the top-left is supposed to be white, but it seems to have the color of the bottom-right texel.

The code in my Display function is as follows:

// screen_surface_ contains a frame from the camera
SDL_UpdateTexture(screen_texture_, NULL, screen_surface_->pixels, screen_surface_->pitch);
SDL_RenderClear(renderer_);
SDL_RenderCopy(renderer_, screen_texture_, NULL, NULL);

glLoadIdentity();
glDisable(GL_TEXTURE_2D);
glColor3f(1.0, 1.0, 1.0);
glBegin( GL_QUADS );
  glVertex3f( 10.0f, 50.0f, 0.0f ); /* Top Left */
  glVertex3f( 50.0f, 50.0f, 0.0f ); /* Top Right */
  glVertex3f( 50.0f, 10.0f, 0.0f ); /* Bottom Right */
  glVertex3f( 10.0f, 10.0f, 0.0f ); /* Bottom Left */
glEnd( );

glColor3f(1.0, 1.0, 1.0);
SDL_RenderPresent(renderer_);

You can view all the code of relevant functions here.

I got a blanket answer saying "Don't mix SDL and OpenGL draw code"; as addressed in this bug report. But that would mean I'm simply stuck waiting for that bug to be fixed, so I'm still looking for a way to disable texturing after SDL_RenderCopy has been called.

Edit: I've confirmed that it's indeed still using the screen_texture_. Setting the texCoord to values between 0-100 shows a part of the webcam feed. (I tried 0-1 first but then I read that texCoords are different for rectangular images).


texts: How to make the game run at 60 FPS in Irrlicht?

texts:
I want my game run at 60 fps, but I don't know where to start, I have the simple loop:

while(device->run()){

How do I lock the frame rate to 60 FPS?


texts: What is the best way to turn image voting into a game?

texts:
I'm trying to come up with a design for an image voting site that turns the (potentially boring) task of voting on thousands of images into a game. The goal is to get the user to vote on as many image pairs as possible without them getting bored.

My first thought was to use to the different ip addresses of uploaded images and turn the voting into a world journey for the user. The site opens on a world map and is presented a series of image "battles" where they have to choose the winning image out of the pair. Each world region will have anywhere from 10-100 image pairs that the user will vote on. As they complete the image pairs for a region, they are "flown" to another part of the world to keep the game going.

The goal of the world map approach is to collect the user's opinion on as many image pairs as possible while giving them the sense of: 1- accomplishment (finishing the image pairs of a region) 2- going around the world

I unfortunately ran into a subtle flaw of this approach: Image pair voting will be restricted to particular region...so you can never have an image pair composed of an image from japan against an image from the US.

I was wondering how I could adapt this approach to fix this flaw - ie allow image pairs to be composed of images from all over the world instead of a particular region only?

Or even if you could come with a different design that accomplishes the same goals (collect as many votes as possible while keeping the user motivated and not bored)

Thanks for your time


texts: Elegant ways to handle rendering with DirectX 11

texts:
I'm looking for a design pattern that's going to help me to elegantly handle the rendering of my game objects.

Lots of game development guides talk about how to handle the game objects themselves, like monsters and characters and all that kind of thing. Nothing talks about linking all of that to DirectX. All the DirectX guides avoid good architecture in favour of getting something simplistic working.

The problem I am essentially having (that nobody seems to want to answer or give guidance on) is how to elegantly handle the COM objects that the DirectX 11 API gives us. I want to come up with a method of controlling how my COM objects are constructed and destructed, to protect my program from wanton destruction of these objects. I want them to be safely housed. The method of housing is consistently the stumbling block. I need the device and the device context in various parts of the program, but I want to avoid coupling every aspect of my program tightly to that.

I don't, for example, want a d3d "manager" object that I'm going to be passing all and sundry into with different methods for rendering the specific type of object I'm passing in. I don't want to have to be passing raw pointers to COM objects to every single method I create.

Ideally I don't want to be building a rigid, hard coded rendering pattern into my main() function or an equivalent Render() method of a cMain class.

I'm ok with how the COM objects interact together, all the interfacing with the DirectX API to achieve rendering. What I'm looking for is someone with experience of modelling a rendering engine, the bit that actually takes objects and renders them in a certain way and order based on a number of conditions. I'm looking for more generalised information on how I should go about designing the rendering element of my game to meet my needs.

My current solution, which includes:

class cMain {
public:
    cMain();
private:
    void Render();
    cD3D m_d3d; //<---- this class initializes and encapsulates all my d3d com objects
};

cMain::Render()
{
    float colour[4] = {0.2f, 0.4f, 1.0f, 1.0f};
    m_d3d.GetDevCon()->ClearRenderTargetView(&m_d3d.GetRenderTarget(), colour);
    m_d3d.GetSwapChain()->Present(0, 0);
}

And an entire philosophy built on that. Surely there's a more elegant way of designing it? I'm running the risk of coupling cD3D to everything using this method, or having all my render work in cMain, neither of which seem particularly sensible.

Alternatively, am I thinking about this too much? Is this the kind of thing that CAN go in my main class without sacrificing too much flexibility?

TL;DR - I'm having trouble wrapping my head around how I should approach building a rendering engine architecture that will accept all the different types of objects I want to render, including but not limited to game units, terrain objects, particles, etc.

I figure how I handle resource loading and access will be linked relatively tightly to how I handle the rendering process, and I want to get it right early on to minimize problems encountered at later stages.


texts: Is there a name for this kind of composited sprite animation technique?

texts:
Character avatars composed of different sprites for each component (arms, legs, head) connected together through a series of joints seem to be trending lately. For example,  Scrolls, Candy Crush (in the cutscenes) and the iOS Agricola game.

This system allows the characters to have movements without having to author each frame on a sprite and can look much smoother.

For example, see how the characters seem to breathe in this video? I've checked the game files, they are indeed composed of static parts, linked together through some kind of skeleton.

What is this technique called?


texts: How do I apply A* to a complex and dynamic 3D environment?

texts:
I've looked a bit at Breadth-First and Depth-First search algorithms and I think I've got a pretty good idea of how they work.

Now I am here : http://www.policyalmanac.org/games/aStarTutorial.htm

The problem is I don't see how a 2D grid can help with a 3D game. I suppose that wouldn't be a problem if the 3D game didn't have the AI explore multiple levels of a building, but since that is most often what occurs, I am not sure how I would "simplify" my static level geometry and my physics-dynamic changing scene into a structure that can be easily be traversed to determine a path to a goal node.


texts: How to disable script component while in game?

texts:
I'm trying to make a C# script to disable the First person controller script component for my character. I'm doing this so that while I'm controlling something else such as a vehicle, the only control script enabled at the time is the vehicle, and vice versa for when I'm not in the vehicle.

I did find a tutorial on the Unity Web site for Enabling and Disabling components but it uses a light component as an example, and I have no idea of how to do the same thing with a script component. I really appreciate any help I can get to solve this problem.

Thank you

This is the code in C# provided by the tutorial:

public class EnableComponents : MonoBehaviour
{
    private Light myLight;

    void Start ()
    {
        myLight = GetComponent<Light>();
    }

    void Update ()
    {
        if(Input.GetKeyUp(KeyCode.Space))
        {
            myLight.enabled = !myLight.enabled;
        }
    }
}


texts: How to resolve this problem with an object's collider?

texts:
In my game there is an obj_maze:

The width of the maze is 10 pixels in all its extension.

In the game, the goal is to get the obj_Cube through the maze.

obj_Cube:

The obj_Cube is wider than the maze on purpose, to get a pixel exceeding all sides as the object runs.

There are also obj_Tubes. They are responsible for defining what position the obj_Cube should go in the intersections that exist in the maze.

The obj_Tubes also have an extra pixel to stand out from the maze.

I made this whole explanation, to make it easier to understand my problem.

When obj_Cube collides with obj_TubeX, its new direction will be defined by what you can imagine.

It turns out that this is done wrongly, detection happens early in the collision, as expected.

Stirring in the bounding box, I was able to correct the problem.

By doing this I get the obj_Cube go right or left correctly.

Now and when the obj_Cube does not come from below, but from the right or from the left? This collision certainly did not happen properly.

Here is an example of the obj_Cube from the right, with the bounding box I used earlier:

The collision is neither detected.

Believe me, I've tested numerous bounding box possibilities for both obj_TubeX and obj_Cube, so that all cases are resolved, but it's physically impossible.

(At least the way I'm trying)...

I also thought about having three equal sprites from each tube with different bounding boxes, but that would be extremely harder and coarser, making my game weigh a lot more.

Sorry for the bad English, I'm not English speaker. I had to use google translator to translate everything.

Thank you in advance!!!


texts:
I'm developing a game in Slick2D and I'm trying to make GUI.

I've already tried TWL library, but it seems to me a bit complicated and it doesn't cover what I need. In my own implementation of GUI I've encountered a problem with positioning of components. That's why I'm interested in Swing. I would use only its layout system and I would render components on my own (in Slick render loop).

So I'm asking, is it good for performance to do so? May I encounter other problems with Swing?


texts: Stronger Hack-proof MMO Game Comparison: Game Client Based Vs. Via Web Browser

texts:
I was wondering. I observed most of any MMO that are hack-prone area. Hacks used one-hit kills, stealing accounts, instant level up, aimbots (mostly MMOFPS), and questionable wallers (also in MMOFPS). These hackers might affect the fairness and excitement of the gamers which lead to doubts, abuse kickers (mostly in MMOFPS*, and misunderstandings. Even in MMORPG referred to hacks for instant money for purchase items. I saw these examples via Wikipedia.

This leads me to my question:

Which kind of MMO game platform or model would be best for making MMO games whilst reducing the possibility of hacking?

For example I could make an MMO game for the web browser (by website or via Facebook) or making an MMO game using installers/clients that fetches for patches and graphics that could run only through program via computer. What will help with preventing hacking and how?

In the case of making an installer/client based MMO games, are there anti-hack programs or techniques you can recommend in MMO context?


texts: Can I sell games made with LibGdx on Steam

texts:
my question is pretty self-explanatory, there is any technical or legal issue in selling libgdx games on steam?

EDIT

It is possible to show some kind of evidence, maybe a exemple of a game that is made with libgdx and already is on steam?


texts: How does sound effects being in tune affect the game?

texts:
Many sound effects have a dominant frequency, especially for artificial sounds (UI, "powerups") and short effects that get repeated (machine guns). Whether by design or accident, these sound effects could be in tune with each other, or with the music.
My questions are, does this matter at all (in games), and if it does, what effects does this produce? When would one purposefully create harmonies, disonnances, or avoid such effects altogether?
In music theory, the effects of consonance/dissonance is well known, one of which is that notes in tune with each other are pleasant, and those that are not are unpleasant. But what about in games, does it matter that, for example, the laser gun you are shooting is in tune with the music?
At least a few well known games have harmonic sound effects, and although it may be deliberate, I'm not sure if it's a purely subjective/artistic choice, or whether it was designed to evoke specific feelings from the player. One notable example is Candy Crush Saga, whose match effects are all part of the same major key as the music: https://youtu.be/8TIeNDnJiN8?t=6m57s
Another example is Super Mario Bros, in particular the 1-up sound effect: https://youtu.be/w2NjUDfOp2o?t=22s although other powerup effects like the coin sound are not in the same key, for whatever reason.
At least one sound designer seems to think this is important:

Aaron Marks: I think I’m pretty much always in the ‘musical’ mindset when doing sound design, whether it’s recording, mixing and mastering or on a creative level. Music is definitely in my blood and I think, subconsciously at least, it’s always there when I’m doing any audio work. I definitely have some techniques where I ‘tune’ sound elements to be either pleasant or something a little more harsh. I also tend to pay attention to the music that is accompanying a scene or game level and often tune the sound effect to a note which blends well or I’ll go the opposite direction and detune it, especially for evil characters and their weapons, for example. You definitely want the audience to ‘feel’ the evilness and this is a great way to do it without being in their face about it.
In games especially, part of the goal is for all of the sound effects to feel natural to the game and not bring any undue attention to themselves. By doing this, the ones you want to really stand out will definitely be noticeable and have more impact. I’m always very careful for sounds like tractor beams, engines, humming machinery or ambience to tune them so they all work together and with the music.

Although this is just one opinion; I'd like to hear from those who have experience with professional game sound design to weigh in, is it something that sound designers generally worry about, and if so, when would one want to have sounds that are in tune, out of tune, and what the effects are.


texts: How to properly scale Image components to screen percentages?

texts:
Let's take a Sprite. I have two methods for retrieving an orthographic size of the screen:

public static float Width(){
    Camera cam = Camera.main;
    float height = 2f * cam.orthographicSize;
    float width = height * cam.aspect;
    return width;
}

public static float Height(){
    Camera cam = Camera.main;
    float height = 2f * cam.orthographicSize;
    return height;
}

Now, for the Sprite, I have an extension method:

public static void ScreenPercentWidth(this SpriteRenderer renderer, float percent){
    renderer.transform.localScale = new Vector3(
        Screen.Width() / 100f * percent / renderer.sprite.bounds.size.x,
        renderer.transform.localScale.y,
        renderer.transform.localScale.z
    );

}

Which I can use like sprite.ScreenPercentWidth(50f) and it works.

What about a RectTransform/Image? Is there any way that I could create similar methods, so I can scale the Image like in the above example?


texts: Pass a single boolean from an Android App to a libgdx game

texts:
I'm writing an Android application that needs to pass a single boolean into an Android game that I am also writing.  The idea is that the user does something in the App which will affect how the game operates.

This is tricky with LIBGDX since I need to get the bool value into the Java files of the game, but of course, you can't call Android specific things from within LIBGDX's main Java files.  I tried using an intent but of course the same problem persists.  I can get the boolean into the MainActivity.Java of the android output of the game, but can't pass it along any further since the android output and the main java files don't know about each other.  I have seen a few tutorials that explain how to use set up an interface in the LIBGDX java files that can call android things.  This seems like wild overkill for what I want to do.

I've been trying to use Android's Shared Preferences with LIBGDX's Gdx.app.getPreferences, but I can't make it work.

Anyhelp would be MUCH appreciated.

I've set up two hello world applications.  One is a standard Android app, with a single button that is supposed to write "true" into the shared preferences.  The other is a standard LIBGDX hello world that is supposed to do nothing but check that bool when launched and if true display one image to the screen, if false, display a different one.

Here's the relevant bit of the Android code:

import android.preference.PreferenceManager;

 public void onClick(View view) {
    if (view == this.boolButton){

        final String PREF_FILE_NAME = "myBool";
        SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_WORLD_WRITEABLE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean("myBool", true);
        editor.commit();
    }
}

And here's the relevant bit of the code from the LIBGDX main file:

Preferences prefs = Gdx.app.getPreferences("myBool");
    boolean switcher = prefs.getBoolean("myBool");

    if(switcher == true){
        texture = new Texture(Gdx.files.internal("data/worked512.png"));
        prefs.putBoolean("myBool", false);
        }
        else
        {
        texture = new Texture(Gdx.files.internal("data/libgdx.png"));
        }

Everything compiles fine, it just doesn't work.  I've spent HOURS googling trying to find a way to pass this single boolean from android into a LIBGDX main and I'm totally stumped.

Thanks for your help.


texts: How to determine that nodes in Grid Graph are unreachable before applying pathfinding?

texts:
I would like to determine accessibility of nodes before applying pathfinding algorithm to Grid Graph.

I have a surface with nodes overlayed on it and I would like to somehow determine that nodes inside yellow region are unreachable from outside of it (from behind the wall).


texts: I can load new tiles but how do I load new chunks?

texts:
I have successfully been able to add new tiles and place random trees on a 2d map grid however I haven't used chunks. I just load a new tile when the player moves and save it to the map array. But I have had some issues with the forests. And I'm thinking chunks would solve my problem. The problem is my forest just appears on the map when the player moves left or up. But I want to focus on how to handle the chunks because I know if I get that right I'll be able to solve the other symptoms to the main problem. Here is a link to the game.

https://76295db93db3812642fa5ba984c042fa81ffc37c.googledrive.com/host/0B6H3TRExU5M9eEkyd2FreHhiNlU/

Here is how I generate new tiles. This runs every game loop and not sure if that is the best way to do it. Does this cause lag? The bottom of the function checks if the tiles need to be updated to forest graphics. I know this is probably the wrong way to do it but I maybe if I get the chunk thing figured out I won't have these issues.

map.update = function() {
    for(var x = Math.floor(player.x - map.width / 2); x < Math.floor(player.x - map.width / 2) + map.width + 2; x++){
        for(var y = Math.floor(player.y - map.height / 2); y < Math.floor(player.y - map.height / 2) + map.height + 2; y++){
            //Surrounding tiles
            var tiles = [];
            //Check if tile needs to be generated
            var check = function(x, y) {
                if(typeof map.data[x] === 'undefined') {
                    map.data[x] = [];
                }
                if(typeof map.data[x][y] === 'undefined') {
                    map.data[x][y] = new Tile(x, y, map.generate.groundLayer(), map.generate.playerLayer(x, y), map.generate.aboveLayer(), map.generate.event());
                }
                //Add tile to collection
                tiles.push(map.data[x][y]);
            };
            //Center
            check(x, y);
            //Top
            check(x, y - 1);
            //Top Right
            check(x + 1, y - 1);
            //Right
            check(x + 1, y);
            //Bottom Right
            check(x + 1, y + 1);
            //Bottom
            check(x, y + 1);
            //Bottom Left
            check(x - 1, y + 1);
            //Left
            check(x - 1, y);
            //Top Left
            check(x - 1, y - 1);

            //Check if there is a forest
            /*
            if(map.data[x][y].playerLayer === sprite.forest.topLeftCorner) {
                tiles[3].playerLayer = sprite.forest.topRightCorner;
                tiles[4].playerLayer = sprite.forest.bottomRightCorner;
                tiles[5].playerLayer = sprite.forest.bottomLeftCorner;
            }
            */

        }
    }
};


texts: How to place an instance of Editor Window in screen center?

texts:
I want to create an instance of Editor Window by using CreateInstance or GetWindow. And I want to place it in center of the screen (or center of Unity).

I didn't find any methods in Unity Engine that could help me. Do they exist?

How can I do it within the script?

Note: I mean: how can I find out what is the user's screen resolution? Which method can give me that?

P.S. Screen.width/Screen.height - is not what I need. Because it refers to the Game View's window, not Unity.exe Editor's size and not monitor Screen


texts: How to run multiple Lua scripts within the same lua state without conflict

texts:
I've been working with Lua for sometime and there is a problem that I could never solve it. First, I'm using a single lua state to have a connection between my scripts so they could transfer data via global table _G.

My scripts have a template like this:

-- Vars
local somevar = 0

-- Update
function Update()
  -- stuff
end

I call Update() function from my application every game step, but since there are other scripts loaded in current lua state with the same template only the Update() function from the last chunk in lua is getting called and there is no way I can call all of Update() functions in my scripts.

If I load my scripts every time I want to call the functions, It'll work the way I want, but this way my local variables and every change that I have made to the scripts would get dumped because the chunk is replaced with a new one.

I've seen a message on Lua's site itself which talks about setting an environment for each chunk that is going to get loaded, but that's not what I want because it forces each script to reside in a unique table and there is no way to communicate with global table since we're going to override the global table for our unique tables.

I'd really appreciate if someone give me some advice because there isn't really much on the internet about these kinds of stuff.

UPDATE

I know the answer to first part of my question. Right now I'm using a table for each of my scripts, something like this:

code1.lua

code1 = {}

function code1.Update()
  -- Update
end

This makes every script accessible via the global table with their table name. The problem is if I load this script for another object in my game, then it'll conflict with the previously loaded script because they're both using the same source and therefore the same names and I can only access the last loaded. As you can see, I've stated this about environments in first part of my question.


texts: When does DirectX convert a vertex/pixel's depth from range Near-Far to 0-1?

texts:
When I output a vertex from a vertex shader, it seems to have a world-space-ish mapping. Vertices about 1 unit away have about 1 unit as their Z value.

When we input into the pixel shader, the depth values are mapped from 0..1 as defined in the viewport state.

Where does this conversion occur? It's late and I'm forgetful, but I can't find a place where I told DirectX what my depth range even was (other than implicitly in the projection matrix). How does it know how to convert it?


texts: Make a bullet shape around model in libgdx

texts:
How do I make a btBoxShape around a Model or ModelInstance in Libgdx?
This is my code:

modelInstance.calculateBoundingBox(boundingBox);
collisionShape = new btBoxShape(boundingBox.getDimensions(tempVector3).scl(.5f));

This works and creates a box of the right size but it is offset from the model. I cant figure out how to make it around the model and not offset.


texts:
My scenario:
RTS combat style, 1 unit fires beam on another unit

My problem is i want to draw a flat texture between 2 Vector3 points. I have looked at various Billboarding styles but that doesn't give me a proper solution.

I looked at this:
http://msdn.microsoft.com/en-us/library/bb464051.aspx

is BasicEffect and DrawPrimitives the correct solution just stretch the texture to the distance between point of origin to target? I used the quad class they used but i found this it seemed to inflexible

So my question to you is how would i go about this sort of problem?

Regards


texts: Relationship between Camera's view size, screen resolution and objects scale

texts:
I've had this question since a long time ago and wanted to know the relationship between how an object is viewed through the camera depending on the resolution of the device, the camera's view size and the object scale, so for example:

let's say i have a 100x100 square in the middle of the screen, the camera is looking directly at it and let's say the square takes 10% of a specific screen, if i wanted it to keep that relationship with the screen do i have to change the square size depending on the screen size?, change the camera's width and height? or change the resolution of the game?

in short, how does the resolution and the camera's widht and height affect the scale and proportions of the objects of the screen?


texts:
I need to know how to get the closest point on the surface of an ellipsoid to another point.

I had an idea, but apparently i was wrong, and oversimplfying.

What i did was squash the ellipsoid and point into local space, so the ellispoid is a unit circle

vector3 pointLocalCoord = ( pointOriginal - ellipsoid.origin ) / ellipsoid.radii

Then from there, the closest point should be 1, in the  direction of the transformed point from the origin

vector3 closestPointOnEllipsoidLocal = norm ( pointLocalCoord )

Then get back into standard space

vector3 closestPointOnEllipsoidWorld = closestPointOnEllipsoidLocal * ellipsoid.radius + ellipsoid.origin

But of course, all of this seems not to work, i was curious if any body could point me in the direction of some pre-existing code or such; as some of the articles i've tried reading kinda go a bit out of my scope of knowledge.

Also, if that seems right to you, please do tell. I'm pretty sure its wrong though.

Edit: Sorry for the unresponsiveness with this and my other question. They're different, i was axperimenting with something else


texts: How to position/transform vertices for 2D UI in shaders?

texts:
I am building a 3D engine and have a rendering abstraction that focuses on writing shaders. Most my 3D shaders have gl_Position output like:

gl_Position = projection * view * model * vec4(position, 1);

I would like to draw some 2D UI on top of all the 3D draw calls. I am having a hard time understanding how to do this.

Let's say I wanted to draw a HUD player life bar that is fixed to the bottom left corner of the screen. I can imagine drawing a quad. and maybe applying a texture to it. I would have 4 vertices for the quad to feed to the shader. How would I change the gl_Position calculation to handle drawing only to 2D screen space? Would I update the transformation to only apply the projection matrix?

gl_Position = projection * vec4(position, 0, 1);

How to determine the local coordinates of the quad verts? When the screen scales or resolution varies, How to ensure the quad stays positioned to the lower bottom screen? How to ensure the quad dimensions stay the same ratio?


texts: ShaderBytecode Compiler one technique multiple passes

texts:
I have an effect code with a basic structure like

technique TechniqueName {
    pass FirstPass {
        Profile = fx_4_0
        VertexShader = RenderFirstVS
        GeometryShader = null
        PixelShader = RenderFirstPS
    }
    pass SecondPass {
        Profile = fx_4_0
        VetrexShader = RenderSecondVS
        GeometryShader = null
        PixelShader = RenderSecondPS
    }
    pass ThirdPass {
        Profile = fx_4_0
        VertexShader = RenderThirdVS
        GeometryShader = null
        PixelShader = RenderThirdPS
    }
}

Now I tried to compile this with

using (BinaryReader reader = new BinaryReader(stream)) {
    CompilationResult result = ShaderBytecode.Compile(reader.ReadBytes((int)stream.Length), "fx_4_0");
    if (result.HasErrors) {
        throw new Exception(result.Message, new Exception(result.ResultCode.ToString()));
    }
    Data = result.Bytecode.Data;
}

stream is new MemoryStream(Encoding.Default.GetBytes(effectContent)).
The Data-Property (byte[]) is about 1 KiB large but if I try to load it via

context.InputAssembler.InputLayout = new InputLayout(device, effect.Data, someElements)

it crashes with following exception D3D11 ERROR: ID3D11Device::CreateInputLayout: Input Signature in bytecode could not be parsed.  Data may be corrupt or in an unrecognizable format. [ STATE_CREATION ERROR #161: CREATEINPUTLAYOUT_UNPARSEABLEINPUTSIGNATURE]

Any idea how I can fix this or why the error is thrown? I do not want to use multiple shaders because I reuse many parameters I do not want to reassign in a deferred shading setup.


texts:
I wish to have the shader effect as in the game 'The stack' by ketchapp

https://play.google.com/store/apps/details?id=com.ketchapp.stack&hl=en

As you can see, the color of the objects as well as the skybox keep changing.

I'm completely c# noob and trying my best to find  shaders to replicate the effect. But I can't find anything.

How can I change the color of an object at runtime?


texts:
I have made an algorithm for procedurally generating a 2D tile map in Unity.

The player can use the mouse to pan the view and look at the map.

My intention was that when the player reaches one of the sides of the map, he would simply see the other side as if he was going around the Earth so to speak.

The only way I have achieved this is by simply instantly setting the camera's position to the other side of the map when the player crosses one of the edges. The problem with this is that the player never actually sees the "border" connection continuously and that bothers me since I took the care to generate the map in such a way that connecting the east/west edges makes sense.

How can I achieve the desired effect?


texts: Implementing my own UI sprite class in Unity using shaders: where and how to position the sprites

texts:
For learning purposes, I am trying to implement my own UI classes in Unity "from scratch", in the GPU using shaders. I mean, I am trying to use simple 2D sprites either positioned via shaders or created within the geometry shaders. These sprites should be, of course, displayed above all else.

I know how to create or translate the sprites within the shader. However, I am struggling with a couple of conceptual issues:

1) where exactly, relative to the camera (or to the near frustum plane), should the UI sprites be positioned? I man, thinking of the Z axis as being the camera.forward, what is the correct default distance to display the sprites at (assuming that at that location, the sprite texture would be the closes to its correct 100% zoom scale).

2) for the correct positioning+rotation, would it just be the case of, every frame, calculating in the shader such correct world position of the sprite in relation to the camera/near frustum plane, and then making the sprite rotate towards the camera? Or is there a better way of doing that, i.e. disregarding world position at all and going directly for the screen position of the sprites within the shaders, since the final step of shaders is to paint the pixels in screen-space?

Thanks for your suggestions!


texts:
I'm looking into scripting languages to embed in my game.

I've always assumed Lua was the best choice, but I've read some recent news about embedding V8 as was considering using it instead.

My question is two fold:

Does anyone with experience embedding v8 (or another javascript engine) recommend it?

How does it compare with embedding Lua?

I like that v8 has a c++ embedding API.  However Lua API has had lots of time to be refined (newer isn't always better and all that).

Note: At this point I'm not too concerned with which is better language or which library has better performance.  I'm only asking about ease of embedding.


texts:
I want to make a 360 degree video of my OpenGL game.

Concerning the rendering: Is it enough to render it in OpenGL with a specific projection matrix? If yes, which one? Or can I render it into a cube map, and then encode it? (Which will require much more rendering power and be more complicated, which I want to avoid)

And how do I encode a 360 degree video with FFMPEG?


texts: How to implement Vector3.MoveTowards follow with random movement

texts:
I want to implement an AI behavior where an enemy runs towards the player while sidestepping randomly and aggressively (like in this video: https://www.youtube.com/watch?v=35Ut_C4eL40)
Currently I am just using Vector3.MoveTowards but that results in smooth movement which isn't exactly what I need. I've tried adding an offset to the target using Random.insideUnitCircle but it just doesn't work.
If anyone could give me an algorithm to implement it'll be great. Thanks


texts: Using keyword [NonSerialized] causes Property to disappear from Inspector

texts:
I have the following class to represent items in an inventory:

[System.Serializable]
public class InventoryItemInfo : MonoBehaviour
{
    public int Row = 0;
    public int Col = 0;
    public int Rotation = 0;
    public InventoryItemType ItemType;
    public int Amount;
    public int EffectiveWidth = 0;
    public int EffectiveHeight = 0;

    public int Width = 0;
    public int Height = 0;

    public bool Selected = false;
    public Vector3 TilePosAccordingToCurrentRotation;
    public Vector3 TileScaleAccordingToCurrentRotation;

    [NonSerialized]
    public Transform TheNicelyPositionedMesh;

    [HideInInspector]
    private int _iCurRow = 0;
    private int _iCurCol = 0;
    private int _iRotationToCheckForDirtyness = -1;

    public Vector3 DefaultRotation;

    public bool Initited = false;

    public bool Dirty = true;
    private bool _bInitialRotationGotten = false;
    (...)

With the keyword [NonSerialized], the property "TheNicelyPositionedMesh" disappears from the Unity Inspector.

I don't see why. Why is that keyword coupled with the visibility in the Inspector?

Thank you!


texts:
So I have some Hitboxes set up on 2 classes, HealthPickup and Player.

public static Rectangle Hitbox;

public override void Initialize()
{
    Hitbox = new Rectangle(Pos.X, Pos.Y, 32, 32);
}

That's just general code, there are other things in the classes too. So what I want to know is why this doesn't work:

// This is in the HealthPickup class' Update function.
if (Hitbox.Intersects(Player.Hitbox))
{
    Console.Beep();
}

Doesn't work if I put it in the main update function either. Am I missing something?


texts: How to make a gameObject Transform Position move in a circle while making its Transform Position move forward?

texts:
// I'm using Unity2D =)

 // I'm trying to move the Transform.Position in a circle pattern and also move it forward.
 // I'm not trying to move transform.rotation at all just the transform.position.

 // This one moves in a circle pattern but unfortunately shakes violently which I don't want.
 // Also it does not move forward which I do want it to do.

 // Most importantly, I don't want it to immediately move on Start. I want it to move after something is true. When I put it on FixedUpdate it moved too quickly.

 // Thank you for any help! =)

     void Start()
     {
         StartCoroutine(MoveCircularly());
         StartCoroutine(MoveForward());
     }

     IEnumerator MoveForward()
     {
         while ( condition )
         {
             g.transform.Translate(Vector2.right);
             yield return new WaitForEndOfFrame();
         }
     }

     IEnumerator MoveCircularly()
     {
         while ( condition )
         {
             //move in a circle
             yield return new WaitForEndOfFrame();
         }
     }


texts: Game engine like Unity 3D that allow me to use .NET code

texts:
I've been looking at Unity 3D for developing a 3D PC game and I really like the scene editor and how it simplifies the process of constructing 3D scenes, managing assets, animations, transitions etc. However, I don't want to restrict myself to using the Unity 3D scripts for handling every bit of game logic in the game.

E.g. If I want to construct a RPG dialogue system I don't want to do it with unity 3d scripts - I'd like to use C#/.net. Also, I might want to use e.g. windows azure and sql azure as backend, and use 3rd party .net libraries such as reactive-extensions etc.

Is there a .net engine out there that helps me with asset loading, animations, physics, transitions, etc. with a scene editor, but allow me to plug it into a visual studio .net project?

Thanks


texts: How to clip game objects to a rectangular area

texts:
I'm trying to figure out how to do this but am coming up short. I'm making a slot machine in unity 2d and would like to clip the tile prefabs when they leave a given rectangular area.

I can't seem to figure out how to do this. All of the references I've found say to use a clipping shader with a mask texture, but it seems like massive overkill to use a masking texture when I just need an easy pre-defined rectangular area.


texts: How to get object to lose less velocity as its speed increases

texts:
I'm developing a game in Flash and I need a little help. It can be considered a math problem.

My object is flying with speed X and my object can collide with stones. When it collides with a stone, I need my object to break the stone and continue, but with less velocity.
It's easy to hard-code it and write something like: myVelocity -= 10;, but my main problem is that I want it to lose less velocity the higher the initial velocity is.

For example: If the velocity is 300 I want it to lose 10 and if it was 200 I want it to lose 20.

Can this be done with some kind of formula?


texts:
I've been trying to develop a multiplayer turn based game which is mostly free to play - I just want to see if the game idea is appreciated - hence I want to do it with minimal cost and I'm confused which one of these to use: red5, zendamf, BlazeDS or Cirrus.

Red5 seemed the best option for me initially but getting a media server to host seems to be quite expensive. Same reason why I couldn't use Electroserver - cost. Both are very attractive options though.

ZendAMF then looked a feasible option since it supported remoting. But how do I let the other players get updates on actions of one player through zendAMF, which as far as I know does not do data push. I'll have to do it by polling - asking server constantly for updates - which wont look very real time.

Then I heard about BlazeDS which does support data push. Now I have to learn java if I want to use that and get a new web host because my existing host does not have tomcat.

Then I heard about cirrus which is still in 'codename cirrus' stage. It looks like a very feasible option since its peer to peer with miniamal server support needed. Is it good for a mutiplayer game?

Well if anyone has experience developing multiplayer flash games I'd like to know if a turn based multiplayer game with more than two players participating can be implemented using zendamf. ZendAMF because I know PHP and AS3.


texts: How can I find an agent that would help me get my foot into the door of a publisher?

texts:
I have submitted my game for review at couple of game publishers with zero response.

My game is very specific and unusual, so maybe I need to find very specific publisher, or maybe it hasn't been noticed in the sea of submissions, maybe the game is not worth publishing. In any case, I need to know for sure which reasons it is and I need to try all the options available before giving up.

Therefore I've been looking for a professional who knows how and where to try these options, but I'm at a loss on what would be the process to find such a person.

What would be the process to find such an agent?


texts:
I am currently trying to get the Depth Buffer as a texture to use it for edge detection algorithms. Since XNA4 does not allow direct access to the Depth Buffer as texture i have to render it into a texture. The effect i currently use looks like this:

float4x4 World;
float4x4 View;
float4x4 Projection;

struct DEPTH_VS_OUTPUT
{
    float4 Position : POSITION;
    float2 Depth : TEXCOORD;
};

DEPTH_VS_OUTPUT DepthTextureVS(float4 Position : POSITION)
{
    DEPTH_VS_OUTPUT output;

    float4 worldPosition = mul(Position, World);
    float4 viewPosition = mul(worldPosition, View);
    output.Position = mul(viewPosition, Projection);
    output.Depth = output.Position.zw;

    return output;
}

float4 DepthTexturePS(DEPTH_VS_OUTPUT input) : COLOR0
{
    float4 result;
    result.rgb = input.Depth.x / input.Depth.y;
    result.a = 1.0;
    return result;
}

technique DepthTextureRender
{
    pass P0
    {
        CullMode = NONE;
        ZEnable = TRUE;
        ZWriteEnable = TRUE;
        AlphaBlendEnable = FALSE;

        VertexShader = compile vs_2_0 DepthTextureVS();
        PixelShader = compile ps_2_0 DepthTexturePS();
    }
}

It looks like this:

The cubes in this scene are 1x1x1 the projection matrix is made like this:

var projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, 16f / 9f, 0.1f, 1000f);

As far as I understood the Depth Buffer concept z/w should give me the distance from the camera position to the pixel as value between 0-1 where 0 would be the Near-plane and 1 the Far-plane but since the cubes in this scene are only about 5 Units away they shouldn't be  white.


texts: what are texcoord tags in mesh.xml file in Ogrexml format?

texts:
I exported a 3d model from blender 2.79 and using ogrexml import/export plugin.
but the texture will crash and UV map not working in that format.
I made the model by four parts head-body-hands-shoes and they have 4 material and 4 textures, so I made a texture atlas for it and join them in a mesh to More optimization.
I think removing other UV maps has a problem because when I check the model.mesh.xml in a note editor and every vertex has 3 texture coordinate tags and I compared it with a normal correct model that looks good in the blender and in ogrexml format, it has one texcoord tag inside of vertex tag.
1-what are texcoord tags? are they using for UV maps in ogrexml format?
2-how can I clear blend files from other unused uvMaps to avoid exporting them with the model?


texts: How to rotate a surface in pygame, without changing its shape

texts:
I'm writing a class in pygame to create a sprite object, and I'd like to be able to rotate it. It works fine with an image, and rotates without issue. But when rotating a surface with a plain colour, the box appears to grow and shrink. I know that this is a result of the surface changing size to fit the vertices of the rectangle inside, but how do I stop it? I'd like to see a visual rotation.

I've created some sample code to show the problem that I'm facing, running it causes the box to simply change in size.

import sys, pygame
from pygame.locals import *

pygame.init()
SCREEN = pygame.display.set_mode((200, 200))
CLOCK  = pygame.time.Clock()

surface = pygame.Surface((50 , 50))
surface.fill((0, 0, 0))
rotated_surface = surface
rect = surface.get_rect()
angle = 0

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    SCREEN.fill((255, 255, 255))
    angle += 5
    rotated_surface = pygame.transform.rotate(surface, angle)
    rect = rotated_surface.get_rect(center = (100, 100))
    SCREEN.blit(rotated_surface, (rect.x, rect.y))

    pygame.display.update()
    CLOCK.tick(30)

How do I fix this issue, to make the surface rotate how I want?

Any help would be appreciated!


texts: How can we modify all of the human bone items in Skyrim?

texts: I have the models, but I am wondering which object_id I need to modify. Is there a single object_id for every skeleton part, or each parts have several variants and several object_id? Is there a list with all of the skeleton parts in the game thereby allowing me to modify all of the vanilla models without having to worry about not having changed all of the skeleton models in the game?


texts: Designing a game that allows for selectable perks/customization

texts:
Call of Duty games all have the core functionality of any FPS (walking around, killing, dying and repeat). Layered on top are various stuff. Of interest to me is during pre-game when you pick your perks. These perks can have very different effects and targets. Some affect walking speed and persist throughout the game, others are only activated at certain events and last for a certain duration. I am wondering what sort of design architecture/pattern would allow such a system that supports a wide variety of perks that have little in common.

For instance, imagine I want to add a perk that speeds up the rate of fire:

Do I make all my gun classes take as a constructor argument 'rateOfFire'? but then I will need to expand the code for each perk that affects the gun and the constructor gets bloated.

Maybe have it as a setter property on each gun? but then I can also bloat properties and make code insecure since I don't want anyone except the appropriate perks to change that property. I will also have to go back exposing more properties for each new perk. In addition, other classes that depend on this value might have already been initialized after the gun was created and acted upon the original 'rateOfFire' value before I get to change it.

and so on... and to further complexity, now imagine I want to add a new perk 'walk faster for 5 seconds after you die 5 consecutive times without killing anyone(death streak)'. This perk has nothing in common with the 'rateOfFire' perk.

And also there is the issue of how to deliver those chosen perks to their targets? I was thinking of the visitor pattern, but it seems inefficient since a perk that affects only certain guns will be passed to all game components that are customizable(level manager/presenter/physics and so on). And I will also need to expose their properties so that the perk can change them once visited.

I thought of other solutions that might work, but they all seem either too complex/over engineered. I am wondering how the Call of Duty developers might have implemented what seems to be a flexible and extensible perk system (many sequels).

Any suggestions are welcome.

Note am not remaking COD, instead I am making a simple mobile puzzle game but the perk problem is similar.


texts:
I just have a few months of OpenGL experience, just starting to get the hang of it.

I find geometry/vertex/fragment shaders to be very powerful. You have a few parameters that translates into a complex representation. One layer of your program can compute these parameters, the "model" only, and sharers can do the "view" part. That gives you a good separation of concerns and a lot of flexibility.

It's a pity that OpenGL ES 2 doesn't have geometry shaders. I think the CPU could totally take over this part in case the GPU doesn't support it and if proper shim libraries were present.

Is there any library that helps unfolding a model into vertexes / vertex attribute parameters / uniques, etc? Maybe one that uses the language of the geometry shaders?


texts: HTML5 - Dynamic canvas grid for scrolling a big map

texts:
I've been working on different scrolling algorithms for my JS-based game. My main problem is that I need to draw a huge map and also have it scroll smoothly. I've made a few attempts and while they're efficient (code and framerate wise) they still look jumpy and have to redraw constantly (though not each frame, it's still too much redrawing for my taste).

My latest idea is to implement some kind of 3x3 grid around the camera which will scroll with delay. What do I mean "with delay" ? well, if you have played Diablo II before, try to get a Maphack app and enable the Automap Screen Area feature: You see, Diablo II's map is made through a concept of "rooms" and those adjacent to the player in a specific area (usually screen size) are drawn offscreen to allow the scrolling.

I want to implement that in an orthogonal perspective (this is, 2D zelda-like), just like this:

The blue grid is made out of canvases around my camera's position. I know I can position them with the simple x+(floor(camera.x / tile_size) * tile_size) formula and with some offsets have them move around the camera like this:

THE PROBLEM arises when the drawn offscreen areas must remain in the same position to allow the scrolling. I've made a second image which illustrates this:

Notice how the colored tiles (or offscreen areas of screen size) remain in the same position UNTIL they get "too far" from the camera (the red dot). HOWEVER, while they have the same position, notice the Tile # (below each blue grid tile) change. I can't do it that way because it would require to redraw, and my goal is to avoid such redraw if the position hasn't changed.

This means however, that, taking in example blue tile 6 (located at 0,1 at the first animation frame) it changes to tile 5 and then to tile 1. While this is true, the idea is to keep it at tile 6, and only re-use the farthest canvases in the closest ones that need to be redrawn.

I'm illustrating my problem this way because my previous question didn't even get a single comment ( https://stackoverflow.com/questions/22185858/infinite-scroll-a-canvas-with-a-tiled-map-without-redrawing/22277681 ) so I had to work and answer my own question... something that doesn't even help either because someone else might have had a better idea, but nobody did, it seems.

That's why I'm asing here in gamedev, maybe here are some more skilled people who can have an idea or a shot at what I'm attempting to do. Also, please, I'm not interested in using other game or JS engines. If I were I wouldn't be asking this here as I know they implement tile scrolling and such, but this is both for my own learning and for creating a custom engine suited for my own game's needs.

Any help then, is really welcome.

Thanks in advance!
- DARKGuy

EDIT: Well alright, after struggling for like 2 days straight on this issue I finally managed to do it. I didn't want to do it with this kind of coords, so I wonder is there any way to optimize this code or to avoid it to do those increments and instead use a formula that would absolutely position them?

Here's the code I'm using (cv = canvas, cx = context("2d"), grid = 3x3 array of canvases. Also, I'm using a 32x32 "grid" just to see how it works. The size should be screen size (or region size, in my engine's case)):

for(ix = 0; ix < grid.length; ix++)
for(iy = 0; iy < grid.length; iy++) {
    cv = grid[iy][ix];
    if(cam.x - cv.x > 48)
        cv.x += 32 * 3;
    if(cam.x - cv.x < -48)
        cv.x -= 32 * 3;
    if(cam.y - cv.y > 48)
        cv.y += 32 * 3;
    if(cam.y - cv.y <- 48)
        cv.y -= 32 * 3;
    cx.fillStyle = cv.color;
    cx.fillRect(cv.x, cv.y, 32, 32);
}


texts: What should I watch out for in a 3d artist's portfolio?

texts:
I'm looking to hire a freelancer to help with 3d modeling. I've thought up a few qualifiers so far:

Is their topology okay for animation?
Have they demonstrated the technical capabilities necessary for my project? (Have they baked normals, AO maps, etc.)
Have they shown an ability to execute from conceptual drawings?

Are there any massively important things I should watch out for that I haven't included?

Any red flags I should be aware of, like making sure the work isn't plagiarized?

Note

I'm specifically talking about reviewing portfolio content, before interviewing them. I'm looking for things I can say yes or no to, or that I might want to question them on further in an interview.


texts:
At the position z = 0 my box has size on one side 0.2. When, for example, I move it to z = 1.5,  size of it scale up. I've trided to calculate it by using triangle formula z*tan(fov/2), but it does not really work.

Do you know how to get size of one side after primitive moved on z axis ?

(All about in opengl)


texts: Conservation of energy of a bouncy ball in Unity3d

texts:
My problem is that in the project I have a ball with a physicMaterial where:

Dynamic Friction and Static Friction both are 0
Bounciness = 1
Friction Combine is set to Multiply
Bounce Combine is set to Maximum

This ball has a rigid body attached in which:

mass = 1
drag  and angular drag both are 0
useGravity = true

There are some cubes which create a boundary for the ball to bounce inside.
The ball bounces in a closed boundary. The problem is overtime its top velocity keeps on increasing and after sometime it gets out of the boundary.

I want the velocity of this ball to NOT exceed a provided maxVelocity. Here i am sharing my project through google drive  bounceProblem.unitypackage


texts: Unity - Pixels, Units, Sprites and Pixels per unit - Setting a relationship between sprites and screen size

texts:
I don't get how units and pixels work in Unity. For instance:

Here I have a camera with size 5. This means that there are 5 units from the center of the camera to either the top or bottom border. This means too that the total height of the camera are 10 units.

At the same time we have a "Display 1" set to 1920x1080. If the height of the screen in pixels is 1080, and there are 10 units, this would mean that every unity will be 108 pixels, right?

On the other hand, if I set the resolution of "Display 1" to 2560x1440, this would mean that every unit would draw 144 pixels, right?

Now, I have my sprite, a 35x37 pixels image.

Since I want my game to be a pixel art, I want the pixels to be more prominent. To do this, I would like to upscale it 4 times, meaning that instead of 35x37, I want to draw 140x148 pixels, right?

But if I go to the settings of my sprite, I find the following settings:

There is a field calles "pixels per unit". Which means that I have to manually the calculation between the resolution of my display and the size of my camera. So in this case set the "Pixels per unit" to 108.

But then, if I want to allow to have different resolutions in my game, say 1440p, this means that the "Pixels per unit" for my sprite must be 144, instead of 108. Since this setting is not automatic, and cannot be changed on runtime (I think), does this mean that I have to duplicate the same sprite and set every file with different PPU, depending on all the resolutions I want to support, and then in runtime select the appropiate sprite? Because that doesn't seem right.

Is there some concept I am not properly grasping about Units and Pixels?


texts: How to combine dynamic asset reload and texture atlases? (rectangle packing with removal)

texts:
Usually texture atlases are built either:

as a seperate content pre-processing step
or once when the game starts

What I want to do is create and update atlases on the fly when:

A new texture file appears on the disk (or when a file gets removed)
Pixel data and/or size of the texture changes (file gets changed)

As a seperate use-case - it's also useful when all assets can't be loaded in memory at once:

Different subsets of textures are used within different levels (yet are not set in stone as player can bring new assets from another level, or find a random drop which introduces a new texture from a vast library).

There a wealth of information on texture-packing algorithms in a all at once scenarios.

What algorithms are there for packing atlases dynamically (add/remove/resize texture)?

What rectangle packing with removal algorithms are there?

Textures of arbitrary size
Multiple power-of-two bins
Both adding and removing has to be fast and online
Removal operation should NOT trigger repacking of the whole atlas. Moving an occupied rectangle or two is acceptable (but better avoided?).


texts: atan2 : inversed result? (angle 180 is on the right side, angle 0 on the left side)

texts:
the result of the angle between my touch and the middle,bottom of the screen gives me 180 when the touch is on the right side of the screen, and 0 when it is on the left. I don't understand why...

override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
    let refPoint = CGPointMake(self.frame.size.width/2, self.frame.size.height)
    let anyTouch: UITouch = touches.anyObject() as UITouch
    let touch = anyTouch.locationInView(self.view!)

    //180 is inversed? 180 is when touch is on the right side...
    let dy = (refPoint.y - touch.y) //opposite
    let dx = (refPoint.x - touch.x) //adjacent

    let rad = atan2(dy, dx)
    let angle = rad * 180 / CGFloat(M_PI)
    println("angle : \(angle) ")
}

Would someone know how to solve this?

Thanks


texts:
I'm developing a simple NPC controller that the player can talk with.

At the moment a NPCController script on the NPC gameobject manages several "high level" feature of the NPC such as intelligence.

Every time the player talks with the NPC, the latter will respond with "Bzz", "Hello" or "Heya" depending on his intelligence level.

The talking part is implemented in a TalkController script. I did this way in order to have multiple behaviours depending on the player/npc interaction without creating a giant NPCController class. Plus some NPC may not speak at all (in this case I'd simply remove the TalkController).

I have a small dilemma on how to change the NPC response in TalkController based on the intelligence level in NPCController.

I could use Events:

// NPCController.cs

public delegate void OnIntelligenceLevelHandler(int level);
public static event OnIntelligenceLevelHandler OnIntelligenceLevelChanged;

// When intelligence increases
OnIntelligenceLevelChanged(2);

and:

// TalkController.cs

// Store _intelligence = 1;
// Subscribe to OnIntelligenceLevelChanged
// Upgrade _intelligence when the event fires
// Switch word on _intelligence when talking

I could use a direct reference:

// TalkController.cs

// Store _npccontroller = GetComponent<NPCController>();
// Switch word on _npccontroller.Intelligence when talking

What would be the best approach?


texts: How to make a Multicast Delegates in Blueprint?

texts:
I used the Set Timer by Event, but I could not use the delegate in more than one event:

I've been researching about and it's possible, but I've only found results in c ++:

https://docs.unrealengine.com/en-US/Programming/UnrealArchitecture/Delegates/index.html

My code:

This is not at all functional. I'm using the same function twice.

I could call the "second" event after the execution of the "first" event, but I would like to know a way (if any) to use the delegate in more than one event.


texts: How can I handle position in an entity system where position can be 2D or 3D?

texts:
I'm working on a game engine to learn how it's done (so I might better take advantage of the techniques involved and other, similar engines in the future), and I've run into a problem when handling position when it should be able to be either 2D or 3D.

Since the physics updating the position must also affect the rendering of the graphical components' positions, I need to hold the position of the entity itself separately. Since it is used by most systems anyway, it is fine to break the purity of the design for this bit.

However, I can't decide a default position component type as the engine is meant to have both 2D and 3D capabilities. I know Unity has both 2D and 3D systems and uses a similar Entity-Component system, and there may be other engines that have a similar setup. How is it determined what type of position component to use in those systems? Or rather, what would be the best way to handle this sort of conflict (in terms of simplicity and memory)?

I'm using C++ with a little bit of inheritance with the components, where every component has an update method that is defined per component that does any sort of batching or default updating behavior (e.g. the SpriteComponent class's update will send the necessary data to the SpriteBatcher). However, the Entity class simply stores them all in a std::unordered_map<std::string, Component*> and iterates through them, calling their update methods.

Edit: I should mention I'm using GLM for my vector types, mostly out of convenience and to keep everything consistent with OpenGL (which I'm using for rendering). Since some functions are defined for 2D but not 3D and vice versa, I can't just use a 3D vector for 2D operations without constructing a new, temporary 2D vector from the 3D vector, which is inconvenient for various reasons (memory usage, construction time, not saving state correctly or having to convert data to save state, etc).


texts: Getting the Halo property of a point light in Unity

texts:
I am adding point lights in my scene ( max 6 ) and I want to be able to enable its Halo property via script. However in the documentation reference, they haven't mentioned how to enable the halo property of a light source via script.

This is what I have so far.

GameObject lightObj = new GameObject("Light");
lightObj.AddComponent<Light>();
lightObj.light.color = Color.blue;
lightObj.transform.position = city.transform.position + new Vector3(-6.0f,0,0);

Point Lights have a property "Draw Halo" on the Inspector but how do I enable it via script?


texts:
Although I did this a couple of times from scratch, still no solution really fits.

I'm using lua for scripting in my games. Lua holds the "prototypes" of the game elements, that are copied to each entity on it's creation. A prototype represents a class of objects ("Soldier with shotgun"). Also, each prototype may hold event hooks (OnDie, OnSpotEnemy, etc). Clearly it's a prototype, not the object that will be handled.

So, each time a hook is executed, I need to create an object to represent the calling entity (and any entities it interacts with) only for the lifetime of a single script execution. What it means is that a instance of the object lives in lua only for the time needed to run this script.

Simple execution of this idea wasn't much work -- I used lightuserdata to hold the C++ pointer to the entity encapsuled in a being class. To access the fields of the C++ object, I overloaded the metatable of being. However, the fact that the fields of the object are handled by a metatable practically breaks any reasonable implementation of inheritance.

I pondered with the usage of normal userdata, but I'm afraid that the dynamic allocation needed to run each script (some of them being ran each tick in the game loop) are going to ruin performance.

Any suggestions? Or maybe a better solution altogether?


texts: How do I construct the planes for my camera's frustum?

texts:
I'm trying to get a handle on frustum culling, but I'm not quite there yet.

I have a camera in three-dimensional space

Camera
    position (cx, cy, cz)
    rotation (tx, ty, tz)
    fieldofview
    near-plane
    far-plane

and a quadtree containing my chunks of terrain

Quadtree
    Chunk
        bottomleft (x, y)
        width
        length
        heightmap

Currently, I am rendering every chunk within the quadtree. However, I would like to cull all chunks outside the six planes of the camera's frustum.

I am unsure how to:

Generate these planes given the information in the camera class.
Efficiently test for intersection using my quadtree. If one region of the quadtree fails, do all of its children (that seems reasonable, I just want to make sure)? What is the process for running through a quadtree for culling?
Perform the intersection test using the planes and my terrain chunks. How do I quickly tell if a piece of terrain (square with varying y values) lies within the 6 camera planes?


texts: Unity problem with instantiated objects when destroyed

texts:
So this is my problem, I have a square that when destroyed spawn 4 smaller squares when shooting on it, but when I shoot one of the 4 smaller squares sometimes a different square that are not even close gets destroyed.
The problem is worse when it has multiple smaller squares because just shooting one of the squares continuously make the other ones get destroy except the one i'm shooting


texts:
I have created an image with the resolution of 25px(width)*34px(height) (I know it's unusual, however it doesn't bother me now). The problem is that when I try to display it by creating a bitmap, it becomes really really small on my Galaxy S4. It should look a little pixelated, kinda like a flappy bird sprite. I checked those sprites as well and they are even smaller in comparison to mine however it is displayed much bigger than my sprite on the screen. I want to know if I can make it look larger without scaling it. Is there a way to make my sprite look bigger?

@Override
protected void onDraw(Canvas canvas) {
    Log.i(TAG, "onDraw called");
    BitmapFactory.Options op = new BitmapFactory.Options();
    op.inPreferredConfig = Bitmap.Config.ALPHA_8;
    bm.setDensity(DisplayMetrics.DENSITY_DEFAULT);
    bm = Bitmap.createBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.giraffe_default,op));
    canvas.drawBitmap(bm,getWidth()/2,getHeight()/2,null);  //get from res, set coords to 10,10
}

This is my onDraw method where I draw my canvas and bitmap. As I said, my image appears to be so small, I can barely see it.


texts:
I'm rigging up a man in 3DS Max 2012, but I'm having some envelope problems. I have this man, but I can't ever seem to catch those nodes along his inner thigh so they protrude, as you can see in the picture.

I've tried adjusting the numbers in Radial Scale, Parent Overlap, Child Overlap, Strength, and Falloff, and even the Exclude command to exclude the other limb but all with no success.

How can I somehow make these stray thigh vertexes conform into their thigh envelope?


texts:
I am attempting to learn Unity Networking using the new UNET framework. I have a functioning rudimentary 3rd person setup in which a host and a client can connect to localhost:7777. Animations are working across both client and host. However, some of the animations are not smooth. I am using the ThirdPersonAnimationController and the Ethan model that come with Unity. The animations from running to turning left or right and from running to stopping are quite jittery. However, they are not jittery when viewing the screen in which the controls are being input.

I am using the NetworkManager and my Player prefab has a NetworkAnimator.
I'm calling my movements in the Update function of my Player script:

void Update()
{
    param = anim.parameters;
    if (!isLocalPlayer)
        return;

    float move = Input.GetAxis("Vertical");
    anim.SetFloat("Forward", move);

    float moveTurn = Input.GetAxis("Horizontal");
    anim.SetFloat("Turn", moveTurn);

    Camera.main.transform.position = new Vector3(transform.position.x, 2, transform.position.z - 2.5f);

}

public override void PreStartClient()
{
    GetComponent<NetworkAnimator>().SetParameterAutoSend(0, true);
    GetComponent<NetworkAnimator>().SetParameterAutoSend(1, true);
    GetComponent<NetworkAnimator>().SetParameterAutoSend(4, true);
}

public override void OnStartLocalPlayer()
{
    // good for initializing things only for the local player: cameras, input, etc...
    GetComponent<NetworkAnimator>().SetParameterAutoSend(0, true);
    GetComponent<NetworkAnimator>().SetParameterAutoSend(1, true);
    GetComponent<NetworkAnimator>().SetParameterAutoSend(4, true);

}

Is there a way to improve the animation across the network? Any suggestions would be very helpful. Thanks.


texts: Customising character appearance though textures

texts:
At the moment I am contemplating adding character customisation to my game, however I am unsure what approaches are available when it comes to using textures/decals to add facial features (like facial hair, hairstyle, scars/blemishes etc).

The character in question is stylised with a cel shader like effect.

So what are some approaches to take? Should I be using shaders to blend textures together by having the normal diffuse texture and then a mask texture to add facial hair or are there better more efficient results to achieve what I want?

Would another possibility be to use a shader and then bake the resultant blended texture to a new diffuse texture and use that?

To clarify, the customisation will be through textures only and not through adding/changing meshes


texts: Improving shading of procedurally generated pixel art sprites

texts:
I've been working on a sprite generator and I'm having a hard time figuring out how to add shading automatically.

Here are some examples of the generated sprites

Currently what I'm doing is checking where a flat color meets a dark boundary, and then applying either a highlight or a shadow depending on the direction.

This is of course really boring. I've tried searching for other methods, but all I could find were AI examples. Does anyone know of any particularity simple yet clever ways of adding shading automatically?

I've thought of expanding the check up to 5 cells, and using a set of pre-determined patterns to generate the shading, but I'm just not too sure


texts: How to make a motorcycle running on a vertical circular track(loop-da-loop) without falling down due to gravity?

texts:
I am currently developing a game, motorcycle type game. Of course, my map is not just made up of simple line or curve. For example: a vertical circular track in the map. i've seen most 2D motorcycle games have this design.

How do you prevent the motorcycle from falling off the vertical circular track by correlating the motorcycle's forward speed? If the forward speed is 0, it will fall down naturally, because this is the physical essence, but if the speed is fast enough, it should firmly grasp the track and not fall down. so how to exert force on it to counteracting gravity? what's math behind it?
looking forward to your reply,i really appreciate it, thank you!


texts: I cant Instantiate a particle system for the duration of a subroutine

texts:
I have a sub routine that lowers the timescale to 0.3 for 2 seconds. while in those two seconds i would like to spawn a trail of particles that follow the player.

I can get the particles working if I attach them to the player in the editor but I'm having trouble spawning them at the start of the time slow down.
The slow down subroutine works fine its just the particles that i cant spawn.

Thanks, any help is appreciated.

public GameObject particles;
public Transform playerParticles;
// Start is called before the first frame update
void Start()
{
    slowDownActivateNoise = GetComponent<AudioSource>();
}

void Update()
{
    if (hasCollided)
    {
        if (!activated)
        {
            StartCoroutine("SlowDownActive");
        }
    }
}

public IEnumerator SlowDownActive()
{

    Debug.Log("subroutine Start");
    activated = true;
    Instantiate(particles, playerParticles.position, playerParticles.rotation);

    Time.timeScale = 0.3f;
    GetComponent<Collider>().enabled = false;

    yield return new WaitForSeconds(2);

    GetComponent<Collider>().enabled = true;
    Time.timeScale = 1.0f;
    hasCollided = false;
    activated = false;
    Debug.Log("subroutine end");

}


texts: Implementing monte-carlo tree search in a tile based game with units

texts:
I have this simple risk-like game I would like to develop an AI for. Players move their Units on the  map and a simple fight resolution is done. There is a time constraint of 100ms for each round, the AI has complete information and fight resolution is deterministic but units move simultaneously each round.

As far as I understand the monte carlo approach, I need to copy the state of a current round and generate a tree with new game states, play it out randomly or do an evaluation.

Currently my zones keeps a list each unit and they're moved around by storing orders. They're kept in a dictionary for each turn and are applied at the end of the round. Deep copying this takes around 3ms and I guess is too slow to use effectively considering the time constraint. I was wondering if I could use this order-system to generate the tree faster by applying and undoing them, but I can't yet wrap my head around how I would do it.

This is my current class design:

How can I effectively add MCTS for this kind of game?


texts: Prevent weapon from clipping during animations

texts:
I am trying my ways with Unity 3d animations, and so far so good.

The only problem is, when I equip an weapon in the player model's hand, the weapon clip through player's head during some frames of some animations. Please refer to the gif and the screenshot below for an example.

Here you can see that the top of the bow is clipping through the player head during the arrow fire animation.

Here you can see a demonstration gif of the problem.

I've been thinking and I will probably need to adjust the weapon rotation/position so it fits the animations, right?


texts: Composition and passing pointers to parent, or work inside namespaces

texts:
My application right now has a Game class, which contains other classes that receive a Game pointer. Also these classes passes the Game* pointer to their subclasses. I do this to keep communication between objects. Is this a bad way to keep all communicated? This looks like a "god object" antipattern.

The only alternative I've found to avoid this is simply instanciate my objects globally, inside namespaces, like they did int his project https://github.com/thelaui/M.A.R.S. . But this also looks as an antipattern, where almost everything is global.

What is then the correct way to design a program where the objects keep communicated?

Or the objects shouldn't keep communicated? Which looks hard to make a game.


texts: Meshes exported from blender as .obj does not map correctly

texts:
I am having some problems with developing my game in OpenGL with java (Using LWJGL3). I have been following a guide for the more complex steps of the process, like loading meshes.

When using the basic mesh of a cube that was provided by the guide it works as it should, so it seems like it is not my software that is the problem? The problem comes when I attempted to create my own models using blender. I made sure to triangulate faces and include normals when exporting, but for some reason even when I created a simple cube it does not work correctly. The textures get smeared, only one face is intact. I have both tried the automatic UV projection, and making my own seams.

I have been stuck on this for a while and I have no idea where I am doing something wrong. I would greatly appreciate some help.


texts:
So, I have code to create a quaternion from a matrix (using the 3x3 rotational part.)

And I have code to construct a transformation matrix from a lookat + up vector pair.

To go from lookat+up to quaternion, I can thus go via the matrix intermediary:

vec3 lookat;
vec3 up;
...
mat44 trf = mat44::create_basis( lookup, up );
quat ori = quat::from_matrix( trf );

So far, so good.

But can I do this without the matrix intermediary?
Because it seems to inefficient. For starters, both the lookat+up and the quaternion are a lot more concise than the intermediate matrix. It goes from compact to large, to the most compact.

How can I create a quaternion using just a look-at vector and an up-vector, both of which are guaranteed to be unit length and perpendicular to each other.