texts: How do I load Player position as new gameobject?

texts:
I want to make game-like time travel, the player has the ability to go to the future by limited time, for that, I want to add some game mechanic like save the player position.

Additional information: ignore the red text.
When pressing the button the player will create a new platform and immediately teleport to the original position. After the player teleported, the player will save the new platform as the new teleport position. after 2 seconds or pressing a button. the new platform will disappear and the player will return to the platform position.
I have this _playerController Script and I already implement the save position, but I don't know how to make it like what I explain.
    public Rigidbody2D theRB;
    public float speedMovement;
    public GameObject prefabGameObject;

    [Space(10)]
    private BoxCollider2D boxCollider2D;
    [SerializeField] private LayerMask GroundMask;
    public float jumpVelocity;

    [Space(10)]
    public float past;
    public float future;

    [Space(10)]
    public float hor;

    // Start is called before the first frame update
    void Start()
    {
        theRB = gameObject.GetComponent<Rigidbody2D>();
        boxCollider2D = transform.GetComponent<BoxCollider2D>();
    }

    // Update is called once per frame
    void Update()
    {
        PlayerPosSaveLoad();
        PlayerMovement();
        PlayerJump();
    }

    public void PlayerMovement()
    {
        hor = Input.GetAxis("Horizontal");
        if (hor > 0 || hor < 0)
        {
            theRB.velocity = new Vector2(hor * speedMovement * Time.deltaTime, theRB.velocity.y);
            if (hor > 0)
            {
                transform.localScale = new Vector2(1f, transform.localScale.y);
                //Animation
                Debug.Log("ToTheright");
            }
            else
            {
                transform.localScale = new Vector2(-1f, transform.localScale.y);
                //Animation
                Debug.Log("ToTheLeft");
            }
        }
    }

    public void PlayerJump()
    {
        //animation
        if (isGrounded() && Input.GetKeyDown(KeyCode.Space))
        {
            theRB.velocity = Vector2.up * jumpVelocity;
        }
    }

    public bool isGrounded()
    {
        float extraHeighText = .1f;
        RaycastHit2D raycast2d = Physics2D.BoxCast(boxCollider2D.bounds.center, boxCollider2D.bounds.size, 0f, Vector2.down, boxCollider2D.bounds.extents.y + extraHeighText, GroundMask);
        Color raycolor;

        if (raycast2d.collider != null)
        {
            raycolor = Color.green;
        }
        else
        {
            raycolor = Color.red;
        }
        Debug.DrawRay(boxCollider2D.bounds.center, Vector2.down * (boxCollider2D.bounds.extents.y + extraHeighText), raycolor);
        return raycast2d.collider != null;
    }

    [SerializeField]
    private Vector2 saveThisPosition;

    public void PlayerPosSaveLoad()
    {
        if (Input.GetKeyDown(KeyCode.E))
        {
            saveThisPosition = transform.position;
            SpawnGameObject();
        }
        if (Input.GetKeyDown(KeyCode.Q))
        {
            SwitchWithsavedPosition();
            Destroy(prefabGameObject);
        }
    }

    private void SwitchWithsavedPosition()
    {
        Vector2 temp = transform.position;
        transform.position = saveThisPosition;
        prefabGameObject.transform.position = temp;
    }

    public void SpawnGameObject()
    {
        Instantiate(prefabGameObject, transform.position, transform.rotation);
    }

And this is the Camera Script because connected with the player.

