# Question
Title: Learning To Create Better Art (2D Games)
Until one of my games "makes it" big, or I get flooded with gold ingots, I will have to handle most or all of my game art myself. The crux of my question is: **how can I learn enough art to get beyond "programmer art" and into something I would actually be proud of?**

The focus of my question is 2D, not 3D.

I already have a good grip on:

* Photoshop/GIMP (image maniplation and creation)
* Flash (animation and drawing simple art)
* Simple drawing (by hand)
* Digitizing hand-drawn art
* Graphic design

However, games require complex and varied art; anything from backgrounds to icons, sprites, animation, and complex effects.

How do I bridge the gap, artistically? I already have the experience and confidence that I can do it; I only need to know the direction in which to put my modest efforts. I know this will pay off, especially in the long term. But I'm not sure *how* to get there.

Using existing art is something I already do, so please don't address that in your question.

# Answer
Lots and lots of practice. Most artists have been doodling and drawing since they learned how to hold a pen, you need to make up for lost time.

My suggestion: start with hand drawn things and other basics. Having a grip on how a program works vs bringing out the fullest in a program for art are two different things so look up some online tutorials and the like and get a couple of new techniques.

Next: practice like crazy. My favorite way to do this is set up a list of things to make, usually simple things - get about 20 to 30 subjects (this is pretty difficult and you wont always use all of them). Then get an alarm clock you can set for 10 - 15 minute intervals set it and in that time do your best to draw up a single object.

When the alarm goes off thats the end of that drawing. No 'but's. You now have the option to begin the same object again (10 to 15 minutes again) or start the process all over again. (Rinse, wash, repeat until you get the desired effect)
> 20 votes

# Answer
Wow, a topic I might be able to answer some, seeing how I've been drawing my entire life (despite this there's scant evidence of it online, given that I tend to not scan my results -- I'm a very analog artist... that, and I dislike showing what I consider failures... although I suppose it would be useful for some?).

Victor's answer addresses the first thing: hand drawing. Kimon Nicolaïdes is probably one of my greatest inspirations, and I'm sad that I never got the chance to study under him.

> "There is only one right way to learn to draw and that is a perfectly natural way. It has nothing to do with artifice or technique. It has nothing to do with aesthetics or conception. It has only to do with the act of correct observation, and by that I mean a physical contact with all sorts of objects through all the senses. If a student misses this step and does not practice it for at least his first five years, he has wasted most of his time and must necessarily go back and begin all over again."

It might sound extreme, but at the time (around 1936) it was a rather common idea (Harold Speed says something similar about practice); compared to today's idea that some people have a natural talent and the rest of us can never catch up, they believed that practice, practice and practice will get you there -- maybe a bit later, but eventually.

Personally, I don't believe in talent. Not in the way media plays it up these days. See, what everyone forgets is that even talented people practice, and there's even evidence that "special talent" doesn't really exist. (Which is good news for us mortals.)

Kimon Nicolaïdes's book, *"The Natural Way to Draw"*, is great, and I regularly re-read it and go through the study plan. Another great book is Harold Speed's *"The Practice & Science of Drawing"*; although it lacks a proper study plan it will give you several points of view on drawing and painting.

But, back to the topic at hand. As Victor said; you will want to practice hand drawing, because it will force you to learn perspective, shadows, textures and similar. Indeed, I don't think you should concern yourself overly much with the digital part yet (actually, I wouldn't be able to say since you've not said nor shown at what level you're at except "simple drawing", which is vague enough to not mean anything :P ); what you're training would be the base for everything else, and without a proper foundation you won't get very high. A quick word of advice: don't throw away your sketches/drawings. Save them -- at least for a few years; whenever you feel like you're not making progress, look at your first ones and you'll be astounded at what a distance you've come.

Hand drawing (and by this I mean with any media: charcoal, graphite, pastels, conté, silverpoint, pen and ink, marker, what have you) will probably be enough for pretty much everything except sprites (sprites could probably be made either by hand or by doing some fancy magic with 3d models -- it's not an area I will claim any expertise). Backgrounds can be made in any media, but watercolours are nice and very rewarding once you've learned them. I remember a few (10-15) years back when I asked a friend of mine how she did her amazing watercolour paintings... Because I'd never been able to produce anything like it; the answer was simple enough: practice, and letting the painting dry before continuing with the next part of it. Not getting the brush wet enough, or getting it too wet -- those parts were just part of the learning curve.

Once you're comfortable with hand drawing and painting/backgrounds, you're pretty much done with the analog part. Learning the software necessary for digitizing it is another step altogether, and one where the same thing repeats itself: practice, practice, practice. Find a good book or two dealing with your software of choice, and start learning (lynda.com has some great video tutorials for photoshop). It's less work, in my opinion, to learn how to digitize something -- software is just a tool, just like your silverpoint or graphite. It's a means to an end, it's not the end result itself. One thing though: when you start using software, get a pen tablet. The ipad and its ilk are horrible at the job, but wacom's intuos, cintiq or even bamboo pen&touch will be worth their weight in gold when it comes to digitizing or any job in photoshop. Mouse and keyboard are great input methods for a lot of things, but not drawing (besides, the pressure sensitivity alone is necessary for a majority of operations).

Alex Shepard's advise, "practice like crazy" is true. His way is one way, another is the way I learned it way back when: pick a subject -- easier things when you're starting out, then draw it for 30 minutes, **without looking at your sketchpad**. If you feel that you're losing the connection between subject and paper, take a second to glance at your sketch/drawing and reposition the pen. Because drawing is being able to draw what you see, not what you know is there.

Before people jump down my throat on the "it's less work to learn how to digitize something"; I realize that it might sound a bit arrogant. Learning the magic that photoshop can do requires a lot of practice and effort, and don't even get me started on 3D modelling because that's just way out there. But learning to use it passably is a *lot* easier than learning how to draw a person without it looking like it's from some forgotten horror show. In my opinion.
> 19 votes

# Answer
You should learn hand drawing. It's the very first skill you should have to draw anything at all. Learning to draw with hands you get notion of perspective, textures, shadows, etc.

Access websites like DeviantArt and CGTextures to get inspiration and see examples. Drawspace it's a great website that covers almost all aspects of drawing.

After you should be able to easily identify how you can do icons, sprites, animations, etc. With a scanner you can visualize your sketches on a screen and adapt it to your game.
> 9 votes

# Answer
To be honest, and I don't know if this is the "right" answer, but even to create quality 2D sprite art requires significant artistic ability and skills. That being said, it's nothing that can't be taught. The whole notion that it's all "natural talent" isn't true. You can start by learning how to draw with this tired and true book, The New Drawing on the Right Side of the Brain: A Course in Enhancing Creativity and Artistic Confidence. I think this book serves as a great launch board to develop artistic abilities (or at least I'm told). As with anything, it all comes down to practice, practice, practice.

Hopefully that's helpful. I feel your pain and I'm constantly in the same boat as you.
> 3 votes

# Answer
A good source of tutorials and practice methods can be found here.

From my limited experience and as pointed out in the accepted answers above, practice makes perfect.
> 3 votes

# Answer
I'm not so sure hand drawing is the way to go. I've found that I'm much better at art with the mouse than I am with hand drawn art. I think the key point is practice. If you're going to practice something a lot, it should be using the tools that you're likely going to be using: a mouse and keyboard.

I'm not an artist, but I think I'm getting better. I've been going through tutorials and modifying existing art. Both develop your knowledge of the tools. Recently when I was creating a texture for a 3D model, I neglected to save the texture file before closing Blender, textures and models are different save operations :(. Anyway, I had to re-create the entire texture from a blank canvas. I think this ended up being a good thing, it gave me practice. Based on that I'm likely going to create multiple versions of every texture, every time. Starting from scratch each time.

Good luck with your art!
> 1 votes

# Answer
In my weird opinion, impose so many constraints on yourself that you start achieving something which looks stylish just from the constraints! :-D

That's what I'd do if I get to go indie again and develop games (kind of my retirement dream). I used to do that as a teen a few decades ago drawing all my sprites and tiles and writing my own music. Back then I could kind of pull it off because the market was saturated heavily with very amateurish looking artwork and sound in CGA graphics, like this:

And that's really what got me into game development and design back then because many commercial games didn't really look like they were being illustrated and scored by pros. I felt like I could really compete with the commercial games out there just working from home and doing all my writing and music and graphics and programming. If I was born a couple of generations later, I might have never bothered, since commercial games these days have such amazing graphics and sound from teams of elite pros. They look like Hollywood films or something. I don't understand how the young ones these days find it in themselves to try to compete in the market now with all these huge games out there, though I'm happy to see that they still exist.

I did practice drawing a lot and took up a second visual arts major but was never good enough to consider it professionally. I got some sketches like this in ballpoint which is probably my best stuff (was easy to draw a sleeping subject):

I actually feel like I draw better with pen and ink than with graphite or charcoal and it's probably because it's a more constrained medium. Similarly when I tried to paint, I wasn't so good at it but I did better when I just scribbled digitally without trying to blend or anything like this:

And I think that's because I'm not good enough to paint with soft brushes and stuff, but if I constrain myself and just make myself scribble with something more like ink with hard lines, it's easier to hide the fact that I don't know what I'm doing. In fact typically the more I impose constraints on myself like forcing myself to draw with just black and white with ink and not all the subtle variations of value you can get with graphite or just scribbling with colors and not using soft brushes, I get better results because the constraints make it easier for someone without skill to do better. I ended up going down the programming path instead in continuation of all the game dev. Now I actually write software for artists to use with dreams of getting back into game dev but only because there is a resurgence of indie games again (I got sick of big company work).

But if I could go back to game development, I think that's the way to go. By constraints, I mean like using those big-blocky retro-style pixels for example. Or maybe you can even use 4-color CGA palettes! I actually like that... dunno, maybe I've got a heavy case of nostalgia glasses. But I tried processing some photos the other day to make them use 4-color palettes (but with blue and orange instead of purple and cyan), and I think they look cool:

So working with a 4-color palette is like a hardcore restriction but I could more easily hide the fact that I'm not such a good artist if I was drawing using such a palette, and especially if I was drawing blocky pixel graphics.

And maybe some people think that kind of strategy is overused these days in indie games with a retro-style resurgence, but dunno, I still find those games fun and they do end up communicating a consistent design language which leads to a sense of stylistic consistency.

So that's kind of my funky suggestion: impose so many constraints on yourself, basically tie your hands behind your back, until what you analogically draw with a pencil using just your mouth starts to look competent given all the restrictions you placed on yourself. The audience can't know you're not so good at drawing if they're watching you draw with your hands tied behind your back and drawing stuff with a pencil in your mouth, so to speak.

Similar kind of thing with music if you do that. I find if I just restrain myself a lot and keep it super simple like not use many instruments and maybe just like a bass line and some drums and sounds, I can kinda hide the fact that I'm drunk and have no idea what I'm doing like this: https://vocaroo.com/i/s1k7kLy45bi6. Of course a pro could probably tell, but maybe I could fluke it to ordinary people.

And my suggestion is really all about fluking -- not to produce great art or music or anything but something that might be able to fool a regular person and make them believe that you're not completely incompetent. And for that I find it helps to restrain yourself heavily, use super simple palettes, blocky graphics, very few instruments for music and sound, etc, just as I was forced to do back then when I was a teenager in the 80s due to technological restrictions, only now I would do it on purpose.
> 1 votes

---
Tags: 2d, art
---


# Question
Title: Game maker studio 2 Random spawn locations are not random
This is a redo of another question I asked. First I want to clarify that I am indeed using drag and drop. So saying something like "maybe switching to gml will fix your problem" is appreciated, but wont help. Anyway, this is what my block looks like:

## \[Create Instance\]

Object: object11 X: random(room\_width) Y: random(room\_height) Layer: "Instances\_2"

I have used this to randomly generate things in my games before, but I am now realizing it isn't very random. Every time it generates, it is in a random place, but it is that same random place every time I play. Does anybody know how to fix this? (sorry this was so long)

EDIT: this is NOT an exact duplicate. This is FAR different from my original. Please take that down. /

# Answer
> 1 votes
I am almost certain that this is a setting for debugging purposes. Debugging randomness is a pain so sometimes engines do a pseudo randomness with some sort of seed so that you can have consistency for debugging purposes.

I am not familiar with Game Maker but this would be my best bet. hope this helps.

(addition): Just from googling it seems that i am indeed correct and you should call `randomize()` at the start of your game.Click here to see the DOC.

---
Tags: game-design, game-maker, random, spawning
---