```lang-cs
    public Transform Player;

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

    // Update is called once per frame
    void Update()
    {
        transform.position = new Vector3(Mathf.Clamp(Player.position.x, -7.3f, 7.3f), Mathf.Clamp(Player.position.y, 1f, 2f), transform.position.z);
    }


texts: What revenue cuts will I take by using Unity combined with Facebook's platform?

texts:
Basically me and a friend want to develop a Facebook game by using Unity. What I wanted to know is if we do earn any money on it, how would we be required to use the profits of said money? I remember reading that Unity requires you to pay royalty (or something like that) after having earned a certain amount of money from your product.

What confuses me is where Facebook would enter the equation? I can't seem to find any sources on royalty on such from FB-based games.

Does anyone have any sources covering FB-games made in Unity on how it all comes together?


texts:
How do I create a ToggleButton via code? I tried using ButtonGroup. Using a CheckBox works, but TextButton does not:

...
CheckBox checkBox = new CheckBox("one", skin);
CheckBox checkBox2 = new CheckBox("two", skin);
CheckBox checkBox3 = new CheckBox("three", skin);

ButtonGroup buttonGroup = new ButtonGroup(checkBox, checkBox2, checkBox3);
...

...
TextButton playButton = new TextButton("one", skin);
TextButton playButton2 = new TextButton("two", skin);
TextButton playButton3 = new TextButton("three", skin);

ButtonGroup buttonGroup = new ButtonGroup(playButton, playButton2, playButton3);

I found this example, but I still can not adjust the background:

TextButtonStyle textButtonStyle = new TextButtonStyle();
textButtonStyle.font = someBitmapFont;
textButtonStyle.fontColor = Color.WHITE;
textButtonStyle.downFontColor = Color.BLACK;
//Optional color to toggle between when pressed
textButtonStyle.checkedFontColor = Color.GREEN;
final TextButton textButton = new TextButton("Text", textButtonStyle);
final TextButton textButton2 = new TextButton("Text", textButtonStyle);
final TextButton textButton3 = new TextButton("Text", textButtonStyle);

ButtonGroup buttonGroup = new ButtonGroup(textButton, textButton2,textButton3);

On the left is what I am left with; on the right is what I want.

Here is my current code:

com.badlogic.gdx.scenes.scene2d.ui.Button$ButtonStyle: {
    default: { down: default-round-down, up: default-round },
    toggle: { down: default-round-down, checked: default-round-down, up: default-round }
},

com.badlogic.gdx.scenes.scene2d.ui.TextButton$TextButtonStyle: {
    default: {
        down: default-round-down, up: default-round, font: default-font, fontColor: white
    },
    toggle: {
        down: default-round-down, up: default-round, checked: default-round-down,
            font: default-font, fontColor: white, downFontColor: red
    }
},


texts: What is a cheap (better free) way to make multiplayer in a shooter?

texts:
I'm a newbie indie, so I don't have a budget for a game. But I'm making a 3rd person shooter and I need multiplayer for it.
It's a mech shooter, so it won't have very fast movements, meaning I don't need fast sync between participants.

I've thought about peer-to-peer, it seems good, but what if the host's PC crashes or they just kill the game? It would be the end of the whole match!
So it seems like I need to have some sort of centralised server, but do I really need a dedicated server, and even a number of servers to be able to host thousands of matches? Or can I sync it through database services like playfab somehow?


texts: Godot - Get button node in click event not working

texts:
How we can get the button reference on the event function that is connected?
My connect signals never works

extends PanelContainer

onready var hbox_container = $ScrollContainer/HBoxContainer
var btn

func _ready():
    createbutton()

func createbutton():
    btn = Button.new()
    btn.set_name("button 1")
    btn.text = "button 1"
    hbox_container.add_child(btn)
    btn.connect("toggled", self, "button_toggled", [btn])

func button_toggled(toggled, target):
    print("which button = ", target.get_name())
    if toggled == true:
        print("Button ist pressed")
    else:
        print("Button is released")


texts: Animating two characters (like a fighting game) whose animations are tied together?

texts:
So, say one character grabs another and throws him against a wall. Are these two separate animations that get attached to each character? Or is this really one animation that somehow involves each character model to itself?
I'm using the Unity game engine.


texts: Building a touch event driven UI from scratch: what algorithms or data types?

texts:
I have a touch display. As input I can receive the coordinates and how many touch points are in use, basically I just get an X,Y couple for every touch event/activated point at a customizable rate.

I need to start from this and build my own callback system to achieve something like Object.onUp().doSomething() meaning that I would like to abstract just the detection of some particular movements and not having to deal with raw data: what algorithms can be useful in this case? What statements? Is there some C++ library that I can dissect to get some useful info?

Would you suggest the use of an heuristic algorithm?


texts: What is the difference between a bonus and a power-up?

texts:
What is the difference between the notions of "bonus" and "power-up?"

I have in-game some objects and the player has the ability to pick up some bonuses/power-ups that allow the player to create an explosion all around. There's also an item that lets the player teleport from one place to another -- are these all power-ups?


texts: Do shader program compilers optimise divide-by-PoT-constants to bitshift operations?

texts:
So just to restate that, let's say we have this:

float f = g / 2;

Given the divisor is a constant, will the shader compiler auto-optimise this to a bitshift operation, as some language compilers are known to do? Where would I find more info on shader program compiler implementation details?

(I'm guessing there will be different answers for OpenGL & DirectX.)


texts: What is the price to license EA's GlassBox game engine?

texts: "SimCity 5" is powered by the GlassBox engine. If we want to use the engine for building our own simulations, what is the price for a license?


texts: Passing elapsed time to the update function from the game loop

texts:
I want to pass the time elapsed to the update() method as this would make easy to implement the animations and time related concepts.

Here's my game-loop.

public void gameLoop(){
    boolean running = true;

    long gameTime = getCurrentTime();

    long elapsedTime = 0;
    long lastUpdateTime = 0;

    int loops;

    while (running){

        loops = 0;

        while(getCurrentTime()>gameTime && loops<Global.MAX_FRAMESKIP){
            elapsedTime = getCurrentTime() - lastUpdateTime;
            lastUpdateTime = getCurrentTime();

            update(elapsedTime);

            gameTime += SKIP_STEPS;
            loops++;
        }

        displayGame();
    }
}

getCurrentTime() method

public long getCurrentTime(){
    return (System.nanoTime()/1000000);
}

update() method

long time = 0;

public void update(long elapsedTime){
    time += elapsedTime;
    if (time>=1000){
        System.out.println("A second elapsed");
        time -= 1000;
    }
}

But this is printing the message for 3 seconds.

Thanks.


texts:
I made a game in Unity with admob  integration, and I published it on the Google Play store.
After 2 days I got a mail from the Play store mentioning a policy violation (reproduced below). I l researched the issue and updated a privacy policy document on my app, then resubmitted the game.
It came went live, but then I got the same mail from the Play store again and they removed it.
From the beginning onwards my ads are also not showing in game, but the test ad is working fine.
Can you tell me what mistake I made and how I can fix it?
Message from Google:

Notification from Google Play about Green Puzzle Truck
Google Play Support
Hi developers at **** **** Studio,
After review, "my game name" , package name, has been removed from
Google Play due to a policy violation. This app won’t be available to
users until you submit a compliant update.
Issue: Violation of Usage of Android Advertising ID policy and section
4.8 of the Developer Distribution Agreement
Google Play requires developers to provide a valid privacy policy when
the app requests or handles sensitive user or device information.
We’ve identified that your app collects and transmits the Android
advertising identifier, which is subject to a privacy policy
requirement. If your app collects the Android advertising ID, you must
provide a valid privacy policy in both the designated field in the
Play Console, and from within the app.
Next steps: Submit your app for another review
Read through the Usage of Android Advertising ID and User
Data policies, as well as the Developer Distribution Agreement, and
make appropriate changes to your app. If you decide to collect
sensitive user information, be sure to abide by the above policies,
and include a link to a valid privacy policy on your app's store
listing page and within your app.
Make sure that your app is compliant with all other Developer Program
Policies. Additional enforcement could occur if there are further
policy violations.
Sign in to your Play Console and submit the update to your app.
Alternatively, you may opt-out of this requirement by removing any
requests for sensitive permissions or user data.
If approved, your app will again be available with all installs,
ratings, and reviews intact.
If you’ve reviewed the policy and feel this removal may have been in
error, please reach out to our policy support team. One of my
colleagues will get back to you within 2 business days.
Thanks for helping us provide a clear and transparent experience for
Google Play users.
Regards,
The Google Play Team


texts: What approach would you take to develop an old school game?

texts:
Possible duplicate: What technology should I use for a web-based game?

I have agreed to show my child how to develop software. He wants me to help him develop a game.

If you were me then what approach would you take to develop an old school game?

I was thinking about an old school game that you can pick up and play them straight away, where there is no "learning curve". This is because we prefer playing these types of games. On top of that I want to be able to say things like "I made the game engine, the AI, he did the scoring system and .. and .. and ..".

I intend to run it in a browser, to target a broad range of platforms. I was thinking to use mainly C# and Silverlight.

So, if you were me then what approach would you take to develop an old school game?

EDIT

Could I use XNA? Is it free? Does it plug into Visual Studio 2010?


texts: XNA/MonoGame and Game Studio/MonoDevelop

texts:
First off, I have a bit of programming experience in Java and have always programmed using ViM (even though I recently moved to Sublime Text 2) and I'm trying to learn C# and the MonoGame framework. My question is whether or not I REALLY need MonoDevelop.

So, do I really need Visual Studio/MonoDevelop to develop games in C# and MonoGame?


texts: Intellisence doesn't show the ECS API Summaries

texts:
I am not sure if this is more of an ECS topic problem or packages in general. but it would be really helpful for ECS programming with all the summaries the Unity has provided. For unity engine methods, intelligence show me descriptions and summary of classes and methods, but it doesn't work on packages I guess.

I have tested this with all IDEs, AutoComplete doesn't show the description for methods and classes. However, I can go to the declaration of packages source code and see the summary. for example, Below you can see a screenshot in the Jetbrain Rider IDE, as you see when I mouse over OnCreate method it doesn't show the description.


texts: Andengine Traffic game: moving sprites along path on map

texts:
I'm developing simple traffic educational game, like "Allianz Křižovatky". When the player taps on a car sprite, it should start to move with the other cars. If the player made a mistake in choosing a car, a collision happens.

I decided to use AndEngine for this game, because I have time limitations in developing it. How do I make the car automatically move along a specified path, with smooth turns? How would I specify this path on a map?


texts: How to get the point of collision in Separating Axis Theorem?

texts: I'm interested in the relatively precise point (not line) of collision for calculating angular velocity on impact for use in a impulse calculation. At first I thought, perhaps naively, that I could use the closest point along the shortest overlapping axis, but closest to what exactly?


texts: XNA 2D: How to load/unload specific content by level

texts:
I'm writing a 2D room-based* platformer using XNA, and I'm trying to figure out the best way to load resources based on what the current map requires. Basically, I need to (want to) dispose of the loaded tileset/textures and load just the ones the next map requests at every transition (ideally, I'll check if they're actually different first), without killing off the more universal textures (player sprites, etc.).

I've seen a few forum posts saying the best way to do this is to create a second instance of ContentManager, but they never go into detail on how to do this correctly.

Currently, my XML map files each contain strings with the filenames of all necessary assets. I was planning on having my XmlReader method load the textures as their names were read, but then I realized I knew neither how to instantiate the second ContentManager, nor where to instantiate it--i.e., should it be in the MapFactory class that's loading the map, or in the static LevelManager that's calling the MapFactory (passing the new ContentManager as a parameter to the MapFactory, along with the name of the desired map)?

Alternatively, is there a simpler/cleaner way to do this? I'm more concerned with the code being easily comprehensible than efficient right now, as this is my first attempt at this kind of game.

*Ex. Castlevania, Metroid, but simpler (for now). I'd like to implement constant streaming eventually (chunks loaded as they are approached), but I want to get this part down first.

UPDATE: Instantiated the second ContentManager using this.Services inside the Game class (it was the only way I could find to get access to Game.Services, which is what everywhere online says to use in the ContentManager constructor). Should have thought of that sooner. For anyone confused by this in the future, the full line of code is:

ContentManager myContent = new ContentManager(this.Services, "myContent")


texts:
I'm making a custom engine, and after much research, I realized that the state changes and the vertex or texture data loadings to VRAM are the most slow operations.

So I want to optimize it making a wrapper between OpenGL and a rendering engine that has a set of functions like OpenGL's, but making it like it saves the calls in arrays. After the "pre-rendering" phase, it schedules all operations, when possible, to make the state changes of GPU less frequent. Next, the scheduler groups vertices to make contiguous packs of vertices, when possible, and render it all, together.

Example of interface

class Renderer
    {
        typedef int Texture; // TMP
        class State
        { public:
            Vertex * Start;
            Vertex * End;
        };

        class SOC : public State
        { public:
            Shader * Reference;
            // End Null if update
        };

        class EOC : public State
        { public:
            GLenum * Reference;
            Vertex * Start;
            Vertex * End;
        };

        class FOC : public State
        { public:
            FrameBuffer * Reference;
            // End Null if draw
        };

    public:

        // Rendering api
        //-------------------------------------------------
        static void End();
        static void Begin(GLenum);
        static void Enable(GLenum);
        static void Disable(GLenum);
        static void BlendMode(GLenum, GLenum);
        static void BindShader(Shader *);
        static void UnbindShader(Shader *);
        static void UpdateShader(Shader *);
        static void SamplingType(GLenum, GLenum, GLenum);
        static void DrawFrameBuffer(FrameBuffer *);
        static void BindFrameBuffer(FrameBuffer *);
        static void UnbindFrameBuffer(FrameBuffer *);
        static void Vertex2(int, int);
        static void Vertex2(float, float);
        static void Vertex2(int, int, Color);
        static void Vertex2(float, float, Color);
        static void Vertex2(int, int, Texture);
        static void Vertex2(float, float, Texture);
        static void Vertex2(int, int, Color, Texture);
        static void Vertex2(float, float, Color, Texture);
        //-------------------------------------------------

        // Rendering phases
        //-------------------------------------------------
        static void Initialize();               //   0
        static void PreparePipeline();          //   1
        static void Schedule();                 //   2
        static void StartRenderPipeline();      //   3
        static void RestorePipeline();          // (0.5)
        //-------------------------------------------------

    private:

        // Rendering source
        //-------------------------------------------------
        static Vertex           * GlobalVertexBuffer;
        static std::vector<SOC>   ShaderStates;
        static std::vector<EOC>   EnableStates;
        static std::vector<FOC>   FBOStates;
        //-------------------------------------------------

        // Handlers openGL
        //-------------------------------------------------
        static GLuint StreamVertexBuffer;
        static GLuint Index;
        //-------------------------------------------------

        // Current state
        //--------------------------------------------------------------
        static std::unordered_map<GLenum, bool>         ActiveFlags;
        static std::unordered_map<Shader *, bool>       ActiveShaders;
        static std::unordered_map<VertexBuffer *, bool> ActiveVBOS;

        static GLenum CurrentPrimitive;

Is this scheduling operation a slowdown for the CPU, or is it a benefit?


texts: C#/XNA multiplayer TCG game inside a browser possibe?

texts:
I wish to try and create a TCG using C#/XNA that would run inside a web browser. Some of the main game's features would be:

At least 2.5D to imitate the card flipping/shuffling and etc. effects
Simple particle effects (maybe even none at all)
Use of scripting since each card would have its own abilities/type/effects
Utilization of relational databases(cards themselves, users, profiles, decks, etc.)
Lobby
Chat rooms
Buddy list
Free

Is such thing possible? You might want interject and point me towards Flash/AS3 as a better alternative, but the thing is I'm much more versed in C# than AS3 and never worked with Flash.

Also, I believe Unity has a WebPlayer and uses C# as one of its scripting(?) languages. Thing is, I want to make sure that the game can run on pretty old PC/Laptop/maybe Tablet and or smartphone hardware.

Suggestions? Warnings? I'm just brainstorming about this at the moment to select the right technologies(aka C#/XNA/? if possible or Unity/C#/Unity WebPlayer) to start researching further on my own. Not a single line of code has been written.


texts:
I was recently given an assignment to generate a mesh from code, in Unity.

  At runtime, the player will click at random positions on the screen.
  An array will store all these points. There must be at least 4 points
  for the calculation to take place. The users clicks will stop getting
  accepted once the player has clicked very close to the first clicked
  point (till here, I got it to work).

  After all the points are added to the array/List, a mesh should be
  created from those points.

I thought of a few algorithms to work it out. First one - Delaunay triangulation

But what if there are 5 points on the same circle for the mesh? This negates the Delaunay's algorithm.

So I figured I'd first take the entire list of points, and parse through each point to find a convex hull. And then try to do each of the triangles within.

I'm not sure if I'm doing this the right way, or if there is any better way for what I want to do. If this is the best way, I don't know how to do the algorithm for the triangulation inside the convex hull


texts: Can Soomla directories be safely moved one directory down in Unity?

texts:
I'm integrating in-app purchases in my game. To do so, I chose to use Soomla (http:soom.la) asset. I use the free version registering for the grow bundle. I've downloaded a unitypackage named unity3d-grow-spend from my grow web console.

When I'm going to import the unitypackage I find that it wants to import things in a variety of top-level directories, like:

/GROW/*
/Plugins/Android/*
/Plugins/GROW/*
/Plugins/iOS/*
/Plugins/Soomla/*
/Plugins/WP8/*
/Soomla/*
/WebPlayerTemplates/SoomlaConfig/*

All this installs inside my /Assets directory.

The thing is that in my assets I only have

/Assets/Scenes
/Assets/Plugins

and I do not want pollution in there.

Question:

Is it safe to move /Assets/GROW into /Assets/Vendor/GROW and move Soomla and WebPlayerTemplates also into the Vendor directory?

Or doing that movement some in-app purchases mechanism will fail?

This would result in having only

/Assets/Scenes
/Assets/Plugins
/Assets/Vendor

in the top-level, which is rather nice.


texts:
I want to create a bungee jumping-like game in Unity and therefore I need a rope physics. I especially need elastic ropes with capability to pull objects with velocity after a little extension. Do you know any place to start? Because I have no idea how to start such scripting.

I looked at Asset Store. There are some rope physic simulators, but I have to do it on my own, plus they are really expensive.

EDIT: I already tried using Spring and/or Configurable Joints in Unity, but they did not give what I want.


texts: How to implement a Play As Guest feature on a mobile device using PhoneGap?

texts:
I have a Facebook Web Game that I converted to Android and iOS using PhoneGap. I can use Facebook for authentication on my mobile apps, but I would also like to allow the user to play as a guest. I've seen various games implement this workflow before and I'm curious how it is actually done. What unique identifier is the phone sending to the server to authenticate against? Does each phone have something unique about it that PhoneGap can expose via a plugin? Does anyone know the logic behind the "Play As Guest" feature many mobile games implement?

Thanks!


texts: Improving Position Sync Bandwidth Usage in a Multiplayer Game

texts:
This is the class i use to sync position between clients in a multiplayer top-down 2D shooter game:

    [System.Serializable]
    public class MovementUpdateClass
    {
        public int MessageTime {get; set;}

        public Vector2Serializer PosXY = new Vector2Serializer();
        public Vector2Serializer VelXY = new Vector2Serializer();
        public float RotZ {get; set;}

        public MovementUpdateClass(int messageTime, Vector2 posXY, Vector2 velXY, float rotZ)
        {
            MessageTime = messageTime;
            PosXY.V2 = posXY;
            VelXY.V2 = velXY;
            RotZ = rotZ;
        }
    }

Any advices about how to improve & optimize it so it spends less bandwidth for both sender and receivers?

Thanks.


texts: Calculate evenly distributed points along a curve

texts:
I'm using this equation to calculate a series of points along a quadratic curve:

// Returns a point on a quadratic bezier curve with Robert Penner's optimization of the standard equation
result.x = sx + t * (2 * (1 - t) * (cx - sx) + t * (ex - sx));
result.y = sy + t * (2 * (1 - t) * (cy - sy) + t * (ey - sy));

Sadly the points are unevenly distributed, as you can see in the dashed-line rendering below. The points are denser in the middle of the curve, and are further spaced apart near the edges. How can I calculate a evenly distributed set of points along a quadratic bezier curve?

Please note that I'm using this for rendering a dashed line, so a slow solution in MATLAB or something will not do. I need a fast solution that will fit inside a renderer. This is not for research or a one-off calculation!

Edit: I'm not asking how to accomplish the above. The above is MY RENDERING! I already know how to estimate the length of a bezier, calculate the number of points, etc, etc. What I need is a better bezier point interpolation algorithm since the one I have calculates points unevenly distributed along the curve!

Edit: Code in any language will do! My game runs in JS but I can port anything.


texts: When to use C++ and when to use blueprints?

texts:
I'm trying to learn how to use the Unreal Engine. I have basic knowledge of C++. Recently I started making a Survival Horror Game as a project that I'm just doing for the learning experience. So far though I've implemented every feature through the Blueprint system.

So my question is for what and when will I use code to improve/make a game in Unreal Engine?


texts: Unity Navigation & Pathfinding and A star algorithm

texts: I just tried to follow a tough tutorial about A* path finding in Unity C#. I have also tried Unity own Navigation & Pathfinding system which is actually quite easy to understand and implement. I am willing to know it that how NavMesh system of unity actually works. Do it also implement the A* algorithm. Further I want to ask that how does A* algorith will work with slope. I implement A* with plane where is no slope.


texts: How to design AI to understand its selling decisions?

texts:
I am programming a game where there are 4 competitors (players) who have finished goods that they can then sell to given markets for which they have (at most a single) contracts for.  Any finished goods is for a given market.

Turn order is important in the game as this will decide who sells first.

Scenario.

Turn order: Player #A, #C, #D, #B

The problem I'm having is I have no idea how to make the AI players aware of the following factors; they seem to need to know a lot of things which may impact on where to sell first.

For example, AI needs to know.

Am I the only person who can sell to a given market?
If so, that's fine -- sell all goods to market.

If not, do the following

Who are my competitors for a given market and will I be able to sell first?
If I sell in Market A, will I still get a chance to sell to Market B when turn order returns to me?  (demand for items goes down for every sale and can bottom out)

Indeed, this is one strategy I'm wanting to employ --  sell to a given market because i he does not he might not get a chance to sell again when turn order returns to them.

If I sell, should the AI go for most revenue per selling round.

Currently I am looking to order all markets for a given player based upon selling ability (who can sell first)

Basically an array of people who can sell for a given market based on player order.

These people then sell, and we reduce the array by one and repeat the process.

Whilst this solves some problems, it does not solve the bigger problem, which is the AI will just end up selling stuff in the order that of the Markets array; and not specifically to the ones where it is either advatangeous to do so, or will generate them the most money.

I am wondering, how do you design an AI to make coheriant, logical decisions about what when and why they would sell to a given market?

Sorry for the wall of text.

Many thanks


texts: How can I add and subtract convex polygons?

texts:
I have two 2D convex polygons overlapping each other. I am looking for an algorithm to subtract and add them. The result must be a single concave polygon or (even better) a set of biggest convex ones forming the concave result (e.g. triangles).

(Left: The initial overlapping polygons. Middle: The resulting concave polygon after adding. Right: A set of convex polygons forming the concave result. Here it would be better to get convex polygons bigger than a triangle for performance reasons. An subtraction of the two overlapping polygons would lead to the same picture as on the left but with the overlapping area not being part of the resulting polygon.)

How can I do this?


texts:
I'm developing an Isometric Game but I have problem apply the right layer for make, for example, a wall behind or in front of the Player depending on the Player position.

I'm able of getting works in an orthogonal map relating the y-axis value of an object with his layer but in an isometric map, the y-axis is not aligned with the editor one.

Anyone can help me understand how to manage this?


texts: How can I correctly instantiate an octree in UE4?

texts:
I tried to create a simple Octree like this:
(I looked at the FMeshTriOctree source code since no question in answers.unrealengine.com helped me)

// My FVertex class is slightly more complexe, but let's say it's something like this:
class FVertex : public FVector
{
      int32 ID;
}

struct FVertexOctreeSemantics
{
        enum { MaxElementsPerLeaf = 16 };
        enum { MinInclusiveElementsPerNode = 7 };
        enum { MaxNodeDepth = 12 };

        typedef TInlineAllocator<MaxElementsPerLeaf> ElementAllocator;

        FORCEINLINE static FBoxCenterAndExtent GetBoundingBox(const PBS::FVertex* Vertex)
        {
            return FBoxCenterAndExtent(Vertex->GetBoundingBox());
        }

        FORCEINLINE static bool AreElementsEqual(const PBS::FVertex* A, const PBS::FVertex* B)
        {
            return A==B;
        }

        /** Ignored for this implementation */
        FORCEINLINE static void SetElementId(const PBS::FVertex* Element, FOctreeElementId Id){}
};

typedef TOctree<PBS::FVertex*, FVertexOctreeSemantics> FVOctree;

But when I instanciate my octree it returns:

Fatal error: [File:D:\BuildFarm\buildmachine_++depot+UE4-Releases+4.9\Engine\Source\Runtime\Core\Private\Misc\CoreMisc.cpp] [Line: 975]
The TOctree() constructor is for internal usage only for hot-reload purposes. Please do NOT use it.

What can I do?


texts: I need some broad phase algorithm for my 2d game (shmup, bullet hell). Does one or another solution have any major advantages?


texts: DirectWrite Producing Strange Artifacts?

texts:
I've written the basis to my UI system around Direct2D. I like it because it's fast and easy to use (even if I had to do some messy work to get it to work with DirectX11). However, I notice when using DirectWrite I'm getting strange problems with my text.

As you can see, the e is a little screwwed up, and it overall looks a little bumpy. This only happens with certain fonts in certain sizes, and with certain arrangements of letters. This particular example is Verdana in size 16.0 font.

Can I fix this? It's pretty annoying to change all my words and fonts because of this problem.


texts:
I'd like to add an online leaderboard to my iPhone game.  Upon discovering the time and effort required to create a Game Center account I started considering other options.

What do you use for online leaderboards?  Why?

I'm open to a variety of options including App Engine, using EC2, Open Feint, PlusPlus etc.

-- I'd like to make this a community wiki but I don't see the option.


texts: Unity - Avoid using Find method by caching UnityObjects - Code review

texts:
I'm trying to avoid using GameObject.Find during runtime to find particular GameObject components when wanting to instantiate them.

I have created a cache for the gameobjects from which I can either return the original instance or create a new instance.

Components which should only have one instance are returned by GetOriginal<UnityObject>

A new instance of an Original component is returned using GetInstanceOf<UnityObject>

public class GameObjectTools : MonoBehaviour
{
    static List<Object> gameObjectCache = new List<Object>();

    // This is called BEFORE Start() when the script is being loaded
    void Awake()
    {
        // Cache any GameObject classes that are required by other classes here
        gameObjectCache.Add(GameObject.Find("Timer").GetComponent<Timer>());
        gameObjectCache.Add(GameObject.Find("Object Rotator").GetComponent<ObjectRotator>());
        gameObjectCache.Add(GameObject.Find("Object Translator").GetComponent<ObjectTranslator>());
    }

    public static T GetOriginal<T>() where T : Object
    {
        int index = -1;
        int numObjects = gameObjectCache.Count;

        for (int i = 0; i < numObjects; ++i)
        {
            if (gameObjectCache[i].GetType() == typeof(T))
            {
                index = i;
                break;
            }
        }

        return index == -1 ? null : gameObjectCache[index] as T;
    }

    public static T GetInstanceOf<T>() where T : Object
    {
        var o = GetOriginal<T>();
        return o == null ? null : GameObject.Instantiate(o) as T;
    }
}

I'm slightly concerned that I am not approaching this problem in the right manner and was hoping for some feedback regarding my methodology.

Is there a more efficient or straightforward approach to achieve what I am trying to achieve here?

EDIT

public class Ball : MonoBehaviour
{
    int lifeSpan = 1000;

    void Update()
    {
        if (Timer.CurrentTime > lifeSpan)
            GameObject.Destroy(gameObject);
    }
}

public class GameObjectTools : MonoBehaviour
{
    public static Ball Ball;

    void Awake()
    {

        Ball = GameObject.Find("Ball").GetComponent<Ball>();
    }
}

If I call

var ball = GameObject.Instantiate(GameObjectTools.Ball) as GameObject;

anytime after the lifespan of the ball has expired then I will get a null reference error.

How then can I ensure that this doesn't happen while still being able to create new instances from a static cache?


texts: How do I convert from the global coordinate space to a local space?

texts:
Given an entity named EntityA, I want to define a local coordinate space, where the position of EntityA is the origin, its heading vector is the X axis, and the normal of the heading vector is the Y axis:

Given their global coordinates, how do I find the position of another entity in EntityA's local space?

An example: EntityA's global position is (50,50), and that of EntityB is (80,90). What is then the position of EntityB in EntityA's local space?

EDIT: Please go easy on the math.


texts: Substance Painter: Jagged edges when painting normals

texts:
I am painting normals on a normal layer using the Textures tab to make bumps and crevices. But the effect is so jagged. How can I fix this?

INB: Texture Set is already on 4K so it's not a quality issue.


texts: How do I create interactive grass like this?

texts:
I would really like to create grass that reacts to the player's movements, so when they walk through, it moves away from them, just like this:

https://www.youtube.com/watch?v=5Gc-Ue9_xgk
https://www.youtube.com/watch?v=tFgyc8iykLk

The problem is, I'm not sure if this is a case of animation, combined with some form of physics, or controlled by a script. The grass looks like 2 planes that are crossing each other and originally I was going to try a LookAtPlayer script, however that would just make the planes spin around to face the player, instead of swaying in the wind, or swaying away from the player when they walk past them.

Any advice on how to create something like this with grass?


texts: How to Convert a Z Up Matrix to a Y Up Matrix?

texts:
My 3D program exports my vertex data and instancing matrixes in Z+ up format.  I want to store them in my own data format as Y+ up.  If given a Matrix4 describing a position with Z+ being up. How can I convert that to a Y+ up Matrix4?

I know you can just rotate the object but I don't want to rotate the object.


texts: How do i calculate the velocity of a sprite after it leaves circular motion?

texts:
I'm trying to make a game where the character can swing on a rope.

I want to know how the velocity of player is calculated when it stops circular motion. Any help would be appreciated.


texts: Rendering of a minimized / out of focus directx game is slow

texts: I m working on a project that captures the game windows and send it to another node. As long as game is in focus or maximize, the rendering is smooth and steady. When the game is out of focus or minimized, the streaming shows jerky effect. When you maximize the windows, the affect again disappears. Is that an issue of directx game rendering or something else? How this problem can be solved?


texts: How do texture lookups for trig functions work?

texts:
I have a pixel shader that calculates a mandelbrot fractal. It uses the standard formula:

z = z2 + c

I'd like to extend it so the power z is raised by varies. To do this i have the following function:

float2 ComPow(float2 Arg, float Power)
{
    float Mod = pow(Arg.x * Arg.x + Arg.y * Arg.y, Power / 2);
    float Ang = atan2(Arg.y, Arg.x) * Power;

    return float2(Mod * cos(Ang), Mod * sin(Ang));
}

The problem i've got is the xbox does this really slowly compared to squaring a complex number. I'm thinking it's partly because of the increased number of instructions, but mainly it's using trig functions (cos, sin and atan2).

I tested this by adding a single atan2 within the for loop and it's visibly jerky, whereas before it was getting a good FPS.

Can i use texture lookup to speed up / replace the cos, sin and atan2 calls? If so, how?


texts: Programming with Python in a recent version of Minecraft

texts:
I've been teaching Python programming to a friend's son using the book Adventures in Minecraft. This book comes with a starter kit that contains a pre-configured Bukkit (v.1.6.4) server, and targets Minecraft 1.6.4.

My friend's son would like to use a more recent version of Minecraft, unfortunately Bukkit is no longer maintained.

Is there another way to use Python with Minecraft? I've googled a bit but without success. I'm not a player of Minecraft myself so there is a lot of Minecraft terminology that I don't understand.

Thanks


texts:
In the process of writing my game prototype, I have found the OBJ format to be insufficient for my needs - it does not support any sort of animation, it doesn't support triangle strips (I'm targeting my ancient hardware). MD2 wouldn't fit the bill because it doesn't have support for named model pieces. MD3 would probably work, but like OBJ, it doesn't have support for triangle strips. Considering the limitations of the formats above, I've come to the conclusion that it may be necessary to write my own format to accommodate my requirements, but that feels like reinventing the wheel.

So, I need a format which can specify indexed tri-strips, supports textures, UV-mapping, collision data, can have multiple named segments and supports animations (have I forgotten anything?). Is there any format like that which already exists, or do I have to write my own?


texts: LibGDX: How to use AssetManager with Texture Atlases?

texts:
A similar question was asked before, but I never saw an answer.

How does one load individual texture regions that derive from a texture atlas using assetManager? I know that assetManager relies on a file name. (the file name could be the .pack file, for instance).

How would this work for individual texture regions? What would go in the file handle?

How would I do this:

manager.load("sprite_sheet.txt", TextureAtlas.class);

but with a textureRegion from that atlas?


texts: How to fill with empty space with retangles

texts:
I have a 'square' class with the representation of its limits from the variables x1, y1 and x2, y1 these variables define points 1 and 3 of the same, in this case the coordinates would be (0,0), (10, - 10):

From this drawing I want to insert rectangular areas, also defined through x1, y1, x2, y2 coordinates, within that area. In this example case I will use the following values (input):
area1 = (0,0)(3,-3),
area2 =  (4,-2)(6,-4),
area3 =  (8,-1)(10,-4),
area4 =  (1,-5)(6,-7),
area5 =  (7,-6)(9,-9)

How to obtain a function from there that returns the rectangles (coordinates) of the largest possible areas within the remaining empty areas and not occupied within the main square, as shown in the visual representation?

Notice, the output of the function in this case should be:
outputArea1 = (3,0)(8,-2),
outputArea2 = (8,0)(10,-1),
outputArea3 = (3,0)(4,-3),
outputArea4 = (6,-2)(8,-4),
outputArea5 = (6,-4)(10,-6),
outputArea6 = (0,-5)(1,-7),
outputArea7 = (6,-6)(7,-7),
outputArea8 = (9,-6)(10,-10),
outputArea9 = (0,-7)(7,-10),
outputArea10 = (7, -7)(9,-9),
outputArea11 = (7,-8)(9,-10)
The following code demonstrates the implementation without the requested function:
class Retangle {

borderLimitX1 = 0;
borderLimitX2 = 10;
borderLimitY1 = 0;
borderLimitX2 = -10;

static void Main() {

    List < Retangle > areas = new List < Retangle > ();

    ///areas.Add(x1,x2,y1,y2)

    areas.Add(0, 0, 3, -3);
    areas.Add(4, -2, 6, -4);
    areas.Add(8, -1, 10, -4);
    areas.Add(1, -5, 6, -7);
    areas.Add(7, -6, 9, -9);

    List < Retangle > remainingAreas = CalculateRemainingAreas(areas);

}

List < Retangle > CalculateRemainingAreas(List < Retangle > originalAreas) {

    List < Retangle > remainingAreas = new List < Retangle > ();

    ///// --> Algorithm to calculate Remaining Areas   <-- ///

    return remainingAreas;
}
}

  internal class Retangle {
int x1,
y1;
int x2,
y2;

Retangle(int x1, int y1, int x2, int y2) {
    this.x1 = x1;
    this.y1 = y1;
    this.x2 = x2;
    this.y2 = y2;
}

}


texts: Getting Target position at the time of shooting

texts:
I have a bullet that has to hit a constantly moving enemy.

So, in BulletScript, I have declared a Transform

public Transform enemy;               //and assigned enemy object to it that is continuously moving and changing its position

Now, when I try to use enemy.position in bullet script so as to hit it, enemy.positiongives the position at which the enemy started and not the position at which it was when bulletprefab was shot.

How can I get the updated position of enemy object every time bulletprefab is instantiated.


texts: Swing for game development - regarding threads

texts:
For those of you who use Swing to develop their real-time Java games. (Meanign a game that constantly updates game state and redraws the screen using a constant loop).

As I see it, there are three main possible approaches to designing games in Swing, in relation to threads:

1- Have the entire game (except for especially long-running tasks) run on the EDT.

2- Have the entire game run on a non-EDT thread.

3- Have clear seperation between a thread to constantly run game logic (a non EDT thread), and a thread to constantly update the screen (the EDT).

By your experience and knowledge, which approach is the most common, and/or the most efficient, and/or the most reasonable programming-wise (aka isn't relativley very complex to design)? Which approach should I use?

Help would be appreciated :) (I really want to pick up good habits).

EDIT: Clarification - Even if you don't recommend Swing for game development, please answer my question as it is. Thank you


texts:
I hope this question hasn't been asked before.

I'm thinking of creating an MMO game, perhaps for Facebook. I've investigated the options of using Java or Flash/Flex. But I'm still not sure which to go with. Does anyone have any advice on which language to use?

Which language has more open source or free tools/libraries? Which one has better performance for a database transaction-heavy game?

A few notes:
I'm intending it to be a 2D, isometric game with cartoony graphics. Nothing necessarily intense on the graphics front. I've heard of JMonkeyEngine, but that's 3D. The only other thing I've found that's good for 2D is LWJGL. One thing I don't like about Flash/Flex is that it can't create a direct connection to the database. Is that also true for a Java-based game?

Essentially, I would like to know how to approach the development of an MMO. What tools/libraries should I use? I'm hoping that there are open source/free options.

Thank you for your time.


texts: What income models are available for Xbox games?

texts: There are number of income models available for different games on various platforms - income from ads, paid games, paid DLCs, microtransactions and so forth. What sources of income are available for developers of Xbox games (both on physical discs, Live Arcade and Live Indie)?


texts: How to make lens flare ignore layers work with first person character in Unity 5?

texts: I have a simple lens flare on my directional light (sun) and I would like the flare to only be visible when the sun is directly visible, naturally...But right now with the default ignore layers, the flare is only visible when 'Everything' is ticked. Obviously this therefore means you can see the flare through other objects which I don't want. I first thought that the camera must have been sitting 'inside' the standard assets first person character's collider, but it was definitely outside the collider so I don't see why it won't show...Could someone show me how to fix this? Thanks.


texts: How to convert Texture2DContent to Texture2D in custom ContentTypeReader

texts:
I'm trying to implement a custom ContentPipeline extension that writes a Surface object with a Texture2D member.

My input file is an xml with fields for all of my Surfaces and their members. In the xml, my Surface's Texture2D is represented by a path to an image file.
In my ContentProcessor, I want to load the Texture2D from the image file path, then write that texture data straight into my object's xnb with the rest of a Surface's members.

Right now, I've got the ContentTypeWriter writing a different ("CompiledSurface") object with a Texture2DContent member. The Texture2DContent is created in the ContentProcessor using BuildAndLoadAsset(string path).

My importer, processor, and writer all seem to be doing their jobs. But in my ContentTypeReader, I can't figure out how to convert the Texture2DContent back to a Texture2D in order to create my runtime object.

Any help is much appreciated.

class Surface
{
    protected Rectangle bounding_box;
    protected Texture2D texture;
    ...
}

class CompiledSurface
{
    public Texture2DContent texture;
    public int x;
    public int y;
    ...
}


texts: Unity 2D - Tile based puzzle. Game Over logic doesn't work

texts:
I'm trying to create a clone of the popular mobile game 1010! However I am struggling to determine when the player can no longer make any moves and therefore it is game over. Can you see any flaws in my logic?

This is my Game Board - It's a 9x9 Grid which is stored as a 2dArray of transforms. The three shapes at the bottom are held in a 'ToolBox':

The shapes are just a Game Object which contain 1-5 child Game Objects which have a SpriteRenderer

My current Game Over logic loops through the Tool Box and for each shape it loops through the grid and sets the position to the grid[x, y] and then calls my IsValidPosition(Shape shape) method.

The IsValidPosition(Shape shape) gets each child transform of the shape and checks whether it is within the Game Board or if the position in the grid is currently occupied by another shape.

This is where the Game Over check starts:

void PlaceShape(Shape shape) {
    if (m_gameBoard.IsValidPosition (m_activeShape)) {
        m_gameBoard.StoreShapeInGrid (m_activeShape);
        m_activeShape.m_placed = true;
        m_toolBox.RemoveShape (m_activeShape);

        //When placed, set sorting layer to board so that sprites dont render over unplaced shapes, also set color back to solid.
        foreach (SpriteRenderer sprite in m_activeShape.GetComponentsInChildren <SpriteRenderer> ()) {
            sprite.sortingLayerName = "Board";
            sprite.color = m_activeShape.m_color;
        }

        //If we completed any lines then score them.
        if (m_gameBoard.m_completedLines > 0) {
            m_scoreManager.ScoreLines (m_gameBoard.m_completedLines);
        }

        if (IsGameOver ()) {
            Debug.Log ("GAME OVER");
            if (m_gameOverPanel) {
                m_gameOverPanel.SetActive (true);
            }
        }

        //Destroy game objects with no children.
        Cleanup ();
    } else {
        m_toolBox.PutShapeBack (shape);
    }
}

This is the method that loops through the shapes that are currently in the tool box:

bool IsGameOver() {
    foreach(Shape shape in m_toolBox.m_toolBox) {
        Debug.Log (shape.name);
        shape.m_fitsOnBoard = m_gameBoard.WillItFit (shape); //Tell shape if it fits on the board.
        shape.Reset ();
    }

    foreach (Shape shape in m_toolBox.m_toolBox) { //If at least 1 shape can fit on the board then it's not game over yet.
        if (shape.m_fitsOnBoard) {
            return false;
        }
    }
    return true;
}

The Game Board's WillItFit(Shape shape) method is then called for each shape in the tool box:

public bool WillItFit(Shape shape) {
    for (int y = 0; y < m_height; y++) {
        for (int x = 0; x < m_width; x++) {
            shape.transform.position = new Vector2 (x, y);
            if(IsValidPosition (shape)) {
                Debug.Log(shape.name + " fits at x: " + x + ", y: " + y);
                return true;
            }
        }
    }
    return false;
}

Then the IsValidPosition(Shape) method is called which subsequently calls the IsWithinBoard and IsOccupied methods:

bool IsWithinBoard(int x, int y) {
    return (x >= 0 && x < m_width && y >= 0 && y < m_height);
}

bool IsOccupied(int x, int y, Shape shape) {
    return (m_grid [x, y] != null && m_grid [x, y].parent != shape.transform);
}

public bool IsValidPosition(Shape shape) {

    foreach (Transform child in shape.transform) {
        Vector2 pos = Vectorf.Round (child.position);

        if (!IsWithinBoard ((int) pos.x, (int) pos.y)) {
            Debug.Log (shape.name + " position: " + pos + " IS NOT WITHIN THE BOARD");
            return false;
        }

        if(IsOccupied ((int) pos.x, (int) pos.y, shape)) {
            Debug.Log (" position: " + pos + " IS ALREADY OCCUPIED");
            return false;
        }
    }

    return true;
}


texts:
How to see the surface arc in Unity?
There is the tutorial and in this tutorial we can see the arc in editor:

While I can not see it. I checked that all my gizmos are enabled.

How can I enable the arc?


texts: Message Passing b/w “LAN Server Only” and “LAN Client” on Different Scenes in Unity

texts:
I want to pass message back and forth on client and server which are on different scenes, how can I do that in Unity?**

Following is my Scenario:-
I have 5 scenes-

BaseScene (2) OfflineScene (3) OnlineScene (4) ClientOnline (5)
ServerOnline.

All these scenes have button having text of the names of the scenes.
On Base Scene, I have add empty game object on which i have placed "customNetworkScript" which extends from "NetworkManager" script and also placed "Network Manager HUD" on it. Following is the code which i have placed in "customNetworkScript":-

public class customNetworkScript : NetworkManager {

        public override void OnClientSceneChanged(NetworkConnection conn)
            {
                SceneManager.LoadScene("ClientOnline", LoadSceneMode.Single);
                ClientScene.Ready(conn);
                ClientScene.AddPlayer(conn, 0);
            }

            public override void OnServerSceneChanged(string sceneName)
            {
                SceneManager.LoadScene("ServerOnline", LoadSceneMode.Single);
            }
    }

I have placed "OfflineScene" and "OnlineScene" in the fields, named "Offline Scene" and "Online Scene" in "Network Manager" component. Also have placed an empty prefab in "Spawn Info" in "customNetworkScript" and it has component "Network Identity" on it. Now when i run project, on one instance, I click on "LAN Server only" and on another instance, I click on "LAN Client". And I get my respective scenes on both the instances -> "ServerOnline" appear on instance where I click "LAN Server only" and "ClientOnline" appear on other instance.
What I want is, when i click on "ServerOnline" button, a message string will pass on to "ClientOnline" scene and same happens in backward direction when i click on "ClientOnline" button.

I have tried "Rpc" and "Command" but they only work when I click on "LAN Host" instead of "LAN Server Only".
I have tried very hard but couldn't find anything useful. It will be a great pleasure if someone explain to me in detail along with the code, how can I achieve this.

ThankYou Very Much for Your Time.


texts: PlayClipAtPoint() playing multiple times on enemy death

texts:
I am having problems with PLayClipAtPoint(). I want to play a given sound as soon as a gameObject is destroyed. Here is my code (the concerned parts):

void Update()
{
    if (health <= 0)
    {
        StartCoroutine(Death());
    }
}

public IEnumerator Death() {
    anim.SetBool("isDying", true);
    AudioSource.PlayClipAtPoint(dmgSounds[0], transform.position);
    Destroy(gameObject, 3f);

    yield return null;
}

I assume that the problem is due to the fact that as soon as the conditions are achieved, in this case the health reaching zero, the coroutine starts and it will keep starting for each frame, but how else should I call it? Anybody has some hint to give?

EDIT: I have already tried to wrap the logic in a bool as suggested in the comment so that it would work only when the bool condition is valid, without success. Here is the code with the flag bool:

void Update()
{
    if (health <= 0)
    {
        if(isAlive){
            isAlive = false;
            StartCoroutine(Death());
        }
    }
}


texts: XNA Collision is quircky/wobbly, how to improve?

texts:
I am sorry if this was already answered but I couldn't find the answer.
So I am doing a tile based platformer and when I was making collision I had quiet a struggle I looked here and googled for answers but they all seems to be overcomplicated for such a simple task/game.

I did come up with this code and it works almost fine:

Rectangle boundRect = new Rectangle((int)position.X, (int)position.Y,
            (int)(sprite.Texture.Width * scale), (int)(sprite.Texture.Height * scale));

        Vector2 previousPosition = position;
        Vector2 previousVelocity = velocity;

        if (boundRect.Intersects(collider))
        {
            velocity = Vector2.Zero;
            position = previousPosition - previousVelocity;
        }

It works almost as good as I want, axcept few things. When I constantly move (i.e.) to left of a collider object(tile) my player sprite is shaking, if thats right word to use, for like 1-3 pixels from edge of object, also in this state I can't move any other direction (i.e. jumping up) till I stop my current movement.

So my question is basicly: "Can I improve this while keeping simplicity, or I need to use better(more complex) approach?"

P.S. Sorry for my English, it is not my native language.


texts:
I'm working to my first game containing items (built a small one before, strategy type but not very complicated). I was thinking something like this for the db design since it will be almost the same items in each shop.  I'm thinking of connecting the shop to user items (not sure if you understand what i'm thinking of):

shopname
  shopNameId, shopName
shopCategory
 shopCategoryId, shopNameId shopCategoryName,
shopItems
 shopItemId, armourId, oneHandedWeaponId, twohandedWeapoinId,

this would be for the shop..now;

oneHandedWeapons
 oneHandedWeaponId, weaponName, weaponMinAtk, weaponMaxAtk, ...

otherAttributes,

oneHandedExtendedAttributes
 oneHandedExtendId, oneHandedWeaponId, ... otherAttritubes,

and again for other item types.
This npc's will be the only place from where they can buy items.

Now when a user bought a new item from one of the shops i should insert the id of that item in the inventory table no?
I was thinking on a structure like this for a stash based on 10 slots.

userStash
userStashId, userId, slot1, slot2, slot3, slot4, slot6, slot7, slot8, slot9, slot10

now on each on slot i can insert the id of that item.

Now my questions:

Is it ok how i did this?
Do you see any problems?
Do you have any advice?
Can you give me another ideea / another example how should I do this part?


texts: Is there a library or a framework that handles networking in an RTS?

texts: I'm aiming for making a(n) RTS game with networking so instead of doing tedious stuff like networking I wonder if there is a library/framework that will save me the effort. I intend to make that game in Unity if it is of any interest.


texts: Serious issues with grid of connected springs

texts:
So i have a simulation I am trying to make where there is a grid. Each dot will be connected to the dot Above, below, left, or right (If such dot exists) via a logical grid.

Theoretically when I create a disturbance it will react slightly like cloth.

My problem is it is going all wrong! I didnt know which way to subtract to get the delta so I gave you two samples.

Issue one Detract: This one is probably the wrong one but it might help. Basically when you cause a disturbance it causes everything to fly away. Its pretty cool looking.

Issue two Attract: This one is probably using the correct delta, however when left on its own the grid eventually groups in on top of itself. Ignore the diagonal ones at the very beginning those are just an error, I removed them since recording that video.

Below is excerpts from the code that causes this. This system works entirely on a 1d array (because they arent always even close to a grid) and as a result I have a bunch of functions that find the index of next-door points. I am not showing their implementation unless that is likely to be the error.

The velocity resulting from the spring is stored in a variable springV.

Each frame the interaction displacement and resulting spring velocity is calculated through function transfer. Then after all of that is calculated it is applied to the positions through function resolveGridS. Transfer() is run on each particle one by one in an order, then resolveGridS is run after that.

Theoretically the correct force given from having a spring from the nextdoor point is calculated in the function resolveGridS and added to the total.

The "Resting" distance of the grid is about 30.

 var springV = Point()
    func transfer()
    {
        if (excluded) {return} //Gets rid of points not on the grid, they dont get to be springs

        let touch = MT.getFirstFinger()
    if (touch.down)
    {
        let location = getPosition()
        let dist2p = Math.dist2P(location, touch.location) / Storage.bounds.rb
        let angle = Math.calculateAngle(location, touch.location)
        pointTowords(touch.location)
        direction += 180
        let calc = (-dist2p * dist2p) + 1.0
        if (circleIndex == 0) {print(calc)}
        moveBy(calc / 5)
    }

    let id = Int(circleIndex / 5) //Get the 1d array location of this particle

    //Get the 1d array index of each of the next door points
    let above = moveDirection(id, Direction.Up)
    let below = moveDirection(id, Direction.Down)
    let left = moveDirection(id, Direction.Left)
    let right = moveDirection(id, Direction.Right)

    //Drag
    springV.x /= 1.1
    springV.y /= 1.1

    if (left.1 == -1) //This check just deals with edge cases
    {
        SpringC(Storage.particles[left.0].getPosition())
    }

    if (right.1 == -1)
    {
        SpringC(Storage.particles[right.0].getPosition())
    }

    if (below.1 == -1)
    {
        SpringC(Storage.particles[below.0].getPosition())
    }

    if (above.1 == -1)
    {
        SpringC(Storage.particles[above.0].getPosition())
    }
}

func resolveGridS()
{
    Storage.circles[circleIndex] += springV.x
    Storage.circles[circleIndex + 1] += springV.y
}

  func SpringC(loc: Point)
  {
        let pos = Point(x: Storage.circles[circleIndex], y: Storage.circles[circleIndex + 1])
        let delta = Math.subtract(loc, pos)
        let dist = Math.dist2P(delta)
        let norm = Math.multiply(delta, 1 / dist)

        springV.x += norm.x * 0.01 * abs(dist - 30)
        springV.y += norm.y * 0.01 * abs(dist - 30)

    }

NOTE: I really dont know how you are supposed to deal with physics when one object has multiple springs connected to it. I made the assumption that you just calculate the force each spring gives for each object. And then after all of the forces are calculated you apply it. That could be wrong.


texts: Fastest way to draw small particles in opengl?

texts: Quick question : Which is the fastest method to render a large array of 4x4/8x8 particles in opengl ? Currently i spend 2triangles for each one but i think that its slow so i would really like to know if im doing it right.....


texts: Unity: AddForce in transform.forward direction not working as expected

texts:
I am building a very simple car-driving game in Unity.

I have a Player object, which looks like this:

As you can see, I have a Rigidbody2d component attached to this object, as well as a script, called "PlayerScript".

Here is this script:

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

public class PlayerScript : MonoBehaviour
{
    Rigidbody2D carRigidbody;
    Vector3 turnVector;
    Vector3 forwardDirection;
    // Start is called before the first frame update
    void Start()
    {
        carRigidbody = GetComponent<Rigidbody2D>();
        turnVector = new Vector3(0, 1, 0);
    }

    // Update is called once per frame
    void Update()
    {
        //transform.lo
        Debug.Log(string.Format("Transform.rotation is {0}", transform.localRotation.eulerAngles));
        Debug.DrawRay(transform.position, transform.forward, Color.yellow);
        if (Input.GetKey(KeyCode.UpArrow))
        {
            carRigidbody.AddRelativeForce(transform.forward * 10);
        }
        if (Input.GetKey(KeyCode.DownArrow))
        {
            carRigidbody.AddRelativeForce(transform.forward * -10);
        }
        if (Input.GetKey(KeyCode.RightArrow))
        {
            transform.Rotate(turnVector);
        }
        if (Input.GetKey(KeyCode.LeftArrow))
        {
            transform.Rotate(-turnVector);
        }
    }
}

I would expect for this code to make my Player object move forward in its local coordinate space when I hold the up-arrow on the keyboard, and move backward in the same space when I hold the down-arrow. Also, The left and right arrows should simply rotate the player-object (changing the forward direction in its local coordinate space).

Rotating left and right seems to work, but moving forwards and backwards seems to only work in the world coordinate space for some reason. Not sure If I am missing something. Here is a gif of what happens.

As you can see, initially, moving forward and backward using the up and down arrow keys works. I then use the left arrow key to rotate the object left, which also works. But when I then try and add a force in the forward or backward direction, the object is not moving in the object's local forward direction, but instead, in the same forward direction as before.

What am I missing and how can I fix this?


texts:
I was wondering if anybody knows about any good pieces of equipment fit for recording sound effects for games.
If you can, also tell please me the price range for professional equipment.


texts: Rain World : How to have intelligent movement / animation?

texts:
In the project RainWorld the characters seem to move "intelligently" as they move "unrestricted". They seem to know "how" to move their limbs and "what" needs to be done.
Here for an example the lizard seems to know how to move his body after he got struck by a weapon.

Also here it looks as if it is intelligently grasping the long ladder/using the jet thinging to climb itself up.

I had been looking into many sources to find out how such gets done but with no significant result. I need help to point myself to the right direction.

Edit

I have figured out from dev log  that characters are just bunch of boxs connected/bounded by an elastic bound "string". But the way the character moves still eludes me.


texts: Is Xbox Live suitable for a multiplayer FPS?

texts:
I'm working on a basic first person shooter.  I would eventually also like to publish it on Xbox Live.

If I do this, will I still have access to parties (invite and chat)?  Does Microsoft provide servers for multiplayer, or do I have to provide my own?  Am I free to connect my own server IP from the Xbox system within game?  Can I charge people on a web page outside of Xbox for things like microtransactions or to maintain the cost of the servers?


texts: Using Slick2D/LWJGL to brighten an Image

texts: Using the Slick2D Library for Java, I want to know if there is a way to brighten an instance of org.newdawn.slick.Image. I'm willing to use other image-manipulation libraries if need be.


texts: directX rotation of a 3d cube inconsistent

texts:
i'm trying to develope a simple 3d cube in directX that can be rotated in any direction by dragging the mouse.

It works in the following way: i drag the mouse to the right or left, and the cube rotates along the Y axis accordingly. The same goes if i drag the mouse up or down (in this case the rotation is along the X axis).

The problem occurs if i rotate my cube 180 degree on X-axis. After this, every rotation along the Y-axis is in the opposite direction, so that if i try to move it towards positive Y-axis it moves in negative Y-axis.

I understand it has something to do with the way i do the transformations, but i can't fix the problem on my own.

D3DXMatrixRotationY(&MatRotY, rotation.y);
D3DXMatrixRotationX(&MatRotX, rotation.x);
D3DXMatrixTranslation(&MatTran, position.x, position.y, position.z);

D3DXMatrixMultiply(&MatRotXY, &MatRotY, &MatRotX);
D3DXMatrixMultiply(&MatRotXY, &MatRotXY, &MatTran);
D3DXMatrixMultiply(&worldMatrix, &worldMatrix, &MatRotXY);

PS: i know i shouldnt be using D3DX at all, but i'd like to solve this problem before having to switch to a different library.

thanks


texts: How to check collisions between rotated rectangle and a straight line?

texts: How do I detect collisions between a rotated rectangle and a straight line?


texts: Direct3D9: How to switch from one full-screen monitor to another?

texts:
I know how to display my game in full-screen on a specific monitor by specifying an adapter number when the D3D device is created.

However, I don't know how to switch from one monitor to another while the game is already running, without re-creating the D3D device from scratch. Is this even possible?

Thanks!


texts: Texture Wrapping isn't getting applied to my object

texts:
I have a Drawable Class, a Cube Class, and a Texture class. I feel like the texture wrapping isn't being applied due to some values being passed by reference, or just being discarded. My cube just derives from Drawable and only implements the render function and some other small overhead that shouldn't be a factor.

This is the error:
http://imgur.com/Dj2hCkp

Drawable:

// A structure to define each vertex of a model
struct Vertex
{
    glm::vec3 Position, Color, Normal;
    glm::vec2 UV;
};

class Drawable
{
public:
    Drawable();
    // cleans up our shaders, textures, and buffers
    virtual ~Drawable();

    // loads the buffers and shaders for our drawable
    virtual void loadBuffers();
    virtual void loadShaders();
    virtual void loadTextures();

    GLSL shaders;

    std::vector<Vertex> vertices;

    glm::mat4 model, view, projection;
    GLint modelLoc, viewLoc, projLoc, textureLocation;

    GLuint vao, vbo;

    GLTexture texture;
};

loadBuffer function:

glCreateVertexArrays(1, &vao);
glGenBuffers(1, &vbo);

glBindVertexArray(vao);

glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), vertices.data(), GL_STATIC_DRAW);

glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast<GLvoid*>(offsetof(Vertex, Position)));

glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast<GLvoid*>(offsetof(Vertex, Color)));

glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast<GLvoid*>(offsetof(Vertex, UV)));

glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);

My texture is created with this function:

GLuint& GLTexture::createTexture(int texWrap, int textureFiltering, const std::string filePath)
{
    glGenTextures(1, &_texture);
    glBindTexture(GL_TEXTURE_2D, _texture);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, texWrap);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, texWrap);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, textureFiltering);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, textureFiltering);

    sf::Image image;
    image.loadFromFile(filePath);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.getSize().x, image.getSize().y, 0, GL_RGBA, GL_UNSIGNED_BYTE, image.getPixelsPtr());
    glGenerateMipmap(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, 0);
    return _texture;
}

draw:

glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture.getTexture());
glUniform1i(textureLocation, 0);

shaders.use();

glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection));
glBindVertexArray(vao);
glDrawArrays(GL_TRIANGLES, 0, vertices.size());
glBindVertexArray(0);
shaders.unuse();

My UV is calculated by clamping the positions from -1 ~ 1 to 0 ~ 1

vert.UV = glm::vec2((vert.Position.x + 1.0f) / 2.0f, (vert.Position.y + 1.0f) / (2.0f));

I feel like i'm doing everything right, based on looking at the source code of two tutorials, yet it ends up warped no matter if i use

GL_CLAMP_TO_EDGE / BORDER
GL_REPEAT

Vertex shader:
    #version 330 core

layout (location = 0) in vec3 in_Position;
layout (location = 1) in vec3 in_Color;
layout (location = 2) in vec2 in_UV;

out vec2 vs_TexturePos;

uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

void main()
{
    gl_Position = projection * view * model * vec4(in_Position, 1.0f);
    vs_TexturePos = in_UV;
}

Fragment shader:

#version 330 core

in vec2 vs_TexturePos;

uniform sampler2D t_Texture;

out vec4 color;

void main()
{
    color = texture(t_Texture, vs_TexturePos);
}

It might be that the texture parameters aren't being stored, is there a openGL debugger I can use to verify this?


texts: How should I handle sound in a split-screen game?

texts:
In a split screen multiplayer game, sound events may be heard by more than one player, and they might sound different to each player.

For example, player one might hear the sound of the car they're driving low-pass filtered. Player two might hear the engine sound doppler-shifted as player one drives past at speed. Player three, observing from a distance might hear the unfiltered engine sound at a low volume.

In such a game, the "obvious" approach is to just play all the sounds at once. What methods can I use to improve on this, to prevent sound overload/"cacophony" while maximizing immersion for each player?


texts: Strange behavior with transformation matrix

texts:
I'm fairly new to transformation matrices. I'm using them to translate and rotate nodes and their child nodes. The following code works when applied once, but shows strange behavior when applied many times in a row:

void Node::update() {
    Mat4 parentTrans = (haveParent ? parent->getTransform() : Mat4::Identity());
    Mat4 thisTrans = this->getTransform();

    Mat4 translate = Mat4::Translation(this->getPosition());
    Mat4 rotate(this->getRotation());
    Mat4 result = parentTrans * thisTrans * translate * rotate;

    this->setPosition(result.getTranslation());
    this->setRotation(result.getRotation());
}

This works for a somewhat complex test case: a parent node w/ one child node, the child node is offset from the parent node, the parent node is rotated, and the child node is has its own local rotation. In this case, the drawing looks correct.

I'm running into problems when applying the above multiple times. For example, when I'm animating a rotating node (changing the rotation just a bit on each frame). Here, the position of the node becomes huge and it just zooms back to some very large position.

Any help or advice on how to address this is greatly appreciated.


texts: Hexagon collision detection for fast moving objects?

texts:
A object has a position and a speed vector. Usually only the position is used to check if two objects collide, this is problematic for very fast moving objects as it can happen that the object moves so fast that it is in front of the first object in the first collision check, and behind it in the second collision check.

Now there is also line based collision checks, in which you only check if the movement vector of each object intersects with the bounding-box of the other one. This can be seen as a expansion of a point. This only works though if the fast moving object is really small.

So my idea is, instead of expanding a point, why not expanding a rectangle? This results in a Hexagon.

Now, so far so good. But how do I actually check if two Hexagons of this kind intersect? Note that these are very specific Hexagon's.

Bonus Question:
Is it possible to calculate where exactly (or rather after how much time) the collision happened? This could be very useful to detect what really happened, like where and with how much power and to simulate how they moved in the time between the collision and the end of the frame.


texts: Mechanics to keep mobs and environment alive without using tons of memory?

texts:
I'm working on a server for a little mobile MMORPG.
This consists mainly of two important features: mobs and environment resources like trees, rocks etc.

The world is randomly generated and each time a player jumps to another grid, the server generates new mobs and resources for that area. Those are simply getting stored in dictionaries or lists, but are kept permanently in memory.

The problem here is that we need to find a way to save and load those entities without keeping them alive in memory for the rest of the day. This just causes huge memory usage which breaks the server at some point.

We also can't destroy those entities once a player leaves the area because players could abuse this by leaving/joining an area until rare mobs or resources spawn.

What mechanics would you recommend for dealing with this issue?


texts:
I think I am missing something really basic here..., I'm creating a 2D game in unity, and the UI Canvas (with the setting "Screen Space - Overlay") is blocking exactly a quarter of my workspace. I can not select any objects on the top right part of the screen.

Is there any fix to this?, or do I have to move the camera down half of the screen?

Thanks


texts:
I have two questions.

I'm working in a rogue-like and I've manage to implement a camera on the player, the camera shows just the players surroundings and is fixed in the side of the windows.

The problem is, when the player is close to the sides of the map there's a black space in the surface.
Like so:

1) How do I make the camera 'snap' to the side and don't go any further?

To draw the map

I took the Camera Rect positions [topleft and bottomright];
Converted it to World Position;
Iterate over it, with a enumerator too;
Did any lit/visited FOG calcunations with X and Y;
And Blited in the screen using the enumerators 'i' and 'j'.

Here's the code:

topleft = Map.toWorld(camera.rect.topleft)
bottomright = Map.toWorld(camera.rect.bottomright)
for i, x in enumerate(xrange(topleft[0], bottomright[0])):
    for j, y in enumerate(xrange(topleft[1], bottomright[1])):
        tile = mymap.tileAt(x, y)
        object = [obj for obj in Object.OBJECTS if obj.pos == (x,y)]
        if tile:
            lit = field_of_view.lit(x, y)
            visited = field_of_view.visited(x, y)
            graphic = tile.graphic
            if lit:
                color = tile.color
            elif visited:
                color = GRAY
            else:
                color = BLACK
            renderedgraphic = myfont.render(ch, 1, graphic)
            screen.blit(renderedgraphic, Map.toScreen((i + 1, j)))
        if object:
            Draw.drawObject(object[0], Map.toScreen((i + 1, j)))

I saw HERE a exemple of this but I couldn't adapt the code to my game because it uses sprites.

I also tried a different approach using just a camera.center position:

in short:

class Object():
    def update(self):
        self.relX = self.x - camera.x
        self.relY = self.y - camera.y

class Camera(Object):
    def update(self):
        self.x = self.relX = PLAYER.x
        self.y = self.relY = PLAYER.y

def MapDraw()
    for x in xrange(mymap.width):
        for y in xrange(mymap.height):
            ... # do fov stuff
            tile = Tile.At(x, y)  # get tile instance
            if tile:
                tile.update() # update it's relative position
                screen.blit(renderedgraphic, (tile.relX * TILESIZE, tile.relX * TILESIZE)) # blit the postion to it's relative position

This is what happens:

which leads to the next question:

2) Is there a better way to create a camera than using this 'hack' of enumerating?

EDIT: Answer

So after some struggles I tried the old, print whatever I had and found out that I could use the camera.x and camera.y for this.

first I check the distace between camera.x and the optional position in the sides, It was 3 for up and down, 7 to sides.

Then a couple of if-statements fixed this. But since int's aren't very consitent depending on mapsize, cameraview, I found that the camera.rect width and height divided by 2 in world position was the same as (7,3) I was looking for.

Anyway, here's the code for the camera.

def update(self):
    self.x, self.y = PLAYER.pos # center camera on player

    self.size = Map.toWorld((camera.rect.width, camera.rect.height)) ## get the ScreenSize of the rect and convert to World Position
    self.size[0] /= 2 # divided each one by two, because the player is in the center.
    self.size[1] /= 2

    if self.x < self.size[0]:  # right
        self.x = self.size[0]
    if self.y < self.size[1]: # up
        self.y = self.size[1]
    if self.x + self.size[0] > mymap.width: # left
        self.x = mymap.width- self.size[0]
    if self.y + self.size[1] > mymap.height: # down
        self.y = mymap.height-self.size[1]

    self.rect = pygame.Rect((self.x * TILESIZE) - CAMERA_WIDTH / 2,
                            (self.y * TILESIZE) - CAMERA_HEIGHT / 2, CAMERA_WIDTH, CAMERA_HEIGHT) # updated the rect

Thanks Tyyppi_77, even tho you provided a small answer, the way you phrased it was just right for me to get it.


texts: Collision Detection doesnt work because some things move more than 1px at a time

texts:
I'm writing a 2d scrolling game in javascript using canvas and since I'm limited to setInterval running at minimum once every ms, I need to have some objects moving at greater than 1 pixel a second. I have this for collision detection between objects:

// ** oversee collisions
collisionsInterval = setInterval(function() {

    // outter object
    for(i = 0; i < objectsToCollision.length; i++) {

        // inner object
        for(j = 0; j < objectsToCollision.length; j++) {

            // dont compare an object to itself
            if(i==j) continue;

            // check if they touch on x axis
            if(Math.abs(objectsToCollision[i].centerX - objectsToCollision[j].centerX) <= (objectsToCollision[i].halfWidth + objectsToCollision[j].halfWidth)) {

                // check if they touch on y axis
                if(Math.abs(objectsToCollision[i].centerY - objectsToCollision[j].centerY) <= (objectsToCollision[i].halfHeight + objectsToCollision[j].halfHeight)) {

                    // a collision was detected, do something useful
                    alert();

                }

            }

        }

    }
}, 1);

The problem is, since it wont alert() when two things are about to touch because my objects move at more than 1px at a time. The problem is, some objects might move 3px at a time, some might move at 8px at a time, and I also have gravity occurring so in the Y direction especially the velocity of my objects will really vary.

In my code above objectsToCollision is an array which contains all the objects I'm checking for collisions with. I've modelled what I've done so far after this https://gamedev.stackexchange.com/a/587 but it doesn't discuss how to solve the problem I'm experiencing!


texts: LibGDX: ActorGestureListener after change position

texts:
I have this code to get pan touch inside an Image and it works fine, but when I uncomment this line

img.setPosition(100, 100);

it doesn't work anymore, why?

Texture tex = new Texture(Gdx.files.internal("square.png"));
        final Image img = new Image(tex);
        //img.setPosition(100, 100);
        img.setSize(157,45);
        img.setColor(0,0,0,1f);

        img.addListener( new ActorGestureListener(){

            @Override
            public void pan(InputEvent event, float x, float y, float deltaX, float deltaY) {
                super.pan(event, x, y, deltaX, deltaY);

                int minX = (int)img.getX();
                int maxX = (int)img.getX()+(int)img.getWidth();
                int minY = (int)img.getY();
                int maxY = (int)img.getY()+(int)img.getHeight();

                if ((x>minX && x<maxX)&&(y>minY && y<maxY)){

                    Utils.print("PAN");
                }
            }
        });

        stage.addActor(img);


texts: If someone is using JNI then are they are true user of NDK (c++)?

texts: As someone involved in the hiring of engineers that must have experience using NDK (I work for Unity and support the VR/graphics groups), I see quite a few resumes of people who claim to be using NDK and c++ but at the same time reference the use of JNI.  I thought JNI basically made it possible to use NDK using java without using c++.  Any thoughts?  ( I know I am a recruiter but I am not using stack overflow to recruit, rather, better understand the very technologies I am working around every day.  I appreciate your help in advance )


texts: SteamWorks.Net for unity and inviting a friend to a multiplayer game

texts:
I'm trying to send an invitation to a steam friend and have it that when he accepts I create a PUN 2 room for both players and they can start their match. So far I've done this :

 protected Steamworks.Callback<GameRichPresenceJoinRequested_t> m_GameRichPresenceJoinRequested;

private void OnEnable()
{
    m_GameRichPresenceJoinRequested = Callback<GameRichPresenceJoinRequested_t>.Create(OnGameRichPresenceJoinRequested);
}

public void InviteFriend()
{

    SteamFriends.InviteUserToGame(steamFriendData.friendSteamId, "");
}

private void OnGameRichPresenceJoinRequested(GameRichPresenceJoinRequested_t pCallback)
{
     Debug.Log(pCallback.m_rgchConnect);
    Debug.Log("<color=green>Friend accepted the invite</color> ");
}

The invite is being sent to the correct friend and when he accepts it launches the game but I get no callback from that and thus have no way to place them in a room. What am I doing wrong ?


texts: How can I detect whether a point is moving in a circle?

texts:
I want to detect if my GameObject (Vector3 Point) being dragged by the player's finger is moving in a circular fashion.

I thought I could save the last 5 points every 10 frames and
join them by lines. Then I'd project them into a "defined" plane. From there, I can form the perpendicular bisectors of those line segments - to check where they are intersecting.

If every intersection point is very nearby - the finger is swiping in a circle!

Now I only need to check if the intersection point is close.

How can I check if they intersect? Or is there a better way to solve this?

Here's my code so far:

public LinkedList<Vector3> FingertipPoints;
public Transform Fingertip;

private void Start()
{
    FingertipPoints = new LinkedList<Vector3>();

    FingertipPoints.AddFirst(new Vector3(0, 0, 0));
    FingertipPoints.AddLast(new Vector3(0, 0, 0));
    FingertipPoints.AddLast(new Vector3(0, 0, 0));
    FingertipPoints.AddLast(new Vector3(0, 0, 0));
    FingertipPoints.AddLast(new Vector3(0, 0, 0));
}

[Range(1,60)]
public int FramesPerCheck = 10; // 6checks per sec
private int Frame;
// Update is called once per frame
void LateUpdate()
{
    Frame++;
    if (FramesPerCheck == Frame)
    {
        Frame = 0;
        FingertipPoints.RemoveLast();
        FingertipPoints.AddFirst(Fingertip.position);
    }

    //Get the Direction Vectors
    Vector3 V1 = FingertipPoints.First.Value - FingertipPoints.First.Next.Value;
    Vector3 V2 = FingertipPoints.First.Next.Value - FingertipPoints.First.Next.Next.Value;
    Vector3 V3 = FingertipPoints.First.Next.Next.Value - FingertipPoints.First.Next.Next.Next.Value;
    Vector3 V4 = FingertipPoints.First.Next.Next.Next.Value - FingertipPoints.Last.Value;

    //Project them on a plane
    V1 = Vector3.ProjectOnPlane(V1, Fingertip.forward);
    V2 = Vector3.ProjectOnPlane(V2, Fingertip.forward);
    V3 = Vector3.ProjectOnPlane(V3, Fingertip.forward);
    V4 = Vector3.ProjectOnPlane(V4, Fingertip.forward);

    //Get the Perpendicular Vectors (is this even right?)
    Vector3 C1 = Vector3.Cross(V1, Fingertip.forward);
    Vector3 C2 = Vector3.Cross(V1, Fingertip.forward);
    Vector3 C3 = Vector3.Cross(V1, Fingertip.forward);
    Vector3 C4 = Vector3.Cross(V1, Fingertip.forward);

    //???
    //How to check if they intersect nearby??
    //

}


texts: How can I exclude an object from receiving shadows?

texts:
I would like to make it so that a certain object is being excluded from receiving shadows.

While it itself should cast shadows onto other objects, it should not receive shadows from other objects.

How can I achieve this?

I'm using HDRP.

Seemingly, the option not to receive shadows is not present when using HDRP.

The MeshRenderer looks like this:


texts:
I'm working on a game which can't run at Full speed on some devices. On Tegra2, with many optimizations, performance is near 40 fps. The framerate is stable but animations aren't smooth enough, so i need a vsync.
With 2.3 Android SDK, we can use EGL library natively. So i try to use eglSwapInterval but no success. In this GDC Paper, it seems that Tegra2 can do it.

Ps: Thread.sleep() to force a constant FPS is not an acceptable solution


texts: How to calculate the distance from the camera to make a GameObject fill the screen?

texts: How do you calculate the distance from the camera so that a GameObject fills the screen? I.e. Without reaching out of the view and regardless of screen orientation.


texts: Why are there so few games compiled for 64-bit processors?

texts:
I noticed that I could not find any game that has a native 64-bit version on the x86 platform (there are some for platforms, obviously for example the Nintendo 64). In fact when I asked if the Allegro library supported 64-bit, the developers had no idea. When I tried to compile something for 64-bit my compiler failed (it was MingW, it wrote that 64-bit is not implemented).

This this make me wonder: why?

At least if the issue was 32-bit-only machines, you could make two .exes and run the more appropriate one or something. But I haven't even seen that, so why does nobody make 64-bit games?


texts: Is it better to have object components in a variable than using GetComponent everytime? (Unity c#)

texts:
Is this:

Rigidbody2D rb = GetComponent<Rigidbody2D>();

void Update()
{
    rb.AddForce(transform.up * 20 * Time.deltaTime);
}

Better than this?:

void Update()
{
    GetComponent<Rigidbody2D>().AddForce(transform.up * 20 * Time.deltaTime);
}

And can you please tell me why?


texts: I made sprite assets in Krita and I exported them as .PNG files. When I import the files into Unity assets, however, they become a lot darker than the original colors. So far, I haven't found the issue, and I was wondering what's going on?


texts:
I want to give players the ability to create and share bullet patterns for a shoot'em up.

The pattern scripts should have all the common programming stuff like loops, if/else, variables, and so on.

But in the end, I just want them to call a "spawn bullet at X, Y with Z angle and A speed" in the C++ game.

To spawn a circle of bullets, the user should only have to write a script with a for loop that goes from 0 to 360 and calls the spawn bullet function on every iteration.

I tried integrating AngelScript, but I am getting nowhere - it looks way to complex for a simple task like this one.

Is there an easy to integrate library that can solve my problem? Thanks.


texts: Unity ECS: How do I stop an entity from spawning twice?

texts:
I am implementing a flight dynamics model using Unity's built-in ECS package, Entities, and I keep running into one particular issue where the aircraft I'm trying to spawn gets converted into an entity twice.
Essentially, I have a singleton Monobehaviour that handles setting up the aircraft entity from a GameObject Prefab. Here's the script:
public class GameManager : MonoBehaviour
{

    private BlobAssetStore blobAssetStore;

    public static GameManager main;

    public GameObject planePrefab;

    public float zBound = 0.0f;
    public float throttleMaxBound = 1.0f;
    public float alphaMaxBound = 20.0f;
    public float bankMaxBound = 20.0f;
    public float flapMaxBound = 40.0f;
    public float throttleMinBound = 0.0f;
    public float alphaMinBound = 0.0f;
    public float bankMinBound = -20.0f;
    public float flapMinBound = 0.0f;

    public State state;
    public Properties prop;

    Entity planeEntityPrefab;
    EntityManager manager;

    private void Awake()
    {
        if (main != null && main != this)
        {
            Destroy(gameObject);
            return;
        }

        main = this;

        manager = World.DefaultGameObjectInjectionWorld.EntityManager;

        blobAssetStore = new BlobAssetStore();

        GameObjectConversionSettings settings = GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, blobAssetStore);
        planeEntityPrefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(planePrefab, settings);

        SpawnEntity();
    }

    private void OnDestroy()
    {
        blobAssetStore.Dispose();
    }

    void SpawnEntity()
    {
        Entity plane = manager.Instantiate(planeEntityPrefab);

        prop = new Properties(
            16.2f,
            10.9f,
            2.0f,
            0.0889f,        // slope of Cl-alpha curve
            0.178f,         // intercept of Cl-alpha curve
            -0.1f,          // post-stall slope of Cl-alpha curve
            3.2f,           // post-stall intercept of Cl-alpha curve
            16.0f,          // alpha when Cl=Clmax
            0.034f,         // parasite drag coefficient
            0.77f,          // induced drag efficiency coefficient
            1114.0f,
            119310.0f,
            40.0f,          // revolutions per second
            1.905f,
            1.83f,          //  propeller efficiency coefficient
            -1.32f          //  propeller efficiency coefficient
            );

        state = new State(
            0.0f,           // time
            0.0f,           // ODE results
            0.0f,
            0.0f,
            0.0f,
            0.0f,
            0.0f,
            0.0f,           // roll angle
            4.0f,           // pitch angle
            0.0f,           // throttle percentage
            0.0f            // flap deflection
            );

        float3 position = new float3(state.q1, state.q3, state.q5);

        manager.SetComponentData(plane, new Translation { Value = position });
    }

}

After a little bit of commenting here and there, I was able to determine that the following two lines are responsible for creating two separate entities, though the latter is the only one I'm capable of manipulating using the system. It's also worth mentioning that these two entities are virtually identical in the Entity Debugger, except for the fact that the first entity contains the "prefab" tag.
planeEntityPrefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(planePrefab, settings);

and...
Entity plane = manager.Instantiate(planeEntityPrefab);

Is there a way to spawn this entity without both showing up in the debugger or is this unavoidable? If not, is there a way to remove the entity with the "prefab" tag from the world?
Thanks! :)


texts: How to handle zooming? (Collision detection and speed are off)

texts:
I'm working on a bird's eye view 2D game. I want to zoom in/out based on the entity's speed (similar to GTA 1/2), but I'm struggling with the zooming.

To zoom, I simply scale all the entities by the zoom factor. One problem is that the hit tests are off (still happening with the smaller entities). The other problem is that the object is effectively moving slower (travelling a smaller distance when zoomed in, a larger one when zoomed out).

The only fix I can come up with is to scale all bounding boxes (used in collision detection) as well, and to adjust the speed based on the zoom factor. But that seems wasteful and complex (especially since I'm determining the zoom factor based on the speed).

Is there a better way?


texts: I can add event animation but I can't add keyframe?

texts:
I am trying to add animation to my UI panel but the problem is I can't add a keyframe to my animation (the button is grayed out). But I can add event animation (the button is not grayed out).

Here is the video of what's happening.
Anyone know how I can resolve my problem?