# Question
Title: Data not showing properly as per my field in the game
I made the game in android in this game i want first login and registration through JSON object. I have a API link where JSON Object send data from that url to the server but in my server i get the data something like this android.widget.EditText{b68c34b VFED..CL. ...........
android.widget.EditText{e1e3128 VFED..CL. ...........

Here is the code :-

RegistrationActivity.java

```
public class RegisterActivity extends Activity {
    private static final String TAG = RegisterActivity.class.getSimpleName();
    String url = "http://codexpertise.com/codexpertise.com/apitest/signup.php";
    private Button btnRegister;
    private Button btnLinkToLogin;
    private EditText inputFullName;
    private EditText inputEmail;
    private EditText inputPassword;
    private ProgressDialog pDialog;
    private SessionManager session;
    private SQLiteHandler db;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        inputFullName = (EditText) findViewById(R.id.name);
        inputEmail = (EditText) findViewById(R.id.email);
        inputPassword = (EditText) findViewById(R.id.password);
        btnRegister = (Button) findViewById(R.id.btnRegister);
        btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);

        // Progress dialog
//        pDialog = new ProgressDialog(this);
//        pDialog.setCancelable(false);

        // Session manager
        session = new SessionManager(getApplicationContext());

        // SQLite database handler
        db = new SQLiteHandler(getApplicationContext());

        // Check if user is already logged in or not
        if (session.isLoggedIn()) {
            // User is already logged in. Take him to main activity
            Intent intent = new Intent(RegisterActivity.this,
                    MainActivity.class);
            startActivity(intent);
            finish();
        }

        // Register Button Click event
        btnRegister.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                String name = inputFullName.getText().toString().trim();
                String email = inputEmail.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();
                compare_version();

                if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {
                } else {

                    Toast.makeText(getApplicationContext(),
                            "Please enter your details!", Toast.LENGTH_LONG)
                            .show();

                }
            }
        });

        // Link to Login Screen
        btnLinkToLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(),
                        LoginActivity.class);
                startActivity(i);
                finish();
            }
        });

    }

    /**
     * Function to store user in MySQL database will post params(tag, name,
     * email, password) to register url
     */
    private void registerUser(final String name, final String email,
                              final String password) {
        // Tag used to cancel the request
        String tag_string_req = "req_register";

        pDialog.setMessage("Registering ...");
        //  showDialog();

    }

    private void compare_version() {
        JSONObject parameters = new JSONObject();

        try {
            parameters.put("type", "signup");
            parameters.put("username", inputFullName);
            parameters.put("email", inputEmail);
            parameters.put("mobileno", "8871539601");
            parameters.put("password", inputPassword);

        } catch (JSONException e) {
        }
        JsonObjectRequest req = new JsonObjectRequest(Request.Method.POST, url, parameters,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONObject jsonObject = response;
                            String resp_code = jsonObject.getString("resp_code");
                            String resp_msg = jsonObject.getString("res_response");
                            System.out.println("response version =====" + response);

                            resp_code = "200";
                            if (resp_code.compareTo("200") == 0) {
                                System.out.println("response msg==" + resp_msg);
                                Toast.makeText(RegisterActivity.this, "response msg==" + resp_msg, Toast.LENGTH_SHORT).show();

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.e("Error: ", error.getMessage());

            }
        });
        MyApplication.getInstance().addToRequestQueue(req);
    }

```

MyApplication.java

```
public class MyApplication extends Application {

    public static final String TAG = MyApplication.class
            .getSimpleName();

    private RequestQueue mRequestQueue;

    private static MyApplication mInstance;
    /*deprecated*/

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized MyApplication getInstance() {
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }
    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

}

```

# Answer
The problem is here:

```
parameters.put("type", "signup");
parameters.put("username", inputFullName);
parameters.put("email", inputEmail);
parameters.put("mobileno", "8871539601");
parameters.put("password", inputPassword);

```

`inputFullName`, `inputEmail`, and `inputPassword` are `EditText` classes. They are not pure text. The fix is to get the text from these objects using `.getText()`:

```
parameters.put("type", "signup");
parameters.put("username", inputFullName.getText());
parameters.put("email", inputEmail.getText());
parameters.put("mobileno", "8871539601");
parameters.put("password", inputPassword.getText());

```

You might need to add `.toString()` as well:

```
parameters.put("type", "signup");
parameters.put("username", inputFullName.getText().toString());
parameters.put("email", inputEmail.getText().toString());
parameters.put("mobileno", "8871539601");
parameters.put("password", inputPassword.getText().toString());

```
> 0 votes

---
Tags: java, android, json
---


title: Unity collision help

text:
# Question
Title: Unity collision help
So my problem is this:

I have a block, which is used as a "pointer block" to show where a block will be spawned. It will be green if it isn't colliding anyone, meaning you can spawn a block. It gets red when it's colliding with something.

The pointer block is a trigger.

OnTriggerEnter gets called when the collider touches another collider. I want to know when another collider is in my pointer block, not when something is just on the edge of the colldier.

https://www.youtube.com/watch?v=0yNqSJ3yAxA&feature=youtu.be

# Answer
For 2D you can try Physics2d Overlap Circle or for 3d try Physics.OverlapBox()

Links:

https://docs.unity3d.com/ScriptReference/Physics2D.OverlapCircle.html

https://docs.unity3d.com/ScriptReference/Physics.OverlapBox.html
> 1 votes

# Answer
You have three options

You can shrink the collider of the pointer ever so slightly that it doesn't trigger from being adjacent.

Or

You can use Physics2D.OverlapCircle() or Physics.OverlapBox()

Or

You can use the Physics Matrix to exclude problem objects like terrain from the pointer interaction
> 1 votes

---
Tags: unity, collider
---


title: LIBGDX - group as child of an actor?

text:
# Question
Title: LIBGDX - group as child of an actor?
I've looked in forums, the doc, and the code, and I'm thinking this isn't currently possible, but maybe I'm missing something, so just to be sure: is there a way to set a group as child of and actor? or, in other words, how do I create a hierarchy of actors?

I'm trying to make sorta of a strategic game, and I have things like "empires", "kingdoms", ""cities", "buildings", "people", "objects", and I thought initially that maybe would be a good idea make these things actors. But I can't find anything like addActor inside Actor class, or addGroup, it seems there is no way for "kingdoms" to have"cities", for "cities" to have "buildings", for actors to have child actors or child groups.

# Answer
We don't know which things are **containers** and what they can contain. But let's assume your world work this way:

1. **Empires** can contains **Kingdoms**, but also **Cities** (which are not contained by any Kingdom but belongs to an empire) and even **Buildings** following the same reasoning.
2. **Kingdoms** can contains **Cities** and **Buildings** (again, buildings which are not contained by any City but belongs to a Kingdom)
3. **Cities** can contains **Buildings**, **Peoples** and **Objects**

Now we've got something. Everything that can *contains one or more type of Actors* is a **Group**.

So you'll add to the stage a bunch of Groups (Empires in my exemple) containg themselves other groups (Empire is a Group containing other Groups like Kingdoms, themselves containing other groups and so on..)

Hope it helps.
> 2 votes

---
Tags: java, libgdx, oop, objects, hierarchy
---


# Question
Title: Restore object right vector to horizontal position using quaternions
I'm fairly new in gamedev mathematics and i have a problem i cannot solve on my own.

I'm working on L-System tree generation engine and i'm having serious difficulities while trying to work out certain quaternion manipulation.
Every generated tree is a group of segments, growing from its parent starting from root. Every segments rotation is represented by quaternion. When child segment grows from its parent, i just multiply quaternion representing child rotation relative to parent by parent rotation quaternion. It works fine, however i need to implement another type of rotation to the child branch: bringing back segments right vector back to horizontal position. Is there any way i can solve this problem using quaternions?

I've tried manipulating quaternion converted to rotation matrix (extract quaternions front vector, recalculate right and up, modify rotation matrix and convert it to new quaternion) but i see that extracted informations about segment rotation are somehow corrupted, as it can be seen on screenshots ('tree' is at position (0,0,0), camera facing direction (0,-1,0)). Second one presents segment rotated 90 degrees about z axis (yaw). Expected vectors should be:
`Right: 0 1 0`
`Front: 1 0 0`
`Up: 0 0 1`

Is there something i do/understand wrong?

**Edit:**
I've checked again my vectors-to-matrix code part and turns out i've messed up vector rows with columns, that's why i was getting those strange results while trying different approaches!

I'm posting my working $ operation:

```
...
mat4 rotationMatrix = mat4_cast(transform.rotation);
vec3 front(rotationMatrix[0][1], rotationMatrix[1][1], rotationMatrix[2][1]);
vec3 worldDown = vec3(0, -1, 0);

vec3 right = normalize(cross(front, worldDown));
vec3 up = normalize(cross(front, right));

float matrix[16] = {
    right.x, front.x, up.x, 0,
    right.y, front.y, up.y, 0,
    right.z, front.z, up.z, 0,
    0,      0,       0,    0
};

mat4 newMatrix = make_mat4(matrix);
transform.rotation = quat(newMatrix);
...

```

# Answer
> 1 votes
Your code is missing. Did you do something like:

```
matrix44 mat = mat( q );
vec4 x = mat.getRow( 0 )
vec4 y = mat.getRow( 1 )
vec4 z = mat.getRow( 2 )
vec4 p = mat.getRow( 3 )

x.z = 0;
x.normalize()
y = z.cross( x )
z = x.cross( y )

matrix44 newmat;
newmat.setRow( 0,x );
newmat.setRow( 1,y );
newmat.setRow( 2,z );
newmat.setRow( 3,p );

quat newq = quat( newmat );

```

Note that this code will fail in edge case where x-axis points straight up (0,0,1).

---
Tags: mathematics, quaternion, glm
---


# Question
Title: Unity prefab functionality without files?
## Task

Display a UI list

---

## Assumptions

* Most UI parts only get their data during runtime
* UI parts need to be styled in the editor (= before runtime)
* UI editing should be done with real time preview in the editor
* The items in UI list should look the same

---

## Current solution

* Save a list item prototype as a prefab (drag&drop in the editor)
* Set that prefab as the reference in the script managing the list
* During runtime, instantiate the referenced prefab as needed

However, this needs a prefab file, which seems like an unnecessary additional point of failure. Just one annoying example: More often than not I forget to click "Apply" after editing such a prototype - which only becomes apparent at runtime.

---

## Suggested solution

* In the script managing the list, set the list item prototype as a reference
* On `Awake()`, create a prefab and store it in a class field
* During runtime, instantiate the prefab from the class field

---

## Question

I got the suggested solution *working* with`PrefabUtility.CreatePrefab()`. The only issue with that is that it still saves a prefab file. I currently just save those to a temp directory, but that is a workaround.
Is it possible to have a prefab which does not exist as a file, but still allows copying with `Instantiate()`?

# Answer
You can `Instantiate` any old `GameObject` you want (or more broadly, anything deriving from `UnityEngine.Object`) — it doesn't have to be a prefab for this to work.

So one possibility would be to have a source `GameObject` in your scene that you set to inactive, using `SetActive(false)`, so it doesn't render or update, and spawn copies of it with `Instantiate`, remembering to re-enable the copies with `SetActive(true)`

Here's a way you can keep track of this to minimize any risk of misuse:

```
public class PseudoPrefab : MonoBehaviour {
    // You can provide overrides for the various flavours of Instantiate,
    // taking position & rotation or world transform flags.
    public GameObject Instantiate(Transform parent) {
        // Clone ourselves, including the GameObject we're attached to.
        var clone = Instantiate<PseudoPrefab>(this, parent);

        var go = clone.gameObject;
        go.SetActive(true);

        // Strip off the PseudoPrefab script from the spawned copy.
        Destroy(clone);

        // Return a ready-to-use instance.
        return go;
    }

    void Start() {
        // Escape to the root, so we're not accidentally found
        // when traversing a particular container's children.
        transform.parent = null;
        gameObject.SetActive(false);
    }
}

```

Now your script that uses these items in a list can look something like this:

```
public class ListManager : MonoBehaviour {

    public PseudoPrefab listItemTemplate;
    public Transform listContainer;

    List<GameObject> _activeItems = new List<GameObject>();

    void AddItemToList() {
         _activeItems.Add(listItemTemplate.Instantiate(listContainer));
    }
    // ...
}

```

Your pseudo-prefab never lives in the same collection as your actual spawned instances, so you don't need to worry about accidentally mutating/deleting it when traversing the active copies.
> 1 votes

---
Tags: unity, instancing
---


title: Making MineCraft In 2D

text:
# Question
Title: Making MineCraft In 2D
I am making a 2D game that is based on Minecraft. I made the terrain but I just don't know how to do the collision between the player. I tied to draw the rectangles with a for loop and detect collision between the player player and the rectangles but when I run it it only detects collision between the last rectangle on the map and the player. Please help.

This is my code.

```
    import java.awt.Graphics;
    import java.awt.Rectangle;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.image.BufferedImage;
    import java.io.IOException;

    import javax.imageio.ImageIO;
    import javax.swing.ImageIcon;
    import javax.swing.JPanel;

    public class Gameplay extends JPanel implements ActionListener, KeyListener{
private BufferedImage player;
private BufferedImage block;
private BufferedImage dbImage;
private ImageIcon player2;
private Graphics dbg;
private int x = 0;
private int y = 0;
private double velX = 5.0f;
private double velY = 5.0f;
public Rectangle rectangle;
public Rectangle rectangle2;
private int[] xb = {0, 50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 650};
private int[] yb = {0, 50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 650};
//
public Gameplay(){
    addKeyListener(this);
    setFocusable(true);
}

public void paint(Graphics g){
    dbImage = (BufferedImage) createImage(getWidth(), getHeight());
    dbg = dbImage.getGraphics();
    paintComponent(dbg);
    g.drawImage(dbImage, 0, 0, this);
    repaint();
}
public void paintComponent(Graphics g){
    try {
        player = ImageIO.read(getClass().getResource("Player.png"));
        block = ImageIO.read(getClass().getResource("Grass.png"));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    drawBlock(g);
    g.drawImage(player, x, y, this);
    rectangle2 = new Rectangle(x, y, 50, 50);
    if(rectangle2.intersects(rectangle)){
        System.out.println("Hello");
    }
}

public void drawBlock(Graphics g){
    for(int first = 0; first < 10; first++){
        for(int second = 0; second < 10; second++){
            g.drawImage(block, xb[first], yb[second], this);
            rectangle = new Rectangle(xb[first], yb[second], 50, 50);
        }
    }

}

@Override
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void keyPressed(KeyEvent e) {
    if(e.getKeyCode() == KeyEvent.VK_UP){
        y += -velY;
    }
    else if(e.getKeyCode() == KeyEvent.VK_DOWN){
        y += velY;
    }
    else if(e.getKeyCode() == KeyEvent.VK_LEFT){
        x += -velX;
    }
    else if(e.getKeyCode() == KeyEvent.VK_RIGHT){
        x += velX;
    }

}

@Override
public void keyReleased(KeyEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void keyTyped(KeyEvent e) {
    // TODO Auto-generated method stub

}
     }

```

# Answer
Please don't load your images inside of your `paintComponent()` Method, but put them in global variables instead.

Also, you should keep a global list or an array of all the rectangles you have in your game. Something like `ArrayList<Rectangle> blockList`. Then, in your `paintComponent()` or whatever method (where you check for collisions), loop over the list and check for collisions between the player and the individual rectangle:

```
for(Rectangle r : blockList) {
   if (playerHitbox.intersects(r)) {
      // Handle collisions here.
   }
}

```

Generally, I would advise you to read about the basics of game programming first, like making a proper structure (don't put everything in one class), proper game loops etc.

What if you started with something simpler than a Minecraft recreation? Thats way more fun than struggling with something too complicated. Just follow the prinicple "KISS": **K**eep **I**t **S**imple and **S**tupid. It will get complicated by itself.

Cheers
> 4 votes

---
Tags: collision-detection
---


# Question
Title: C++: Smart pointers, Raw pointers, No Pointers?
Within the scope of developing games in C++, what are your preferred patterns in regard to use of pointers (be it none, raw, scoped, shared, or otherwise in between smart and dumb)?

You might consider

* object ownership
* ease of use
* copy policy
* overhead
* cyclic references
* target platform
* use with containers

# Answer
After having tried various approaches, today I find myself in alignment with the Google C++ Style Guide:

> If you actually need pointer semantics, scoped\_ptr is great. You should only use std::tr1::shared\_ptr under very specific conditions, such as when objects need to be held by STL containers. You should never use auto\_ptr. \[...\]
>
> Generally speaking, we prefer that we design code with clear object ownership. The clearest object ownership is obtained by using an object directly as a field or local variable, without using pointers at all. \[..\]
>
> Although they are not recommended, reference counted pointers are sometimes the simplest and most elegant way to solve a problem.
> 33 votes

# Answer
I also follow the "strong ownership" train of thought. I like to clearly delineate that "this class owns this member" when its appropriate.

I rarely use `shared_ptr`. If I do, I make liberal use of `weak_ptr` whenever I can so I can treat it like a handle to the object instead of increasing the reference count.

I use `scoped_ptr` all over the place. It shows obvious ownership. The only reason I don't just make objects like that a member is because you can forward declare them if they're in a scoped\_ptr.

If I need a list of objects, I use `ptr_vector`. It's more efficient and has fewer side effects than using `vector<shared_ptr>`. I think you might not be able to forward declare the type in the ptr\_vector (it's been a while), but the semantics of it make it worth it in my opinion. Basically if you remove an object from the list it gets deleted automatically. This also shows obvious ownership.

If I need reference to something, I try to make it a reference instead of a naked pointer. Sometimes this isn't practical (i.e. any time you need a reference after the object is constructed). Either way, references show obviously that you don't own the object, and if you're following shared pointer semantics everywhere else then naked pointers generally don't cause any additional confusion (especially if you follow a "no manual deletes" rule).

With this method, one iPhone game I worked on was able to only have a single `delete` call, and that was in the Obj-C to C++ bridge I wrote.

Generally I'm of the opinion that memory management is too important to leave to humans. If you can automate deletion, you should. If the overhead from shared\_ptr is too expensive at run time (assuming you turned off threading support, etc), you probably should be using something else (i.e. a bucket pattern) to get your dynamic allocations down.
> 25 votes

# Answer
Use the right tool for the job.

If your program can throw exceptions ensure your code is exception aware. Using smart pointers, RAII, and avoiding 2 phase construction are good starting points.

If you have cyclic references with no clear ownership semantics you can consider using a garbage collection library or refactoring your design.

Good libraries will allow you to code to the concept not the type so it shouldn't matter in most cases which kind of pointer you are using beyond resource management issues.

If you're working in a multi-threaded environment, make sure you understand if your object is potentially shared across threads. One of the main reasons to consider using boost::shared\_ptr or std::tr1::shared\_ptr is because it uses a thread-safe reference count.

If you're worried about the separate allocation of the reference counts there are many ways around this. Using the boost::shared\_ptr library you can pool allocate the reference counters or use boost::make\_shared (my preference) which allocates the object and the reference count in a single allocation thereby alleviating most cache miss concerns people have. You can avoid the performance hit of updating the reference count in performance critical code by holding a reference to the object at the topmost level and passing around direct references to the object.

If you need shared ownership but don't want to pay the cost of reference counting or garbage collection consider using immutable objects or a copy on write idiom.

Bear in mind that far and away your biggest performance wins are going to be at an architecture level, followed by an algorithm level, and while these low level concerns are very important they should be tackled only after you've addressed the major issues. If you're dealing with performance issues at the level of cache misses then you have a whole host of issues that you also have to be aware of like false sharing which have nothing to do with pointers per say.

If you're using smart pointers just to share resources like textures or models consider a more specialized library like Boost.Flyweight.

Once the new standard becomes adopted move semantics, rvalue references, and perfect forwarding will make working with expensive objects and containers much easier and more efficient. Until then don't store pointers with destructive copy semantics, such as auto\_ptr or unique\_ptr, in a Container (the standard concept). Consider using the Boost.Pointer Container library or storing shared ownership smart pointers in Containers. In performance critical code you can consider avoiding both of these in favor of intrusive containers such as those in Boost.Intrusive.

The target platform shouldn't really influence your decision too much. Embedded devices, smart phones, dumb phones, PCs, and consoles can all run the code just fine. Project requirements such as strict memory budgets or no dynamic allocation ever/after load are more valid concerns and should influence your choices.
> 10 votes

# Answer
If you're using C++0x, use `std::unique_ptr<T>`.

It has no performance overhead, unlike `std::shared_ptr<T>` which has reference counting overhead. A unique\_ptr *owns* its pointer, and you can transfer ownership around with C++0x's *move semantics*. You can't copy them - only move them.

It can also be used in containers, e.g. `std::vector<std::unique_ptr<T>>`, which is binary-compatible and identical in performance to `std::vector<T*>`, but will not leak memory if you erase elements or clear the vector. This also has better compatibility with STL algorithms than `ptr_vector`.

IMO for a lot of purposes this is an ideal container: random access, exception safe, prevents memory leaks, low overhead for vector reallocation (just shuffles around pointers behind the scenes). Very useful for many purposes.
> 4 votes

# Answer
It's good practice to document which classes owns what pointers. Preferably, you just use normal objects, and no pointers whenever you can.

However, when you need to keep track of resources, passing pointers is the only option. There are some cases:

* You get the pointer from somewhere else, but do not manage it: just use a normal pointer and document it so that no coder after you tries to delete it.
* You get the pointer from somewhere else, and you keep track of it: use a scoped\_ptr.
* You get the pointer from somewhere else, and you keep track of it but it needs a special method to delete it: use shared\_ptr with a custom delete method.
* You need the pointer in an STL container: it will be copied around so you need boost::shared\_ptr.
* Many classes share the pointer, and it's not clear who will delete it: shared\_ptr (the case above is actually a special case of this point).
* You create the pointer yourself and only you need it: if you really can't use a normal object: scoped\_ptr.
* You create the pointer and will share it with other classes: shared\_ptr.
* You create the pointer and pass it: use a normal pointer and document your interface so that the new owner knows that he should manage the resource himself!

I think that pretty much covers how I manage my resources right now. The memory cost of a pointer like shared\_ptr is generally twice the memory cost of a normal pointer. I don't think that this overhead is too big, but if you are low on resources you should consider designing your game to reduce the number of smart pointers. On other cases I just design to good principles like the bullets above and the profiler will tell me where I will need more speed.
> 3 votes

# Answer
When it comes to boost's pointers specifically, I think that they should be avoided as long as their implementation is not exactly what you need. They do come at a cost that is larger than anyone would initially expect. They provide an interface that allows you to skip vital and important parts of your memory and resourcement management.

When it comes to any software development I think that it is important to think about your data. It is very important how your data is represented in memory. The reason for this is that CPU-speed has been increasing at a much greater rate than memory-access time. This often makes the memory-caches the main bottleneck of most modern computer games. By having your data aligned linearly in memory according to access order is much friendlier to the cache. This kind of solutions often lead to cleaner designs, simpler code and definetly code that is more easy to debug. Smart pointers easily lead to frequent dynamic memory allocations of resources, this causes them to be scattered all over the memory.

This is not a premature optimization, it's a healthy decision that can and should be taken as early as possible. It's a question of architectural understanding of the hardware that your software will run on and it is important.

Edit: There are a few things to consider regarding the performance of shared-pointers:

* The reference counter is heap allocated.
* If you use thread-safety enabled, reference counting is done via interlocked operations.
* Passing the pointer by value modifies reference count, which means interlocked operations most likely using random access in memory (locks + likely cache miss).
> 1 votes

# Answer
I tend to use smart pointers everywhere. I am not sure if this is a totally good idea, but I am lazy, and I cannot see any real downside \[except if I wanted to do some C-style pointer arithmetic\]. I use boost::shared\_ptr because I know I can copy it around - if two entities share an image, then if one dies the other shouldn't lose the image too.

The downside of this is if one object deletes something it points to and owns, but something else is also pointing to it, then it isn't deleted.
> 0 votes

# Answer
The benefits of memory management and documentation provided by good smart pointers mean I use them regularly. However when the profiler pipes up and tells me a particuarly usage is costing me, I'll revert back to more neolithic pointer management.
> 0 votes

# Answer
I'm old, oldskool, and a cycle counter. In my own work I use raw pointers and no dynamic allocations at runtime (except the pools themselves). Everything is pooled, and ownership is very strict and never transferable, if really needed I write a custom small block allocator. I make sure that there is a state during game for every pool to clear itself. When things get hairyI do wrap objects in handles so I can relocate them, but I'd rather not. Containers are custom and extremely bare bones. I also don't reuse code.
While I would never argue the virtue of all the smart pointers and containers and iterators and whatnot, I am known for being able to code extremely fast (and reasonably reliable - although it's not advisable for others to jump into my code for somewhat obvious reasons, like heart-attacks and perpetual nightmares).
At work, of course, all is different, unless I am prototyping, which I thankfully get to do a lot.
> 0 votes

# Answer
Almost none though this is admittedly a strange answer, and probably nowhere close to suitable for everyone.

But I have found it so much more useful in my personal case to store all instances of a particular type in a central, random-access sequence (thread-safe), and instead to work with 32-bit indices (relative addresses, i.e.), rather than absolute pointers.

For a start:

1. It halves the memory requirements of the analogical pointer on 64-bit platforms. So far I've never needed more than ~4.29 billion instances of a particular data type.
2. It makes sure that all instances of a particular type, `T`, will never be too scattered in memory. That tends to reduce cache misses for all kinds of access patterns, even traversing linked structures like trees if the nodes are linked together using indices rather than pointers.
3. Parallel data becomes easy to associate using cheap parallel arrays (or sparse arrays) instead of trees or hash tables.
4. Set intersections can be found in linear-time or better using, say, a parallel bitset.
5. We can radix sort the indices and get a very cache-friendly sequential access pattern.
6. We can keep track of how many instances how of a particular data type have been allocated.
7. Minimizes the number of places that have to deal with things like exception-safety, if you care about that sort of thing.

That said, convenience is a downside as well as type safety. We can't access an instance of `T` without having access to *both* container *and* index. And a plain old `int32_t` tells us nothing about what data type it refers to, so there's no type safety. We could accidentally try to access a `Bar` using an index to `Foo`. To mitigate the second problem I often do this sort of thing:

```
struct FooIndex
{
    int32_t index;
};

```

Which seems kind of silly but it gives me back the type safety so that people can't accidentally try to access a `Bar` through an index to `Foo` without a compiler error. For the convenience side, I just accept the slight inconvenience.

Another thing which could be a major inconvenience for people is that I can't use OOP-style inheritance-based polymorphism, since that would call for a base pointer which can point to all kinds of different subtypes with different size and alignment requirements. But I don't use inheritance much these days -- prefer the ECS approach.

As for `shared_ptr`, I try not to use it so much. Most of the time I don't find it makes sense to share ownership, and doing so haphazardly can lead to logical leaks. Often at least at a high-level, one thing tends to belong to one thing. Where I often found it tempting to use `shared_ptr` was extending the lifetime of an object in places that didn't really deal with ownership so much, like just a local function in a thread to make sure the object isn't destroyed before the thread is finished using it.

To tackle that problem, instead of using `shared_ptr` or GC or anything like that, I often favor short-lived tasks running from a thread pool, and make it so if that thread requests to destroy an object, that the actual destruction is deferred to a safe time when the system can ensure that no thread needs to access said object type.

I do still sometimes end up using ref-counting but treat it like a last resort strategy. And there are a few cases where it genuinely makes sense to share ownership, like the implementation of a persistent data structure, and there I do find it makes perfect sense to reach for `shared_ptr` right away.

So anyway, I mostly use indices, and use both raw and smart pointers sparingly. I like indices and the kinds of doors they open up when you know your objects are stored contiguously, and not scattered across the memory space.
> 0 votes

---
Tags: c++, software-engineering
---


# Question
Title: Oculus Rift on Motion Simulator Platform
I currently develop a VR environment for an existing (physically) large motion simulator platform. The user can sit on this motion platform and gets accelerated and tilted to induce the feeling of motion in a research car simulator environment. The Oculus Rift positional tracker is already mounted on the moving platform in front of the user, just as you would do on your PC.

The 3D engine I currently use is Unity 5.3. The rotation angles and linear accelerations of the platform are already fed into Unity. The results are however not what I aimed for. While the rotational compensation works well as long as we tilt the platform, once the angular velocity goes to zero, the tracker gets reset without being called by me or firing an event that it has done so. The linear acceleration compensation always jitters around the true resting point.

I already tried using the native Unity VR implementation and also the Oculus plugin. However, the sensor fusion is not available at this level. The Oculus forums have many topics about this problem, but I could not find any solutions.

**Are there alternatives that one might try in order to use the Oculus on a moving platform?**

What I would like to do ideally is to subtract the induced motion from the Oculus sensor data before getting processed further. I already considered patching e.g. LibOVR, but I could not find any helpful Sensor fusion related functions there, either.

# Answer
> 1 votes
I can't give a definitive answer, but my suggestion is that you experiment with headsets from different manufacturers (Microsoft Mixed Reality, VIVE, and potentially mobile-phone based ones), and see if the reset issue occurs with them as well. My hunch is that the reset issue is Oculus specific, and is not a trait of VR systems in general.

As an example of a successful project that is similar, see the paper CarVR: Enabling In-Car Virtual Reality Entertainment. It talks about using VR in a moving car.

Like what you have done, they have put an IMU in the platform (the car), and subtract that data from the rendering in Unity. It seems they were successful in their tests, and do not mention reset or other issues. In their research, they specifically used Samsung GearVR with a Samsung Galaxy S6 Edge as the VR device.

Another approach would be to use a VR system that relies on cameras to determine orientation. Theoretically, a camera-only system could fully manage all head motion and orientation if sufficiently powerful. Microsoft's Mixed Reality headsets do this to some extent. See this Microsoft page on tracking for some background on this. That said, I believe that Microsoft's system is a mix of camera tracking with integrated sensors for a hybrid approach.

---
Tags: unity, motion, oculus
---


# Question
Title: How to create enemy "flash-light" for 2D game?
I'm developing a 2D stealth game but I cannot figure out how to create something like a torch (flashlight) that the enemies hold and look around with.Any help? Also, if relevant, I'm using MonoGame.

# Answer
> 1 votes
If I have understood your question correctly, what you want to have is e.g. a "dark map", where you can have a circular area whoch is brighter from the torch.

Now, since I don't really know Monogame, you could fill your screen with a half transparent, dark color over your normal map. Then, you probably could draw a sprite over it with a gradient from the aforementioned color to a fully transparent color. You'd have to use subtractive blending to clear the area from the dark color.

I mean something like that:

This was created using an image editor, I took the image, filled it with a 65% yellow-brownish color, then made a selection around the torch source, deleted it and added a gradient from fully transparent to the previous color. For your game you could also create this image in a pixel editor and then just draw it - either clearing the area below, or using subtractive blending if thats possible in monogame.

For example in JavaFX, you can clear a rectangle of a drawing canvas with the method clearRect(), for reference.

Cheers

---
Tags: monogame
---


# Question
Title: How do I move a target camera along Y axis
I have a camera that rotates around a target point on mouse move. How can I move the camera's position upwards/downwards related to the target position? So when camera is moved upwards the object is seen to go downwards and opposite.

I was trying to change target vector y, camera position vector y but none of it really worked:

```
void Camera::move(float dir)
{
    m_target.y += dir;
}

```

and

```
void Camera::move(float dir)
{
    m_pos.y += dir;
}

```

I got to confess I'm not strong at linear algebra and most likely that's the reason why I don't understand it well. I was trying to google it however all results are about forward/backward camera movement which is as easy as to change `m_radius` class member.

My camera's position is described by radius, theta and phi angles (spherical coordinates it's called, I guess).

This is how I set position `m_pos`and then call `XMMatrixLookAtLH`

```
setPosition(m_target.x + m_radius * cosf(m_theta) * cosf(m_phi), m_target.y + m_radius * sinf(m_theta), m_target.z + m_radius * cosf(m_theta) * sinf(m_phi));
setLookAt(XMLoadFloat3(&m_pos), XMVectorZero(), XMLoadFloat3(&m_up));

```

Target is always set in origin (0, 0, 0) because all my model data is loaded related to the origin. I added target position effect to the `setPosition()` method just in case I will ever need to change it.

# Answer
> 0 votes
If I understood what you wanted to do correctly, you will have to do some vector addition. Create a vertical vector B of length equal to the distance you want to move up (say (0,2,0) for a vertical distance of 2), and add it to the pos vector. Set your new pos vector to the result of the addition.

If you want to visualize it:

Here A would be your pos vector and B your upward movement. Note that B here is not vertical, it's just an example.

---
Tags: c++, directx, camera, vector
---


title: Using Jpegs as backgrounds

text:
# Question
Title: Using Jpegs as backgrounds
I am working on a project where I need to add rendered text over a jpeg background image. I have my scene completely set up but when I render all I get is the text, there is no background image. The business name text should be rendering in gold over the background image.

# Answer
> 1 votes
Setting a background image in the viewport is only for reference while modeling.

Two ways to get a background image in your render are to use the import image as planes addon and align the camera so the plane fills the camera view. Another is using an alpha over compositing node to composite your text over the image.

# Answer
> 0 votes
Here's another post that contains possible solutions

Also, you'll notice that this post is on blender.stackexchange.com. Questions related specifically to blender might be better asked and receive faster more accurate answers over there.

---
Tags: blender
---


# Question
Title: How to handle wearable items on character
I am developing a text/image based rpg game with javascript.I have questions about how to handle wearable items on character.

Lets say that there are many(naked no item) character types(images)and there are many items.When a player equips a sword and a helmet,do i have to make images of all item combinations with all base character types import them into the game then check all of them with if elses then display correct picture on screen ? or is there any other way

# Answer
> 2 votes
When you make separate spritesheets for *every* possible combination, the number of art assets you need to create increases exponentially with the numbers of items in your game. This will soon becomes impossible to do.

The usual technique applied here is called **paperdolling**.

You create separate spritesheets for the "naked" character, one for each armor, each weapon and each headgear. These spritesheets only contain the mentioned object. All other pixels are transparent. Then at runtime when you draw all the sprites of the character one after another to create the composite character sprite.

This, of course, means that you can only share spritesheets between characters as long as they use the same animations.

As a performance optimization you can use a technique called "sprite batching". Create a new off-screen canvas for each character, blit all the spritesheets of that character onto it, and use that canvas as a source image for drawing the character in your render loop. That way drawing a character only requires one `drawImage` call and not an additional one for each piece of equipment.

---
Tags: character
---


title: ECS: AI components and systems

text:
# Question
Title: ECS: AI components and systems
I'm trying to find the best design pattern for my AI code using an ECS.

Right now the entities that act as CPU-controlled have components like:

* WeaponComponent
* ChargeComponent
* MovementComponent
* AIControlledComponent

...

I have an *AIControlSystem* that goes over the entities that have the *AIControlledComponent* and during each frame switches the mental state of the entity based on some rules like "can I see the player?", "can I move somewhere safe?", etc...

Based on the mental state, this systems adds a set of actions to a queue.

Then the queue is being consumed and evaluated. An action like "Attack" is actually calling a method of the system that checks whether the entity has a *WeaponComponent* attached and fires, or if there's a *ChargeComponent* it charges at the player. This way, those methods tend to grow as the kind of enemies and actions grow and the code starts to become a mess as there are way too many checks and paths to follow.

I thought I could refactor the code splitting it up based on the kind of enemy (aka an enemy that has a Weapon won't be able to Charge and vice versa) but then I'd have to have a base AIControlSystem and inherit from that and specialize it based on the components attached to the entities. This would result in pretty much one new system per enemy kind and it doesn't really look like a good solution.

I thought about diverging from the pure ECS pattern of keeping components as data containers only and actually implement those methods in the components themselves so that I can have a base AIControlledComponent with the virtual methods that interpret the queue of actions and inherit a new component from that one for each enemy type. It looks a bit better for code organization but I'm not sure that making this kind of exception is a good idea.

Is there any other way to keep the code under control and at the same time have the flexibility needed?

# Answer
> 3 votes
> The problem I see with this approach is that the AI module cannot be easily decoupled from the components attached to the entities. To evaluate a tree or run a state machine, it needs to know information from the entity being used so it actually needs to pull information like the inventory, the weapons available, the position, etc from the actual components.

Observe any animal: its nervous system is tailored to its tasks. Birds have sharp eyesight to seek food and threats, and the ability to rectify their posture and attain lift when falling, instinctively. And a human mind is wired to be very aware of the capabilities of its own body, its level of health, hunger, cold, not to mention presence or absence of limbs... you get the drift. If we use RL as a basis for object modelling, there is no fault in having the mind / AI be aware of such aspects as location, posture, health, held items, capabilities etc. What you *could* do is abstract missile weapons to be treated as a generic type. This leads to nice abstract AI logic like `if holding missile weapon in hand, attempt to fire`. A brain in a jar, OTOH, is exactly that - provided it knows it is disembodied, it also knows that attempting to climb out of the jar is futile. That is: have AI check for `null` components and proceed accordingly.

> I thought about diverging from the pure ECS pattern of keeping components as data containers only and actually implement those methods in the components themselves so that I can have a base AIControlledComponent

> I thought I could refactor the code splitting it up based on the kind of enemy (aka an enemy that has a Weapon won't be able to Charge and vice versa) but then I'd have to have a base AIControlSystem and inherit from that and specialize it based on the components attached to the entities. This would result in pretty much one new system per enemy kind and it doesn't really look like a good solution.

1. Keeping them as pure data items or not isn't the crucial issue; but your hierarchy of control is, and in that regard, the "pure" approach is often pushed as "sound practice". In truth it makes little difference whether the logic is on `this` or on something else (like a higher level controller). Just don't let the non-pure method turn your code to spaghetti. (In my experience, the pure approach has more monolithic code and makes it harder to make mistakes in the local object that don't agree with global control mechanisms - I always find clear, top-down approaches best.)
2. Some will disagree, but generally speaking, the entire idea behind ECS is object composition vs. inheritance. I'm not saying you couldn't use inheritance on some of your component types, but I would avoid it inasmuch as possible.

> Based on the mental state, this systems adds a set of actions to a queue. Then the queue is being consumed and evaluated. An action like "Attack" is actually calling a method of the system that checks whether the entity has a WeaponComponent attached and fires, or if there's a ChargeComponent it charges at the player.

I think this is central to your crisis. Your AI mind component should, knowing the full state of its own body and relevant parts of the external environment, never have queued "Attack" unless circumstances were ideal in the first place. For example, imagine you suddenly realised you didn't have a rifle in your hands after all, but a pen-knife. Would you still charge and attack, especially if the enemy were all armed with guns? I doubt it. It is tactically very different and in your present code, that distinction is not being made by your AI component before queueing the action in question.

> whether the entity has a WeaponComponent attached and fires, or if there's a ChargeComponent it charges at the player

This is also totally wrong to my mind. Why is `Charge` a `Component`? Surely it's just a verb, a type of action that any AI can choose to take, even if it has a missile weapon in hand? Surely the only thing that would prevent a charge is speed / encumberment, and those should be factors handled in the AI mind's decision as to what actions to take, based on entity's own physical status? But... OK.

The last 2 paragraphs give you the gist of your problems: you're leaving what should be crucial, first class *AI(!)* decisions made before queueing occurs, to become last minute, second class decisions made at the moment when your entity should either be pulling the trigger or running for its life. Doesn't sound very decisive to me, and I can imagine what happens to real soldiers who fight this way. Further to that, I'm not even sure if the AI is involved at all in your "second-guessing" phase, or whether those are just other components making those final decisions as to whether to act or not... if the latter, you need to change that to single-phase AI decision-handling, and queue actions based on certainties.

**Suggest you consolidate your AI processing to happen entirely *before* that queueing begins.** The problems here are all in your AI strategy, and not in your ECS usage, insofar as I can see.

# Answer
> 1 votes
Use a behavior tree instead for sure. Each behavior tree, you make it specific to the "actor". Each actor has the components that it has and since the BT is attached to it, the nodes of the BT will know the components and can query for them. Now your BT knows exactly what the actor has at it's disposal and can work with it.

So for example you have a bird BT that you attach to bird entities that have the fly component. You have specific flying leaf/action node that you use in this BT when you want to get this bird AI around. Since the action node is fly, then it's expecting the entity it's attached to, to have the fly component. It will query to get it, and will work with it.

Now your entities that have components attached and a BT attached can have nodes in that BT work on it's components.

---
Tags: ai, entity-system, component-based
---


# Question
Title: How to load/unload chunks data where view port is currently focused on?
I have a 2D tile based engine with infinite procedural chunk generation.
But I can't invent an algorithm, that will fill only chunk tiles on view port (and destroy old). Pls help
ViewPort size can changing on the fly (2 - 100)
I can't load all chunks completely, because I need to analyze the tiles in the visibility zone

```
class Map {
  public List<Chunk> { get; set; }
  public int viewPortWidth = 2 ... 100;
  public int viewPortHeight = viewPortWidth;
  public Vector2Int playerPosition { get; set; }
}

class Chunk {
  Tile[] Tiles { get; set; }
  public int chunkWidth = 16;
  public int chunkHeight = chunkWidth;

  public Chunk(int _leftX, int _bottomY)
  {
    for (int y = 0; y < chunkHeight; y++)
    {
        for (int x = 0; x < chunkWidth; x++)
        {
            randomNumberGenerator.InitState(x + _leftX, y + _bottomY);
            chunk[x, y] = randomNumberGenerator.Range(100);
            Tiles.Add[chunk[x, y]];
        }
     }
}

```

# Answer
If your viewport is just a rectangle, and your chunks are arranged in a 2D grid, you can simply convert your viewport's corners into chunk coordinates (that is, fine which chunk each viewport corner is in); assuming your viewport position is in pixels, this might look like:

```
int chunkX = viewport.X / (tileSizeInPixels.X * tilesPerChunkX);
int chunkY = viewport.Y / (tileSizeInPixels.Y * tilesPerChunkY);

```

The grid of chunks spanned by the four chunk coordinates you find in this fashion is the set of all chunks visible in the viewport. You can potentially unload all chunks outside that set.

In practice you may want to expand the rectangle you use for computing this to something larger than the viewport, to account for the fact that loading/unloading chunks takes time and the player may be able to move the viewport fast enough to outpace this IO.

In your example it looks like you're actually trying to unload *individual tiles* from a chunk, which is still doable with the same approach as above (just compute tile positions instead of chunk positions) but seems, to me, to defeat a large part of why you'd bother organizing tiles into chunks in the first place.
> 1 votes

---
Tags: unity, procedural-generation, tilemap, viewport
---


# Question
Title: How to make player move only along the line
I am using Line Renderer to draw a line on 2D scene using a path of multiple Transforms. And I want player to move along the line without the ability to get off it, like if he was on a rail. The simplest method I can see is setting a number of invisible walls along the line, so the player couldn't physically move away from the line. But maybe there's better method?

# Answer
> 3 votes
You have a line with a starting point `pStart` and an end point `pEnd`.

To get any point on a line, use the linear function equation:

```
y = m * x + b

```

Now you have to get the slope of the line which is simply `m = (pEnd.x - pStart.x) / (pEnd.y - pStart.y)`. Then, you can calculate every `x` and `y` pair on the line by simply putting in a value for `x`. So far for the mathematical background, now to the practical implementation (this is all pseudocode).

In your case, you can build a slope vector for the line

```
slopeX = pEnd.x - pStart.x
slopeY = pEnd.y - pStart.y

```

and then normalize it (get it to a lenght of one):

```
slopeLength = squareroot((slopeX * slopeX) + (slopeY * slopeY))
slopeNormX = slopeX / slopeLength
slopeNormY = slopeY / slopeLength

```

Now you know in which direction you have to move your player each time step. To move him, simply do the following:

```
playerX += slopeNormX * deltaTime
playerY += slopeNormY * deltaTime

```

Also, don't forget to check wether the player is still on the line:

```
playerX*playerX > pEnd.x*pEnd.x && playerY*playerY > pEnd.y*pEnd.y

```

We have to square the positions here because we don't know wether the coordinates are positive or negative (`abs()` would be too slow).

Cheers

---
Tags: unity, c#
---


# Question
Title: Creating an Item to be taken, then used latter in C# for a texted base-game
I need to create an item that the player decides to take and then use at a later time.

Really I am looking for a command to open up a backpack that lists the items the player has collected. then the player can return to the previous state. This is for a text-based game.

I also need to know how to define an item I create, that can be used.

# Answer
> 1 votes
I don't have working knowledge of C# and it sounds a little bit like you might be fishing for someone to just give you code that'll work here--but I'll give some broad-strokes advice and **pseudocode** in the hope that you're really just looking for a little direction. For simplicity, I'll assume you don't mean for the backpack to be another item the user could take or leave, but rather for the backpack to be equivalent to the player's inventory.

The first big task is figuring out how to represent the "item". There are two main approaches.

If all of your items all basically do the same thing (i.e., all of your items are food the player can eat, or weapons they can use), you could represent them with a struct or a compound data type like a dictionary. Either of these could hold string values like the name of the item, a longer description of it, and numeric values like how heavy or powerful a weapon is, or how many hit-points the food might heal.

```
struct Food {
   string name;
   string description;
   integer heals;
   integer weight;
};

struct Food banana = Food("banana", "a ripe banana", 10, 1);

```

If you're going to have items that do all kinds of different things, you probably want to write an item class of some sort that defines behavior all of your items should have, and write individual items that inherit the generic item and customize it.

```
class Item {
    string name;
    string description;
    integer weight;
};

class Food : Item {
    boolean edible = true;
    integer spoil_time = -1;
    integer max_heal;

    integer heals(){
        if(spoil_time == 0){
            return -max_heal;
        } else {
            return max_heal;
        }
    }

    void age(){
        if(spoil_time > 0){
            spoil_time--;
            if(spoil_time == 0){
                print("The "+name+" begins to stink.");
                description = description + " (spoiled)";
            }
        }
    }
};

class Banana : Food {
    string name = "banana";
    string description = "a banana";
    integer max_heal = 10;
    integer spoil_time = 600;
    boolean edible = false;

    void peel(){
        print("You peel the banana.");
        edible = true;
    }
}

```

Regardless of whether you represent the items as a data type or a class, you can store the items in a "list" type. You'll have one at least one list for the player's inventory. If you want the player to be able to "drop" an item and take it again later, you also want each "room" or "location" in your game to have its own inventory list.

You'll also need commands to work with these. Here are a few examples:

```
boolean eat(string what){
    foreach(item in player.inventory){
        if(item.name == what){
            if(item.edible){
                player.adjust_hp(item.heals());
                print("You eat "+item.description);
                player.inventory_weight -= item.weight;
                return true;
            } else {
                print("You can't eat that!");
                return false;
            }
        }
    }
    print("Your stomach grumbles as you search in vain.");
    return false;
}

void inventory(){
    print("You open up the backpack and see:")
    foreach(item in player.inventory){
        print(item.description);
    }
}

boolean take(string what){
    foreach(item in player.inventory){
        if(item.name == what){
            integer new_weight = player.inventory_weight + item.weight;
            if( new_weight > player.max_inventory_weight ){
                player.inventory_weight = new_weight;
                print("You pick up "+item.description);
                return true;
            } else {
                print("You can't carry any more!");
                return false;
            }
        }
    }
    print("There's no "+what+" to take.");
    return false;
}

```

If you'd like the player to be able to look at or inspect these items, you probably need to modify your existing look command to also check the player's inventory and possibly the room's inventory.

---
Tags: c#, text-based
---


# Question
Title: What is the cause of this lighting artifact on my dynamic terrain mesh?
I am generating my own terrain mesh in Unity, using pseudo-random noise to determine the height. I construct the mesh using quads, each quad is composed of two triangles.

All seems to be going well, except the terrain does not look right - the quads are very visible. You can see the outline of them on the surface, but I haven't seen this effect before elsewhere. I feel that something is wrong with either my normals or my UV's. I am using just one white directional light.

Dynamic Terrain http://www.spannerworx.com/images/terrain.png

I thought the issue was with the normals, so I stopped calling RecalculateNormals and manually calculated the normal for every vertex using the averaged normal of the sum of each triangle touching that vertex. This was a lot of effort, but made no effect and ended up looking just the same.

Has anyone else seen this dynamic mesh effect before and maybe make some suggestions as to how I could try resolve this?

Just to clarify, I am already generating the triangles myself, two per quad. I do it like this:

```
for (int t = 0; t < quadCount; t++)
{
    int x = t / (Samples - 1);
    int z = t % (Samples - 1);

    // Calculate quad corner indexes
    int indexBR = CalculateIndex(x + 1, z);
    int indexBL = CalculateIndex(x, z);
    int indexTL = CalculateIndex(x, z + 1);
    int indexTR = CalculateIndex(x + 1, z + 1);

    // Assign indexes for triangles
    // Triangle 1
    triangles[6 * t + 0] = indexBR;
    triangles[6 * t + 1] = indexBL;
    triangles[6 * t + 2] = indexTL;

    // Triangle 2
    triangles[6 * t + 3] = indexBR;
    triangles[6 * t + 4] = indexTL;
    triangles[6 * t + 5] = indexTR;

    // Normals stuff...

}

```

# Answer
> 10 votes
This isn't caused by your UVs or by your normals. The problem is **triangle interpolation**, and it's a very common problem for quad-based heightmaps.

Here's a closeup of a small portion of your screenshot (slightly contrast-enhanced on the right, to show the problem more clearly):

As you can see (slightly to the northwest of the two red dots), the problem is that the heightmap has divided these heightmap quads into triangles for rendering by creating a diagonal connecting the northeast and southwest vertices of each quad, so you get one triangle on the northwest, and one on the southeast of each quad.

Since each of those triangles has a light vertex at the northeast, and another light vertex at the southwest, and those vertices are directly connected to each other (via triangulation for rendering), you end up with a light patch running straight through the middle of the triangulated 'quad'.

So that's the problem you've run into.

I'm aware of two solutions to this problem:

One solution is to try to make your height map smarter; don't just use a single hard-coded direction for creating triangles out of your quads. Instead, turn quads into triangles by connecting the closer of the two diagonals. In this case, the northwest and southeast corners are closer together than the northeast and southwest corners, so it would have made sense to divide this particular quad up into triangles to the northeast and southwest. This approach tends to work really well for undulating terrain, such as in your screenshot. But it does require you to convert your heightmap quads into triangles yourself.

A more robust solution is to not put normals on your vertices at all. Instead, use a texture map with the normals encoded into its RGB channels. Your fragment/pixel shader can then read each fragment/pixel's normal out of that normal map, and use it directly. The benefit of this is that textures don't get smeared around over triangles at all, so you won't get this "diamonds" artefact regardless of which direction that heightmap's triangles are facing.

# Answer
> 1 votes
Much thanks to @Trevor Powell, a very interesting insight, and not quite the obvious one. This took me some time to process, but results speak for themselves. Wery welcome after so much frustration over blocky terrains! I implemented smart triangulation.

There's one thing I'd like to add. If you have good normals (personally tried this with analytically accurate normals for my terrain surface) and if you are using per-pixel shading (so that normals are getting interpolated in the shaders), try using this (better have your normals normalized, just in case):

Take the dot product of normals for both diagonals. Split the quad along the diagonal which yields bigger dot product (the normals are more similar). Works even better than merely deciding based on height difference. Good luck!

# Answer
> 0 votes
@Trevor Powell, thank you for the help! Just to clarify, from my example code I had to check if the first difference was greater (not less), to get the desired effect:

```
if (Math.Abs(vertices[indexTR].y - vertices[indexBL].y) > Math.Abs(vertices[indexTL].y - vertices[indexBR].y))
{
// Triangle 1
triangles[6 * t + 0] = indexBR;
triangles[6 * t + 1] = indexBL;
triangles[6 * t + 2] = indexTL;
...

```

Cheers!

# Answer
> 0 votes
@TrevorPowell, also I've taken time to investigate the normal mapping solution. I use two kinds of height functions: generic ones and functions that provide a way to compute analytical normals at arbitrary points (smooth functions). I compute normals for a generic function using incident triangles method. For each triangle in the grid, incident to the vertex in question I compute normal via cross product and average them. I use "ghost cells" around my finite grid so I can subivide one logical grid into many smaller grids seamlessly (normals on the edges are the same). It is important that this method relies on a priori known tesselation.

So the thing is, with smooth functions I can make a very HQ normal map with much bigger resolution than my terrain mesh and have great results. However, I've noticed that if normal map dimensions are not POTs, it's mapped onto my grid very poorly.

This means I would have to restrict my grid dimensions to POTs as well and, in case of generic functions I couldn't simply utilize high-res normal maps.

That's why I decided to stick with adaptive tesselation solution instead. I'd like to point out that my method with dot product only works if normals are known before the tesselation stage, whereas if they are generated using incident triangles method (grid-dependent) they can really be known only after the tesselation stage. In this case I use the method with closer heights you suggested.

---
Tags: unity, normals, dynamic-mesh
---


# Question
Title: Unity - moving an object around a radius
I'm trying to move a 2D object around the mouse position, However, i want to constrain the object from rotating unnaturally around itself, i want it to basically rotate around a radius, similar to how a boat moves. I've provided the boat example below of what i am trying to achieve, the game is called battleboats.io and their rotation around the mouse will not skid, it looks natural like propellers pushing from behind.

Here's my code for achieving this in unity:

```
public Camera camera;
public Rigidbody2D rigidbody;

private float rotationSpeed = 200f;
private float acceleration = 4.4f;

Vector3 GetMousePosition(Camera c)
{
    return c.ScreenToWorldPoint(Input.mousePosition);
}

void Update()
{
    Vector3 direction = GetMousePosition(camera) - transform.position;
    direction.Normalize();
    float rotationAngle = Vector3.Cross(direction, transform.up).z;

    //rotation
    rigidbody.angularVelocity = -rotationAngle * rotationSpeed;

    //forward momentum
    rigidbody.velocity = transform.up * acceleration;
}

```

Any help is appreciated.

What i currently have and the result of my code is illustrated in the below gif.

# Answer
> 6 votes
You need to put a cap on how big `rotationAngle` is allowed to be. Right now, as the difference between the mouse and the "player" grows larger, your "player" rotates more quickly to catch up. But in order to put a "minimum turn radius" on your object, you need to restrict how quickly it can change direction.

Try this:

```
float rotationAngle = Vector3.Cross(direction, transform.up).z;

//apply a maximum turn angle of 25 degrees
rotationAngle = Mathf.Max(Mathf.Min(rotationAngle,25), -25);

//rotation
rigidbody.angularVelocity = -rotationAngle * rotationSpeed;

```

Adjust the "25/-25" as needed to achieve the desired turn rate.

---
Tags: unity, 2d, physics, mathematics, rotation
---


# Question
Title: Steelseries Stratus XL controller: Keycode for middle button
I'm working on an Android app (Java, level 19+) that uses a controller to e.g. walk and it's working (almost) fine with both the Steelseries Stratus XL and the Moga Pro Power. The only problem is that the Stratus XL has a button in the middle (the one with the circle: click) that closes the app.

I now want to disable that but I have no idea what the keycode for the button is and it also doesn't say anything about it on the official Steelseries homepage.

Has anyone here worked with the Stratus XL before and knows what keycode to use?

# Answer
According to the FCC instruction filing for Stratus XL, the center round key is intended to be a home key.

If that's correct, there might not be much you can do, as the developer reference for the home key states:

> KEYCODE\_HOME added in API level 1 int KEYCODE\_HOME Key code constant: Home key. This key is handled by the framework and is never delivered to applications.
>
> Constant Value: 3 (0x00000003)

I searched the developer reference on supporting game controllers, but didn't see anything specific to redirecting home key requests.
> 3 votes

---
Tags: java, android, controllers, gamepad
---


title: Why isn't SDL displaying my texture?

text:
# Question
Title: Why isn't SDL displaying my texture?
I am self teaching SDL game programming from SDL Game Development Black and White textbook.

I stopped at the second chapter, where I have to display .bmp picture on screen.

Given code:

```
SDL_Surface* pTempSurface = SDL_LoadBMP("assets/rider.bmp");

m_pTexture = SDL_CreateTextureFromSurface(m_pRenderer,pTempSurface);
SDL_FreeSurface(pTempSurface);

SDL_QueryTexture(m_pTexture, NULL, NULL, &m_sourceRectangle.w, &m_sourceRectangle.h);
m_destinationRectangle.x = m_sourceRectangle.x = 0;
m_destinationRectangle.y = m_sourceRectangle.y = 0;
m_destinationRectangle.w = m_sourceRectangle.w;
m_destinationRectangle.h = m_sourceRectangle.h;

```

should be loaded inside init function of Game1.cpp, as author tells

```
#include <iostream>
#include "Game1.h"
#include <stdio.h>
#include <SDL2/SDL.h>

Game::Game()
{

}

bool Game::init(const char* title, int xpos, int ypos, int width, int height, int flags)
{
    SDL_Surface* pTempSurface = SDL_LoadBMP("assets/rider.bmp");

    m_pTexture = SDL_CreateTextureFromSurface(m_pRenderer, pTempSurface);
    SDL_FreeSurface(pTempSurface);

    SDL_QueryTexture(m_pTexture, NULL, NULL, &m_sourceRectangle.w, &m_sourceRectangle.h);
    m_destinationRectangle.x = m_sourceRectangle.x = 0;
    m_destinationRectangle.y = m_sourceRectangle.y = 0;
    m_destinationRectangle.w = m_sourceRectangle.w;
    m_destinationRectangle.h = m_sourceRectangle.h;

    if(SDL_Init(SDL_INIT_EVERYTHING) == 0)
    {
        std::cout << "SDL init success\n";
        m_pWindow = SDL_CreateWindow(title, xpos, ypos, width, height, flags);

        if(m_pWindow != 0)
        {
            std::cout << "window creation success\n";
            m_pRenderer = SDL_CreateRenderer(m_pWindow, -1, 0);

            if(m_pRenderer != 0)
            {
                std::cout << "renderer creation success\n";
                SDL_SetRenderDrawColor(m_pRenderer, 255, 255, 255, 255);
            }
            else
            {
                std::cout << "renderer init fail\n";
                return false;
            }
        }
        else
        {
            std::cout << "window init fail\n";
            return false;
        }
    }
    else
    {
        std::cout << "SDL init fail\n";
        return false;
    }

    std::cout << "init success\n";
    m_bRunning = true;

    return true;
}

void Game::render()
{
    SDL_RenderClear(m_pRenderer);

    SDL_RenderCopy(m_pRenderer, m_pTexture, &m_sourceRectangle, &m_destinationRectangle);

    SDL_RenderPresent(m_pRenderer);
}

void Game::SDL_Quit()
{
    std::cout << "cleaning game\n";
    SDL_DestroyWindow(m_pWindow);
    SDL_DestroyRenderer(m_pRenderer);
}

void Game::clean()
{
    std::cout << "cleaning game\n";
    SDL_DestroyWindow(m_pWindow);
    SDL_DestroyRenderer(m_pRenderer);
    SDL_Quit();
}

```

Game1.h

```
#ifndef GAME1_H
#define GAME1_H
#include <iostream>
#include <stdio.h>
#include <SDL2/SDL.h>

class Game

{
public:

    Game();
    ~Game();

    bool init(const char* title, int xpos, int ypos, int width, int height, int flags);

    void render();
    void update();
    void handleEvents();
    void clean();
    void SDL_Quit();

    bool running() { return m_bRunning; }

private:

    SDL_Window* m_pWindow;
    SDL_Renderer* m_pRenderer;

    SDL_Texture* m_pTexture; // the new SDL_Texture variable
    SDL_Rect m_sourceRectangle; // the first rectangle
    SDL_Rect m_destinationRectangle; // another rectangle

    bool m_bRunning;
};

#endif // GAME1_H_INCLUDED

```

main.cpp

```
#include "Game1.h"
#include <iostream>
#include <stdio.h>
#include <SDL2/SDL.h>

Game* g_game = 0;

int main(int argc, char* args[])
{

    g_game = new Game();

    g_game->init("Chapter 1", 100, 100, 640, 480, 0);

    while(g_game->running())
    {
        g_game->handleEvents();
        g_game->update();
        g_game->render();
    }
    g_game->clean();

    return 0;
}

void Game::handleEvents()
{
    SDL_Event event;
    if(SDL_PollEvent(&event))
    {
        switch (event.type)
        {
            case SDL_QUIT:
                m_bRunning = false;
            break;

            default:
            break;
        }
    }
}

```

When build this in CodeBlocks I get no error. Even window loads, but there is no rider.bmp image on window screen.

What is wrong? Should given code be placed somewhere else inside init()? Thank you

# Answer
> 2 votes
You need to initialize SDL before calling `SDL_LoadBMP` and construct the renderer before calling `SDL_CreateTextureFromSurface`. It's a good rule of thumb to initialize SDL and create the window and renderer before doing anything else.

So simply move that code to bottom of `init`.

---
Tags: sdl2
---


# Question
Title: How can I attract & repel the mouse cursor from particular UI controls?
This question came from some of my students. I wanted to share it here so others can find & improve on the solutions we've found so far.

In particular, my answer below doesn't behave as well as I'd like in windowed / editor mode - UI buttons no longer respond to hovering the cursor. I welcome alternative answers that solve this more completely.

---

We're making a visual novel game using the Fungus asset for Unity.

We want to add a twist where some dialogue options are easier or harder to press, because they attract or repulse your mouse cursor.

Unfortunately, we haven't been able to identify a cross-platform way to manipulate the mouse's position, nor a way to create a "Fake" mouse cursor image that can still interact with Fungus's UI buttons.

How can we pull this off?

# Answer
We can take complete control of how Unity handles cursor events by providing our own InputModule.

Start by finding the EventSystem in your scene, and removing any existing InputModules from it, and adding a custom one instead (based on a sample by OpticalOverride). This replaces the native mouse cursor with our own fake cursor for the purpose of all UI events. In particular, clicks from the fake cursor will trigger Fungus dialogue options under it.

```
using UnityEngine;
using UnityEngine.EventSystems;

public class FalseCursorInputModule : StandaloneInputModule {

    public RectTransform cursorVisual;
    public float cursorSpeed = 2f;

    Vector2 m_cursorPos;
    private readonly MouseState m_MouseState = new MouseState();

    RectTransform m_canvas;

    protected override void Start() {
        OnApplicationFocus(Application.isFocused);
        m_canvas = (RectTransform)cursorVisual.parent;
        m_cursorPos = new Vector2(Screen.width, Screen.height) / 2f;
    }

    // Lock & hide the real mouse cursor.
    private void OnApplicationFocus(bool focus) {
        if (Screen.fullScreen) {
            // In full-screen, this works perfectly.
            // Out of full screen, click events don't work.
            Cursor.lockState = CursorLockMode.Confined;
            Cursor.visible = false;
            return;
        } else {
            // This works as a fallback, but we don't get hover events.
            Cursor.lockState = CursorLockMode.Locked;
        }
    }

    // Intercept mouse events and use them to drive our virtual cursor instead.
    protected override MouseState GetMousePointerEventData(int id = 0) {
        MouseState m = new MouseState();

        // Populate the left button...
        PointerEventData leftData;
        var created = GetPointerData(kMouseLeftId, out leftData, true);
        leftData.Reset();
        if (created)
            leftData.position = m_cursorPos;

        // Add the relative movement of the mouse to our virtual cursor position.
        Vector2 delta = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
        m_cursorPos = m_cursorPos + cursorSpeed * delta;

        // Translate to canvas space for handling repulsion & positioning visuals.
        Vector2 scale = new Vector2(m_canvas.rect.width / Screen.width, m_canvas.rect.height / Screen.height);

        Vector2 placedPosition = Vector2.Scale(m_cursorPos, scale);

        foreach (var repulsor in FindObjectsOfType<CursorRepulsor>())
            placedPosition = repulsor.Repulse(placedPosition);

        placedPosition.x = Mathf.Clamp(placedPosition.x, 0, m_canvas.rect.width);
        placedPosition.y = Mathf.Clamp(placedPosition.y, 0, m_canvas.rect.height);

        cursorVisual.anchoredPosition = placedPosition;

        // Translate back to screen space for UI raycasting.
        m_cursorPos = placedPosition;
        m_cursorPos.x /= scale.x;
        m_cursorPos.y /= scale.y;

        // Finish setting up left mouse event data.
        leftData.delta = m_cursorPos - leftData.position;
        leftData.position = m_cursorPos;
        leftData.scrollDelta = Input.mouseScrollDelta;
        leftData.button = PointerEventData.InputButton.Left;
        eventSystem.RaycastAll(leftData, m_RaycastResultCache);
        var raycast = FindFirstRaycast(m_RaycastResultCache);
        leftData.pointerCurrentRaycast = raycast;
        m_RaycastResultCache.Clear();

        // copy the apropriate data into right and middle slots
        PointerEventData rightData;
        GetPointerData(kMouseRightId, out rightData, true);
        CopyFromTo(leftData, rightData);
        rightData.button = PointerEventData.InputButton.Right;

        PointerEventData middleData;
        GetPointerData(kMouseMiddleId, out middleData, true);
        CopyFromTo(leftData, middleData);
        middleData.button = PointerEventData.InputButton.Middle;

        m_MouseState.SetButtonState(PointerEventData.InputButton.Left, StateForMouseButton(0), leftData);
        m_MouseState.SetButtonState(PointerEventData.InputButton.Right, StateForMouseButton(1), rightData);
        m_MouseState.SetButtonState(PointerEventData.InputButton.Middle, StateForMouseButton(2), middleData);

        return m_MouseState;
    }
}

```

Your `CursorVisual` should be an image on a canvas set to the same size as you've configured Fungus to use, with a `sortOrder` of 2 so it sits above any menu graphics. The image should be anchored to the bottom-left to make the `anchoredPosition` code above work as expected.

You can add additional objects to this canvas to be your repulsion / attraction loci. Here's one way we might write that script:

```
public class CursorRepulsor : MonoBehaviour {
    [Tooltip("Farthest distance at which the repulsor has an effect")];
    public float limitRadius = 300;
    [Tooltip("Distance at which the repulsor achieves its maximum effect")];
    public float peakRadius = 100;

    [Tooltip("Strength of the push - use a negative number to attract")];
    public float strength = 5;

    public Vector2 Repulse(Vector2 cursorPosition) {
        Vector2 me = ((RectTransform)transform).anchoredPosition;
        Vector2 away = cursorPosition - me;

        float distance = away.magnitude;
        if(distance > limitRadius)
            return cursorPosition;

        float intensity = Mathf.Clamp01((limitRadius - distance) / (limitRadius - peakRadius));

        float repulse = strength * intensity;

        return cursorPosition + away * repulse / distance;
    }
}

```

Placing these repulsors in the appropriate locations for your Fungus scene is left as an exercise for the reader / someone with more Fungus experience than I have thus far. ;)
> 3 votes

---
Tags: unity, gui, mouse
---