# Question
Title: Is it a bad practice to add helper methods if the class is intended only for data?
For example, if I have something like:

```
class ItemData
{
    public int cost;
    public int level;
    ...
    public List<ItemData> childItems;
}
```

And I'm aiming to separate data from logic, is it ok if I add methods to ItemData such as:

```
class ItemData
{
    ...
    public void AddChildItemData(ItemData childItem);
    ...
}

```

that are helper methods for setting or manipulating the data? Or should these be moved elsewhere to service classes?

# Answer
Your design contradicts object oriented programming.

In object oriented programming (which is the core of the C# language) you combine data and logic in a class. This means a class is a construct that defines all of its properties (cost, level, children in your example) as well as **what it can do.** Hence you should of course combine those two parts,

---

## Discussion of the matter in practice

**1. Classes as pure data containers:**

So much for the theory of OOP. In practice however this is not always practical to a full extent. Imagine a physics system, that has control over many objects exposed to it. Even though an object is theoretically **capable of colliding with other objects** it's better to leave those checks to a seperate system so it is easier to maintain, because it's centralized.

Second example: I'm doing a simple engine for a game at the moment and designed a rendering system. I created a *Scene* class, that holds information about all visuals (only geometry and lights). I have a second class *Renderer*, that operates on scenes (orders the lists for optimization and renders everything). Because the renderer can be configured in many ways all those functionalities are not included in *Scene*, even though they are directly tied to them. That way *Scene* is exclusively for holding data.

There are a lot of cases where classes are designed as pure data containers without any logic to them. However, if you have methods, that are immediately tied to your data container (Like your *AddChildItemData* method) there is no sense in outsourcing it. Imagine code like this:

```
ItemData data = new ItemData();
ItemData childData = new ItemData();
ItemDataManipulator manipulator = new ItemDataManipulator(data);
manipulator.AddChildItemData(childData);

```

That's not readable and looks like an awful design.¹

**2. Acess considerations:**

However, there's another point to be considered: If you want some parts of the logic only be accessible to some part of your code (for example the part where you load data from disc) you might lean towards creating something like a creator class to hide this kind of logic from other parts of your software (you could for example decide not to make item modification available to mods). There are many other possibilities to achieve this (mainly access modifier) you should consider.

---

## Conclusion

It depends. There are cases where classes (and - even more so - structs) are designed as pure data containers. But logic, that is only useful for this container, should be included in it. As I showed above, imagine you'd have to instantiate a seperate class to add a children to one of your objects. That's **usually** no smart design and over-complicates things.

But, as I discussed above: **The design of your software completely depends on what you want to achieve and there is not definite answer.**

Listing of various object-oriented design patterns (I did not read much of it, but it looks reliable)

---

¹: Note: There are software patterns where code like this is actually common. It can be useful to hide some features in certain situations. A little example: I'm using a builder pattern for keyframe-animations in my code with various operations that could be used when creating and editing operations. When applying the animation somewhere I don't need these operations. Patterns like this can be extremely useful when you want to expose only a certain set of operations in a given context.

---

Personally I follow this paradigm:
**Try to keep your code as complex as needed, but as simple as possible.**
> 5 votes

# Answer
> is it ok...

You shouldn't ask for **our** permission for **your** code. Ask whomever is responsible for code standards, if that's you then only you can truly answer the question of whether or not it's permissible.

However on the question of whether or not the use of helper functions can be **suggested** or follow **good standards**™?

In theory; Not really, a true object-oriented design should have each object be entirely self-contained and not dependant on outside helper functions.

In practice; Designing a truly object-oriented design is **hard** and the cost usually isn't worth it for games, as long as you're **consistent** a strict adherence to proper practices doesn't matter much.

**Most importantly:** Don't tangle yourself too far with code standards, you can write good code with bad practises and bad code with good standards.

As long as you **document** and **be consistent**! You'll be fine.
> 0 votes

# Answer
A core principle of object-oriented programming is **encapsulation**. It means that all member-variables of a class should be declared `private` and the only way to change them from the outside is through methods of the class. This separates the interface from the implementation.

This is especially important for complex containters like `List`, because when you expose these directly you allow other classes to make changes to the list which are not under the control of the class which owns the list. When adding or removing child items means that more needs to be done than just adding them to the container and you (or another programmer) forget about that, this will end in disaster.

If you need other classes to read the content of the list, it is usually a good idea to expose only the most minimal interface. When you want to provide read-only access to a `List`, it's usually sufficient to return an `IEnumerator` which allows to read the contents of the list but not change it:

```
class ItemData
{
    private List<ItemData> childItems;

    public void AddChildItemData(ItemData childItem) {
         // do whatever internal bookkeeping is required
         // when child items are added
         childItems.Add(childItem);
    }

    public IEnumerator<ItemData> GetChildItemData() {
         return childItems.GetEnumerator();
    }
}

```

Notice that this class does not expose the implementation detail that it stores its data in a `List<ItemData>`. That means you can easily change the way you store the information without having to change any of the code which uses it. This improves loose coupling making your code more reusable and maintainable.
> 0 votes

---
Tags: c#, design-patterns, architecture
---


# Question
Title: Unity - How to move a ship realistically to a point in a 2D top-down game
i'm trying to move a sailing ship to the point where i clicked with the mouse. this movement should be realistic (oar at the back where the ship moves around) so if the mouse click is left and in front of the ship the ship should afterwards move there with a curvy path in order to have the right rotation

i'd be glad if someone could help me with this issue thank

# Answer
> 7 votes
See this page

> **Adding Realistic Turns**
>
> The next step is to add realistic curved turns for our units, so that they don't appear to change direction abruptly every time they need to turn. A simple solution involves using a spline to smooth the abrupt corners into turns. While this solves some of the aesthetic concerns, it still results in physically very unrealistic movement for most units. For example, it might change an abrupt cornering of a tank into a tight curve, but the curved turn would still be much tighter than the tank could actually perform.
>
> For a better solution, the first thing we need to know is the turning radius for our unit. Turning radius is a fairly simple concept: if you're in a big parking lot in your car, and turn the wheel to the left as far as it will go and proceed to drive in a circle, the radius of that circle is your turning radius. The turning radius of a Volkswagen Beetle will be substantially smaller than that of a big SUV, and the turning radius of a person will be substantially less than that of a large, lumbering bear.
>
> Let's say you're at some point (origin) and pointed in a certain direction, and you need to get to some other point (destination), as illustrated in Figure 5. The shortest path is found either by turning left as far as you can, going in a circle until you are directly pointed at the destination, and then proceeding forward, or by turning right and doing the same thing.
>
> In Figure 5 the shortest route is clearly the green line at the bottom. This path turns out to be fairly straightforward to calculate due to some geometric relationships, illustrated in Figure 6.
>
> First we calculate the location of point P, which is the center of our turning circle, and is always radius r away from the starting point. If we are turning right from our initial direction, that means P is at an angle of (initial\_direction - 90) from the origin, so:
>
> ```
> angleToP = initial_direction - 90
> P.x = Origin.x + r * cos(angleToP)
> P.y = Origin.y + r * sin(angleToP)
>
> ```
>
> Now that we know the location of the center point P, we can calculate the distance from P to the destination, shown as h on the diagram:
>
> ```
> dx = Destination.x - P.x
> dy = Destination.y - P.y
> h = sqrt(dx*dx + dy*dy)
>
> ```
>
> At this point we also want to check that the destination is not within the circle, because if it were, we could never reach it:
>
> ```
> if (h < r)
>     return false
>
> ```
>
> Now we can calculate the length of segment d, since we already know the lengths of the other two sides of the right triangle, namely h and r. We can also determine angle from the right-triangle relationship:
>
> ```
> d = sqrt(h*h - r*r)
> theta = arccos(r / h)
>
> ```
>
> Finally, to figure out the point Q at which to leave the circle and start on the straight line, we need to know the total angle + , and is easily determined as the angle from P to the destination:
>
> ```
> phi = arctan(dy / dx) [offset to the correct quadrant]
> Q.x = P.x + r * cos(phi + theta)
> Q.y = P.y + r * sin(phi + theta)
>
> ```
>
> The above calculations represent the right-turning path. The left-hand path can be calculated in exactly the same way, except that we add 90 to initial\_direction for calculating angleToP, and later we use - instead of + . After calculating both, we simply see which path is shorter and use that one.
>
> In our implementation of this algorithm and the ones that follow, we utilize a data structure which stores up to four distinct "line segments," each one being either straight or curved. For the curved paths described here, there are only two segments used: an arc followed by a straight line. The data structure contains members which specify whether the segment is an arc or a straight line, the length of the segment, and its starting position. If the segment is a straight line, the data structure also specifies the angle; for arcs, it specifies the center of the circle, the starting angle on the circle, and the total radians covered by the arc.
>
> Once we have calculated the curved path necessary to get between two points, we can easily calculate our position and direction at any given instant in time, as shown in Listing 2.
>
> **LISTING 2.** Calculating the position and orientation at a particular time.
>
> ```
> distance = unit_speed * elapsed_time
> loop i = 0 to 3:
>     if (distance < LineSegment[i].length)
>         // Unit is somewhere on this line segment
>         if LineSegment[i] is an arc
>             //determine current angle on arc (theta) by adding or
>             //subtracting (distance / r) to the starting angle
>             //depending on whether turning to the left or right
>             position.x = LineSegment[i].center.x + r*cos(theta)
>             position.y = LineSegment[i].center.y + r*sin(theta)
>         //determine current direction (direction) by adding or
>         //subtracting 90 to theta, depending on left/right
>         else
>             position.x = LineSegment[i].start.x
>               + distance * cos(LineSegment[i].line_angle)
>             position.y = LineSegment[i].start.y
>               + distance * sin(LineSegment[i].line_angle)
>         direction = theta
>         break out of loop
>     else
>         distance = distance - LineSegment[i].length
>
> ```

# Answer
> 7 votes
As simple solution , as already I said in a comment, you can try this aproach:

consider a phase where you point the ship in the target direction, in that phase you apply a rotation to the sip but also a forward movement. When the ship is already facing target you can apply a full forward speed. I arranged a test in love2d , here follow the ship update method .

```
turnAngSpeed = 0.4 --direction changing speed
ForwordSpeed = 40 -- full forward speed
turnForwordSpeed = ForwordSpeed *0.6 -- forward speed while turning
function ent:update(dt)
            dir = getVec2(self.tx-self.x,self.ty-self.y) -- ship --> target direction (vec2)
            dir = dir.normalize(dir) --normalized
            a= dir:angle() - self.forward:angle() --angle between target direction e current forward ship vector
            if (a<0) then
             a=a+math.pi *2 -- some workaround to have all positive values
            end

            if a > 0.05 then -- if angle difference
                if a < math.pi then
                    --turn right
                    self.forward = vec2.rotate(self.forward,getVec2(0,0),turnAngSpeed * dt)
                else
                    --turn left
                    self.forward = vec2.rotate(self.forward,getVec2(0,0),-turnAngSpeed * dt)
                end
                --apply turnForwordSpeed
                self.x = self.x+ self.forward.x * turnForwordSpeed * dt
                self.y = self.y+ self.forward.y * turnForwordSpeed * dt
            else
                --applly ForwordSpeed
                self.x = self.x+ self.forward.x * ForwordSpeed * dt
                self.y = self.y+ self.forward.y * ForwordSpeed * dt
            end
end

```

The example animation shows (the final loop) a case where the ship can't reach the target , as the combination of turning and forward speed defines a turning radius too big, in this cases can bee usefull reducing the "`turnForwordSpeed`" or better make it dependent on angle distance (`a`) and target distance.

# Answer
> -2 votes
Unity Nav mesh system, it would likely do what you want with a little playing around with the nav agent values.

Nav Meshes are pretty simple to use. And only usable in the top down setup (or at least only available to x/z movement)

Unity manual Page on setting up a nav mesh

Basically you can use any shape mesh to bake a navigation area, and add nav agents to your objects and have them find their paths around a navigation mesh

---
Tags: unity, movement, movement-prediction
---


title: Making game totally from scratch

text:
# Question
Title: Making game totally from scratch
I'm used to make my games in Java. Java is an awesome language but to launch .jar files you need a good updated JRE. So I thought: "I'm just going to make my games in C# or C++!" Unfortunely, I can't find the logic behind all those libraries like OpenGL etc.

My question is: Is it achievable to make a game in C# or C++ from scratch?(So no libraries) And where can I find any guidlines or tutorials?

Thanks!

# Answer
> 9 votes
The obvious answer to this question is to sit down and watch through the entire archive of **Handmade Hero**.

It is *exactly* what you are after. It is literally a tutorial on how to make a game from scratch, without engines or libraries. Obviously it is very long.

# Answer
> 2 votes
Unless you want to spend a couple of years writing your own drivers, you'll need at least a graphics library. I'm all for making things from scratch and while that can be fun, making **EVERYTHING** from scratch is frustrating, annoying and pointless.

The logic behind using libraries like OpenGL is to avoid complicated tedium that has a general solution and it lets you focus on the game.

As for where to learn?

This is impossible for us to answer, as there isn't just one skill that has to be gained, my advice is to start with a game idea and learn as you go.

# Answer
> 2 votes
**Sure you can!** Just, probably not very well on PC. You can pretty much forget about graphics card acceleration. To quote Patrick Hughes' answer to another question:

> \[PC is like the\] wild west, barroom brawls and your OS is the sheriff keeping everyone from getting shot.
>
> \[...\]on home PCs you have to support tens of different chipsets that have to work flawlessly against millions of programs written across the past decade or more? Personally I think that it's a miracle that the house of cards keeps standing!

As a business venture there's just too much going on there for you to be able to confidently support much more than *your own* PC, let alone the variety of quirks that crop up on other people's systems. But, if you're just interested in learning things about low level tricks (which in today's world only come up if you're working on drivers/middleware/APIs - things studios don't really do) and thus don't care too much about compatibility check out some of the code released from demoscenes, at ie The Great Demoscene Sourcecode Giveaway.

Or, as a technical exercise, writing a game from the ground up targeting a simple platform like Arduino is completely achievable. Since it's essentially just a flashable chip, you'll have to decide on the parameters of your game. Maybe you skip the screen and do sound only? Strange controller? It would be a good setup for getting into console development.

---
Tags: c#, c++, java
---


title: Libgdx: how does dispose() work?

text:
# Question
Title: Libgdx: how does dispose() work?
My game uses a lot of images, for the over-world, battle screens, chats, etc. I'm really meticulous when it comes to memory management, and I've noticed that even though I dispose every image when I load in a new one, the memory never goes down.

Isn't this what Dispose() should do or is my understanding wrong?

# Answer
> 3 votes
Disposal patterns like LibGDX's in languages with GCs often have to do with releasing un-managed resources in addition to (or instead of) managed memory. This true with C#'s `IDisposable` interface, and based on the documentation LibGDX's pattern serves a similar purpose.

This means that simply looking at private working-set CPU-side RAM use may not be an accurate way to tell if disposing of the resource is "working as intended" or not. For example, if a texture isn't caching its image data on the CPU (expecting it to be on the GPU), then disposing it will not impact CPU-side memory appreciably at all.

LibGDX's source code is on GitHub, so you can take a look at the specific implementations of the dispose method. For example, texture's or pixmap's.

---
Tags: libgdx, memory-efficiency
---


# Question
Title: Can I use feature creep to my advantage?
Can I use feature creep to my advantage?

Every time I prototype a game, features are inadvertently added. This happens either through coincidence, or it happens to be easy to add based on existing content.

If I know the genre of the game, can I just start making the basic mechanics and add features as they become apparent?

For example, if I want to make a 2d platformer over the course of 6 months, can I just start making the running, jumping, shooting, etc. and add the core mechanics as I inadvertently find them? Or is this too risky of a time investment without a predetermined plan?

My logic behind this is that the design will be more bang for the buck. The design choices will more easily be built around what is easy to make (time-wise).

In summary, is there anything wrong with building a game *before* I design it?

# Answer
That is an interesting question. Mainly because answering it raises the shades-of-grey versus black-vs-white dilemma.

> is there anything wrong with building a game before I design it?

If you think of that question as a yes or no type, the answer can only be: yes, there is. If the answer can be more nuanced, then it changes. Reason: you should never build a game before ***some*** designing. But you sure can save ***parts*** of the design for later.

It means, I don't think you should see the issue at hand as a do or don't. Rather, it is something that you should think of in terms of degrees. Feature creeping maybe the very second root of all evil in what regards game development (the first, as Donald Knuth has thougth us, is that "premature optimization is the root of all evil"). However, in my experience, not thinking of any of the main features, i.e. not having at least a basic design of where you want to go with your basic mechanics, is not a good idea either.

The first main reason is that it is helpful resource-wise (including time as a resource) to have some planning to guide you trough - because reaching dead-ends all the time due to excessive try-and-error can be just as waste of resources as having to include unforeseen features.

The second main reason, game-design-wise, is coherence. Good game-design has conceptual coherence, or consistency if you want. It means, the overall game-play, the history, the implementation, even the graphics, should fit each other as smoothly as possible. It is very unlikely that a game-design will achieve something like that if main features are just found out on the go. If not for anything else, because on the go has a lot of randomness into it: the things you will step on may have very different impacts depending on *when at the development process you did find them*.

I don't mean saying that you shouldn't do what you said at all. I am just claiming that you have to find some balance.

> For example, if I want to make a 2d platformer over the course of 6 months, can I just start making the running, jumping, shooting, etc. and add the core mechanics as I inadvertently find them? Or is this too risky of a time investment without a predetermined plan?

I would start by introducing a slight modification in your sentence. By making the running, jumping, shooting and etc you are already implementing core mechanics. What you would add on-the-go in your example are the specific game-play features.

It is not because you know the game will be a 2D platform, that running, jumping or shooting can't vary depending on the game design. Can your player run on the walls? Can your player float in the air when jumping? Even, can your player shoot while running? Does your player shoots only in a linear direction or via a parabola? These decisions can be very much game-feature dependent.

But I see your point: these mechanics often have some parts that vary very little. So, if you do *some* game-design and decide on basic features as much as to be somewhat sure how running, jumping, shooting, etc will work, that's a start. Then you can go for these mechanics and keep building on them.

Of course you can still later find a new feature that requires you to alter these mechanics - no matter how basic they were. But the key here is probability. The probability that this will happen too often will be smaller if you at least did some thinking on the consequences of running, shooting, jumping and etc for the basic ideas you had for the game.

---

Lastly, if you want to go that route, I would suggest the following. Think of it as a iterative process. You do some initial, broad-level design-thinking. You implement what seems basic and more "universal" within your game, for it to succeed. Then you do some more design-thinking, re-evaluate what you implemented and go for some more implementation.
> 19 votes

# Answer
When doing complex projects like games, you often can't make all the features you want, because you're running out of time/money or because they didn't turn out to be as good as you expected. This is known as feature creep. But there's a flip side to this; you will also find features that you didn't think you needed, but as the project takes shape their need becomes apparent.

This is why people **build prototypes** \- so they can learn what works and what doesn't, so they can **cut features that don't work**, but also so they can **find new features that would be awesome**. If you're not doing either of those things **you're not learning**, you're doing it wrong.

This is basically the sentiment expressed in a talk called Advanced Prototyping, by Chris Hecker and Chaim Gingold, which includes many examples from their work on Spore, where they were often surprised by what worked and what didn't, going as far as redesigning whole systems based on prototype feedback.

Another example is the design process for Left 4 Dead; at first the game only had basic zombies, but from playtesting with experienced players, the designers found that the players stuck together effectively and the game was too easy, so they added special zombies to break the team apart and keep the game exciting.

Of course, this **doesn't mean you should build your game without any prior design at all**. You should make sure that the core of your game is fun before proceeding, because that's often the hardest part of making a game.
> 4 votes

# Answer
I would say yes, go for it. But plan some common features / classes ahead of time to have some cohesion between each new component.

Unity is known for its component approach to game development, and would allow this form of development easily. If you aren't using Unity, you could replicate a semi-component approach. I'm unfamiliar with other game engines.

Unity game objects all have a transform component. This states the position, rotation, and scale of the object. So make a generic 'transform' class to hold these values, plus a reference to the actual game object maybe.

Take a 'Jump' component, for example. Have all the logic work with a game object's transform class to do the manipulating of position. (Or your engine will have a similar built in class already.) You could attach this 'Jump' class to any object, and the class will animate the transform position when an action is triggered (Jump.PerformJump() or whatever). The Jump class doesn't have to know anything about its owner (or, at least, minimal info).

Now you can have fun creating a ton of components, then attaching them to game objects, combining them on one object, etc. For example: Run, Jump, Crouch, MovingTile, FireWeapon (specify the 'bullet' sprite, and behavior to make a generic component), etc.

Make each component as generic as possible to allow for multiple uses / variations. For FireWeapon, you can specify the bullet sprite, speed, damage, etc. You could try to make those attributes normalized, so that speed and damage is specified between 0 and 1. Then scale those to the game's max values. This way you only worry about relative differences between the weapons. Plus this adapts to global settings such as difficulty where a higher difficulty has a higher max damage, etc.

Before you know it, you have an arsenal of components to plug in, and you can now quickly develop for any game type.
> 2 votes

# Answer
Brief: most of the time you cannot have a single design step followed of a single coding step. You will have to alternate them. As a general rule, try to respect what is already designed (not what is already coded).

About not having an initial design (just a sketch or a mental image): if you do not have a design you do not have a design. You must do something to come with one. But as long as you start to build one, try to respect it, do not come with a new one every time.

---

Do experimentation and get random features may or may not be harmful. It may even be beneficial or unavoidable. For example: you know that you want to support jumping (many 3D/2D RPG do not allow to jump). How do you know it? Because you imagined a game map requiring jumping to sort an obstacle? So the **jump** implementation is good enough as long as it lets the player sort that obstacle or does it have to comply with certain characteristics like maximum reachable altitude, can be it boosted by items or game objects in map, physics must include acceleration or bounce (when Mario jump into an enemy He gains impulse to elevate again and that is very important for the game play)?

If you already can answer those questions then your design documents (imaginary or real) are very complete. If you cannot answer those, then your design is incomplete. In this case, you will have to go again to work in the design or do experimentation to fill the gaps. The opportunities may be very open or very restrictive. If some of your game levels will have obstacles, and you just need the jumping for them then there are a lot of freedom to decide the maximum reachable altitude or the speed, maybe you decide to pretend there are a physics engine begin it all just to improve the visuals of the jump animation but you do not need it for anything else. (In many 2D RPG games you cannot jump when you want, but as long as there is a single tile hole in a map, trying to step into it automatically triggers a jump to the floor tile next to the hole tile)

I understand that It is OK to go to code without a complete design as long as you respect what is already decided. Also It may be unavoidable in some situations as game universes may be built from a variety of different thinking processes. For example a card game: I know I want the cards to have Attack and Defense, a certain numbers of card in the table at a given time and that the player during his/her turn can choose with which card attack which other card. It may look to some as an already complete design, but then it comes the balancing of the game, only possible through many simulations. After many simulations I decide that a card with Attack 10 is overpowered, I can simply delete it from the game but I like it too much so I will do something different, I will create a new rule that says that if a player attack with such a card it cannot attack with other card during that turn. Now I have a new rule that enriches the game mechanics, but apply it to a single card looks weird (like a dirty hack), I realize It looks weird and then I decide to create a new set of cards that have high numbers but the new limiting rule applies to them. Now I have a more complex game mechanic, built above the simpler original one, in my opinion, I turned it to my advantage to make a better game.

Now, one thing about that last example, in the proposed example of the card game, new cards may result in new assets (cost increase, time increase). But I think is a good example of let the opportunities you only see when coding influence your design decisions in a good way.

I don't think most of the games we play were fully designed before coding, I'm sure they had to make difficult decisions to comply with timelines and so.

When somebody else is paying for it all: explain, negotiate.
> 1 votes

---
Tags: game-design, architecture, time-management
---


# Question
Title: Transitioning through menus in Unity: what is the best option performance-wise?
I'm making a menu manager and I'm not sure what should I do to make a transition from one menu to the other. What is better to be used performance wise? Here is the step in my mind.

1. Simple enable or disable menu.
2. Change alpha 0 or 1.
3. Move the menu outside of canvas.

So what is better?

# Answer
> 2 votes
When you make a menu invisible by making it completely transparent or moving it outside of the view area, any scripts or other components attached to it are still being executed. The best way to show or hide a GUI feature is using `gameObject.SetActive(true)` and `gameObject.SetActive(false)` because this will also prevent the logic behind it from running.

---
Tags: unity, performance, menu
---


title: Can't attach animation to script

text:
# Question
Title: Can't attach animation to script
I'm working on a little game (which is also my first one) and I want to insert a splash screen at the beginning (after the Unity one). I've finally achieved to add a fade-in and a fade-out transistion when the splash screen starts and ends, but the fade out is activated by a button and I wont to play it simply after a certain time. I've made a script for that:

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

public class FadeInOut_2 : MonoBehaviour
{
    public Animation anim;

    IEnumerator Start()
    {
        yield return new WaitForSeconds(2f);

        anim.GetComponent<Animation>().Play();

        Application.LoadLevel(Application.loadedLevel + 1);
    }

}

```

The problem is: when I try to attach the animation the Inspector refuses to do it.

Any ideas? Thanks

# Answer
> 2 votes
You aren't waiting on the animation so once you play it `Application.LoadLevel` just does its thing and you wont notice the animation.

First, you'll need a way to wait on the animation which could be a simple coroutine:

```
private IEnumerator WaitForAnimation ( Animation animation )
{
do
    {
        yield return null;
    } while ( animation.isPlaying );
}

```

And then use it to yield before calling `Application.LoadLevel`:

```
    ...
    anim.Play();
    yield WaitForAnimation(anim);

    Application.LoadLevel(Application.loadedLevel + 1);
}

```

Also, you don't need to call `GetComponent<Animation>` on an `Animation`.

# Answer
> 0 votes
I noticed that you created a coroutine but never called it, by using StartCoroutine().

---
Tags: animation, unity
---


title: How to correctly draw a line in Unity

text:
# Question
Title: How to correctly draw a line in Unity
I'm working on a game which requires me to draw a few lines from a single point that is more formally said

Given point A with coordinates x,y I draw n lines where the i-th line has the coordinates named as xi,yi. Given the LineRenderer capabilities inside Unity3D I was unable to draw more than one line from a particular point with it since it renders only polylines.

I'm currently using the Debug.DrawLine() method which successfully renders the line. I have tried using GL.Begin() as it is shown in the Unity example but I cannot see my lines being drawn.

My question is : are there any other methods for doing this? If not, can you tell me how can I show the line that is being drawn with Debug.DrawLine() inside play mode? I've saw that I could use Gizmos.DrawLine() but I didn't quite understand it's usage.

# Answer
> 54 votes
# Using GL Lines:

I would recommend using the the GL API for drawing lines. The line thickness will always be 1px on screen and there is no option to change it. There will also be no shadows.

The GL method calls are executed immediately so you need to make sure to call them after the camera has already rendered.

Attaching the script to the camera and using Camera.OnPostRender() works good for rendering in the game window. To get them to show in the editor, you can use MonoBehaviour.OnDrawGizmos().

Here is the barebones code to draw a line with the GL API (note, this code does not work in modern Unity):

```
public Material lineMat = new Material("Shader \"Lines/Colored Blended\" {" + "SubShader { Pass { " + "    Blend SrcAlpha OneMinusSrcAlpha " + "    ZWrite Off Cull Off Fog { Mode Off } " + "    BindChannels {" + "      Bind \"vertex\", vertex Bind \"color\", color }" + "} } }");

void OnPostRender() {
    GL.Begin(GL.LINES);
    lineMat.SetPass(0);
    GL.Color(new Color(0f, 0f, 0f, 1f));
    GL.Vertex3(0f, 0f, 0f);
    GL.Vertex3(1f, 1f, 1f);
    GL.End();
}

```

Here is a full script that attaches all of the given points to the main point. There are some instructions in the comments of the code to get it set up right and about what is going on.

If you are having problems changing the color of the connecting lines, make sure to use a shader on your line material that takes into account the vertex color such as `Unlit/Color`.

```
using UnityEngine;
using System.Collections;

// Put this script on a Camera
public class DrawLines : MonoBehaviour {

    // Fill/drag these in from the editor

    // Choose the Unlit/Color shader in the Material Settings
    // You can change that color, to change the color of the connecting lines
    public Material lineMat;

    public GameObject mainPoint;
    public GameObject[] points;

    // Connect all of the `points` to the `mainPoint`
    void DrawConnectingLines() {
        if(mainPoint && points.Length > 0) {
            // Loop through each point to connect to the mainPoint
            foreach(GameObject point in points) {
                Vector3 mainPointPos = mainPoint.transform.position;
                Vector3 pointPos = point.transform.position;

                GL.Begin(GL.LINES);
                lineMat.SetPass(0);
                GL.Color(new Color(lineMat.color.r, lineMat.color.g, lineMat.color.b, lineMat.color.a));
                GL.Vertex3(mainPointPos.x, mainPointPos.y, mainPointPos.z);
                GL.Vertex3(pointPos.x, pointPos.y, pointPos.z);
                GL.End();
            }
        }
    }

    // To show the lines in the game window whne it is running
    void OnPostRender() {
        DrawConnectingLines();
    }

    // To show the lines in the editor
    void OnDrawGizmos() {
        DrawConnectingLines();
    }
}

```

*Further note on shadows:* I explored using a geometry shader to make shadows but since the GL calls run immediately, they are not in the normal rendering pipeline and `AutoLight.cginc` and `Lighting.cginc` won't pick up the `ShadowCaster` pass.

---

# Lines with Shadows and Radius

If you need to change the line thickness and want to have realistic shadows. Just use a cylinder mesh and scale the height.

Here is a script that will make a cylinder to connect each point to the main point. Place it on a empty game object and fill in the parameters. It will hold all of the extra connecting objects.

```
using UnityEngine;
using System.Collections;

public class ConnectPointsWithCylinderMesh : MonoBehaviour {

    // Material used for the connecting lines
    public Material lineMat;

    public float radius = 0.05f;

    // Connect all of the `points` to the `mainPoint`
    public GameObject mainPoint;
    public GameObject[] points;

    // Fill in this with the default Unity Cylinder mesh
    // We will account for the cylinder pivot/origin being in the middle.
    public Mesh cylinderMesh;

    GameObject[] ringGameObjects;

    // Use this for initialization
    void Start () {
        this.ringGameObjects = new GameObject[points.Length];
        //this.connectingRings = new ProceduralRing[points.Length];
        for(int i = 0; i < points.Length; i++) {
            // Make a gameobject that we will put the ring on
            // And then put it as a child on the gameobject that has this Command and Control script
            this.ringGameObjects[i] = new GameObject();
            this.ringGameObjects[i].name = "Connecting ring #" + i;
            this.ringGameObjects[i].transform.parent = this.gameObject.transform;

            // We make a offset gameobject to counteract the default cylindermesh pivot/origin being in the middle
            GameObject ringOffsetCylinderMeshObject = new GameObject();
            ringOffsetCylinderMeshObject.transform.parent = this.ringGameObjects[i].transform;

            // Offset the cylinder so that the pivot/origin is at the bottom in relation to the outer ring gameobject.
            ringOffsetCylinderMeshObject.transform.localPosition = new Vector3(0f, 1f, 0f);
            // Set the radius
            ringOffsetCylinderMeshObject.transform.localScale = new Vector3(radius, 1f, radius);

            // Create the the Mesh and renderer to show the connecting ring
            MeshFilter ringMesh = ringOffsetCylinderMeshObject.AddComponent<MeshFilter>();
            ringMesh.mesh = this.cylinderMesh;

            MeshRenderer ringRenderer = ringOffsetCylinderMeshObject.AddComponent<MeshRenderer>();
            ringRenderer.material = lineMat;

        }
    }

    // Update is called once per frame
    void Update () {
        for(int i = 0; i < points.Length; i++) {
            // Move the ring to the point
            this.ringGameObjects[i].transform.position = this.points[i].transform.position;

            // Match the scale to the distance
            float cylinderDistance = 0.5f*Vector3.Distance(this.points[i].transform.position, this.mainPoint.transform.position);
            this.ringGameObjects[i].transform.localScale = new Vector3(this.ringGameObjects[i].transform.localScale.x, cylinderDistance, this.ringGameObjects[i].transform.localScale.z);

            // Make the cylinder look at the main point.
            // Since the cylinder is pointing up(y) and the forward is z, we need to offset by 90 degrees.
            this.ringGameObjects[i].transform.LookAt(this.mainPoint.transform, Vector3.up);
            this.ringGameObjects[i].transform.rotation *= Quaternion.Euler(90, 0, 0);
        }
    }
}

```

# Answer
> 7 votes
# Lines with Shadows and Radius via Cube

Going off of @MadLittleMod's answer, here another version using Cube based lines(*tris: 12*) instead of Cylinder based lines(*tris: 80*):

```
using UnityEngine;
using System.Collections;

public class ConnectPointsWithCubeMesh : MonoBehaviour
{

    // Material used for the connecting lines
    public Material lineMat;

    public float radius = 0.05f;

    // Connect all of the `points` to the `mainPoint`
    public GameObject mainPoint;
    public GameObject[] points;

    // Fill in this with the default Unity Cube mesh
    // We will account for the cube pivot/origin being in the middle.
    public Mesh cubeMesh;

    GameObject[] ringGameObjects;

    // Use this for initialization
    void Start()
    {
        this.ringGameObjects = new GameObject[points.Length];
        //this.connectingRings = new ProceduralRing[points.Length];
        for(int i = 0; i < points.Length; i++) {
            // Make a gameobject that we will put the ring on
            // And then put it as a child on the gameobject that has this Command and Control script
            this.ringGameObjects[i] = new GameObject();
            this.ringGameObjects[i].name = "Connecting ring #" + i;
            this.ringGameObjects[i].transform.parent = this.gameObject.transform;

            // We make a offset gameobject to counteract the default cubemesh pivot/origin being in the middle
            GameObject ringOffsetCubeMeshObject = new GameObject();
            ringOffsetCubeMeshObject.transform.parent = this.ringGameObjects[i].transform;

            // Offset the cube so that the pivot/origin is at the bottom in relation to the outer ring     gameobject.
            ringOffsetCubeMeshObject.transform.localPosition = new Vector3(0f, 1f, 0f);
            // Set the radius
            ringOffsetCubeMeshObject.transform.localScale = new Vector3(radius, 1f, radius);

            // Create the the Mesh and renderer to show the connecting ring
            MeshFilter ringMesh = ringOffsetCubeMeshObject.AddComponent<MeshFilter>();
            ringMesh.mesh = this.cubeMesh;

            MeshRenderer ringRenderer = ringOffsetCubeMeshObject.AddComponent<MeshRenderer>();
            ringRenderer.material = lineMat;

        }
    }

    // Update is called once per frame
    void Update()
    {
        for(int i = 0; i < points.Length; i++) {
            // Move the ring to the point
            this.ringGameObjects[i].transform.position = this.points[i].transform.position;

            this.ringGameObjects[i].transform.position = 0.5f * (this.points[i].transform.position + this.mainPoint.transform.position);
            var delta = this.points[i].transform.position - this.mainPoint.transform.position;
            this.ringGameObjects[i].transform.position += delta;

            // Match the scale to the distance
            float cubeDistance = Vector3.Distance(this.points[i].transform.position, this.mainPoint.transform.position);
            this.ringGameObjects[i].transform.localScale = new Vector3(this.ringGameObjects[i].transform.localScale.x, cubeDistance, this.ringGameObjects[i].transform.localScale.z);

            // Make the cube look at the main point.
            // Since the cube is pointing up(y) and the forward is z, we need to offset by 90 degrees.
            this.ringGameObjects[i].transform.LookAt(this.mainPoint.transform, Vector3.up);
            this.ringGameObjects[i].transform.rotation *= Quaternion.Euler(90, 0, 0);
        }
    }
}

```

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


# Question
Title: Can I use an asset that looks identical to another persons product?
A question on intellectual property law for anyone that's made game assets before.

I'm considering making a commercial game, in this game there will be some assets that look identical to real life products and it's important that they do look exactly the same. An example would be a laptop that looks exactly like the real life laptop it's modeled on including branding in the same locations.

Is this legal?

# Answer
You should consult a lawyer.

It may be possible to do this, depending on the products in question, your legal jurisdiction, the legal jurisdiction(s) in which the products have IP protections, and so on. You're going to need a lawyer to help you unravel all the tangled, varied license legalese though.

You specifically cite the example of laptops, and the branding on those laptops. That branding is almost certainly going to require complying with license terms (here are legal notices containing relevant data for Acer, Apple, HP, Lenovo and Microsoft, just to name a few... and some of those are US-specific).

Other sorts of products may vary, you're going to want to do research and confirm the legality of using *every single* item you want, probably individually, as there aren't really many blanket rules.

Guns and cars *do* require licensing from the appropriate manufacturers, for example. And while it might be acceptable to model a coffee mug that is "exactly like" some other generic coffee mug, you probably can't model it exactly like a *specific* coffee mug because the logos on the mug might be protected by intellectual property laws, as before. There are even logos and branding that one might *assume* is safe for public use, being from government agencies, but even that is often covered by some kind of protection.

In short, even if you can afford a lawyer to help track down and make all the arrangements, I question that the result would be worth the time, effort and cost. Generally if you're trying to find out "how close" you can mimic a thing without legal repercussions you are on the wrong path and should find a new one.
> 5 votes

# Answer
It will certainly be illegal if either of the following are true:

* The product is protected by a certain industrial design right called a *design patent*, which prohibits using copycat designs. Cars are a common example of products protected by design patents. Even specific aesthetic elements of a product can by copyrighted (e.g. the bezel of the iPhone is a legally protected design.) See here for more info: https://en.wikipedia.org/wiki/Design\_patent
* You include any logos which have been trademarked.

Even if neither of those are true in your case, you're still walking on very shaky ground. You could try to make a fair-use argument, but that's not nearly as protective as some folks seem to think.

Regardless of all that, you need to keep in mind that a multi-million/billion dollar corporation is quite capable of financially annihilating you in the event of a legal boxing match. Even if you win, you lose. Why risk it?
> 0 votes

---
Tags: assets, copyright, intellectual-property
---


# Question
Title: How to make the character cannot pass through other randomly moving objects when they are collided?
As the title above, how can i make my random wallImg solid enough so that my birdImg cannot pass through it from any sides of the wallImg? Here's the code of Processing's Crappy Bird that i've altered so my game will be running upside down instead of sidescrolling. Any help will be appreciated

```
PImage backImg;
PImage birdImg;
PImage wallImg;
PImage startImg;

int gamestate = 1;
int score = 0;
int highScore = 0;
float speed;
boolean moveLeft, moveRight, moveUp, moveDown;

int x = -200;
int y;
int vy = 0;
int wx[] = new int[2];
int wy[] = new int[2];

//initiate and declare
Bird playerBird = new Bird (x, y, vy);

void setup()
{
  size(600,800);
  fill(0);
  textSize(40);
  speed = 2;
  backImg =loadImage("cXaR0vS.png");
  birdImg =loadImage("mw0ai3K.png");
  wallImg =loadImage("4SUsUuc.png");
  startImg=loadImage("U6KEwxe.png");

}

void draw()
{
  if(gamestate == 0) {
    imageMode(CORNER);
    image(backImg, 0, x);
    image(backImg, 0,x-backImg.height);
    x += 6;
    vy += 1;
    y += vy;
    if(x >= 800) x = 0;
    for(int i = 0 ; i < 2; i++) {
      imageMode(CENTER);
      image(wallImg, wy[i] - (wallImg.width/2+100),wx[i]);
      image(wallImg, wy[i] + (wallImg.width/2+100), wx[i]);
      if(wx[i] > 900) {
        wy[i] = (int)random(200,width-200);
        wx[i] = 0;
      }
      if(wx[i] == width/2) highScore = max(++score, highScore);
      if((abs(width/2-wx[i])<25 && abs(y-wy[i])>100))playerBird.y=wy[i];
      wx[i] += 6;
    }
    playerBird.y = y;
    playerBird.drawBird();
    text(""+score, width/2-15, 700);
  }
  else {
    imageMode(CENTER);
    image(startImg, width/2,height/2);
    text("High Score: "+highScore, 50, width);
  }
}

void mousePressed() {
  if(gamestate==1) {
    wx[0] = 400;
    wy[0] = y = width/2;
    wx[1] = 0;
    wy[1] = 600;
    x = gamestate = score = 0;
  }
}
void keyPressed() {
  // vy = -17;
  if(keyCode == UP)
    {
      vy = -17;
    }
  if (key == CODED) {
     if (keyCode == LEFT) {
       moveLeft = true;
     } else if(keyCode == RIGHT) {
       moveRight = true;
     }
  }
}

void keyReleased() {
  vy=-17;
  if (key == CODED) {
     if (keyCode == LEFT) {
       moveLeft = false;
     } else if(keyCode == RIGHT) {
       moveRight = false;
     }
  }
}

//bird class
class Bird
{
  int x;
  int y;
  int vy;
  float speed;
  float xPos;

  //constructor
  Bird(int tempX,int tempY,int tempVy)
  {
    x= tempX;
    y= tempY;
    vy= tempVy;
    speed = 5;
    xPos = width/2;
  }

  void drawBird(){
    image(birdImg, xPos , y);
    if(moveLeft&&xPos>=20) xPos -= speed;
    if(moveRight&&xPos<=580)xPos += speed;
  }
}
```

---

I manage to get the character to be able to stay on top of the platform 'wallImg' from above but I can't make my character from jumping through the platform from below. Any ideas?

```
PImage backImg;
PImage birdImg;
PImage wallImg;
PImage startImg;

int gamestate = 1;
int score = 0;
int highScore = 0;
float speed;
boolean moveLeft, moveRight, moveUp, moveDown;
int minX;
int maxX;

int x = -200;
int y;
int vy = 0;
int wx[] = new int[2];
int wy[] = new int[2];

//initiate and declare
Bird playerBird = new Bird (x, y, vy);

void setup()
{
  size(600,800);
  fill(0);
  textSize(40);
  speed = 2;
  backImg =loadImage("cXaR0vS.png");
  birdImg =loadImage("mw0ai3K.png");
  wallImg =loadImage("4SUsUuc.png");
  startImg=loadImage("U6KEwxe.png");

}

void draw()
{
  if(gamestate == 0) {
    imageMode(CORNER);
    image(backImg, 0, x);
    image(backImg, 0,x-backImg.height);
    x += 6;
    vy += 1;
    y += vy;
    if(x >= 800) x = 0;
    for(int i = 0 ; i < 2; i++) {
      imageMode(CENTER);
      image(wallImg, wy[i] - (wallImg.width/2+100),wx[i]);
      image(wallImg, wy[i] + (wallImg.width/2+100), wx[i]);
      if(wx[i] > 900) {
        wy[i] = (int)random(200,width-200);
        wx[i] = 0;
      }
      minX = wy[i] - (wallImg.width/2+400);
      maxX = wy[i] + (wallImg.width/2);
      if(wx[i] == width/2) highScore = max(++score, highScore);

      if((abs(width/2-wy[i])<25 && abs(y-wy[i])>maxX)){
        playerBird.y=wy[i];

      }
      /*COLLISION */
      int collisionTestY1 = wx[i] - 50;
      int collisionTestY2 = wx[i] + 50;
      int collisionTestX1 = wy[i] + 100;
      int collisionTestX2 = wy[i] + (wallImg.width/2);
      int collisionTestXX1 = wy[i] - 100;
      int collisionTestXX2 = wy[i] - (wallImg.width/2);

      if(playerBird.xPos >= collisionTestX1 && playerBird.xPos <= collisionTestX2 && playerBird.y <= collisionTestY2 && playerBird.y >= collisionTestY1){
        vy=0;
        print("lol");
      }

      if(playerBird.xPos <= collisionTestXX1 && playerBird.xPos >= collisionTestXX2 && playerBird.y <= collisionTestY2 && playerBird.y >= collisionTestY1){
        vy=0;
      }
      //line(collisionTestX1,collisionTestY1,collisionTestX2,collisionTestY1);
      //line(wy[i]-100,wx[i]+10,minX,wx[i]+10);
      //line(wy[i],wx[i],wy[i] - wallImg.width/2,wx[i]);
      wx[i] += 6;
    }
    playerBird.y = y;
    playerBird.drawBird();
    text(""+score, width/2-15, 700);
  }
  else {
    imageMode(CENTER);
    image(startImg, width/2,height/2);
    text("High Score: "+highScore, 50, width);
  }
}
void mousePressed() {
  if(gamestate==1) {
    wx[0] = 400;
    wy[0] = y = width/2;
    wx[1] = 0;
    wy[1] = 600;
    x = gamestate = score = 0;
  }
}
void keyPressed() {
  // vy = -17;
  if(keyCode == UP)
    {
      vy = -17;
    }
  if (key == CODED) {
     if (keyCode == LEFT) {
       moveLeft = true;
     } else if(keyCode == RIGHT) {
       moveRight = true;
     }
  }
}
void keyReleased() {
  vy=-17;
  if (key == CODED) {
     if (keyCode == LEFT) {
       moveLeft = false;
     } else if(keyCode == RIGHT) {
       moveRight = false;
     }
  }
}
//bird class
class Bird
{
  int x;
  int y;
  int vy;
  float speed;
  float xPos;

  //constructor
  Bird(int tempX,int tempY,int tempVy)
  {
    x= tempX;
    y= tempY;
    vy= tempVy;
    speed = 5;
    xPos = width/2;
  }
  void drawBird(){
    image(birdImg, xPos , y);
    if(moveLeft&&xPos>=20) xPos -= speed;
    if(moveRight&&xPos<=580)xPos += speed;
  }
}
```

# Answer
You have to write your own collision checks and solve collisions when they occur. Processing has no build in collision checks.

**Solving collisions can mean several things:**

1. Mostly it means, that you cancel the movement that created the collision. Or you modify the movement to another direction eith lower magnitude in another direction. (Imagine running diagonally towards a wall, when you hit it you might want to move further along the wall)
2. Or it means that you start some event(s) when your collision ist registered (For example "Game over" or activating something when you step on something)

You also have several **ways of detecting a collision:**

1. You could do pixel wise checks (checking if individual non-transparent pixels of the images overlap)
2. You could use hitboxes with simpler shapes and check them against each other (Bounding rectangles or bounding spheres)
3. You could use sensors to check if something is right mexzlt to your objects and adjust xour movement accordingly. (I don't recommend this option, as it can be tedious to implement if your background is multicolor or your game gets more and more complex. Hitboxes are imo cleaner)
> 1 votes

# Answer
Assuming that your walls are squares/rectangles, and that your bird is also squareish (if it isn't the collision detection in the method I'm going to show you might be a bit funny)

```
int x1 = objA.X;
int x2 = objB.X;
int y1 = objA.Y;
int y2 = objB.Y;
int X1 = x1 + objA.Width;
int X2 = x2 + objB.Width;
int Y1 = y1 + objA.Height;
int Y2 = y2 + objB.Height;

if (Y1 < y2)
    return false;
if (y1 > Y2)
    return false;
if (X1 < x2)
    return false;
if (x1 > X2)
    return false;

return true;

```

if you create a method where object A is your bird and object B is your wall, if it returns false, change the velocity of your bird.

You'll need to do a for loop for each wall, for example

```
for(int i = 0; i < WALLCOUNT; i++)

```
> 0 votes

---
Tags: javascript, collision-resolution, processing
---


# Question
Title: How do I make players believe they're doing something wrong even when they're not?
**You're doing it right. …right?**

In the game *Cart Life*, you are led to consider this, even though you are doing fine. This effect is created by making you do mundane jobs, earn little money, and have and things happen that feel like your fault.

Is there a better way than life-like mundane and unfortunate encounters to make you feel like you're failing at the game? I want to use this to mess with how my players play the game. Overwhelm them. Make a little success feel huge. Make them feel depth. Any ideas?

# Answer
The usual expectation of a player is that while they progress in the game that everything turns better. Their character becomes more powerful, they gain new tools and abilities, the game world around them grows and flourishes thank to their actions and they gain the trust and friendship of NPCs they interact with.

Turn that around:

* Take away tools and abilities from the player-character to make it permanently less powerful.
* Have the game world change for the worse, caused directly or indirectly due to the player-characters actions.
* NPCs who reacted positive to them start to loathe the player-character for their actions.

The tricky part is to make all of them feel as if it was the direct consequence of the choices or mistakes the player made while it actually was all prescripted and there wasn't a way to avoid it. Some techniques you can use:

* The hopeless boss fight: Have a fight which looks possible at first but actually can not be won. When the player loses, punish them but progress with the story.
* Unwinable dexterity test. Example: Have the player jump over a chasm, and when they land on the other side it breaks off, they fall down and end up at the bottom of the chasm with barely any health left. Foolish player, should have seen the other side was crumbly. But it actually was impossible to jump far enough. You expect the player to continue from the bottom of the cliff. Other situation where you can cheat that way are QTEs which don't actually react to the players input or any game mechanics which are usually based on random numbers but in the story-critical situation a critical failure is pre-programmed.
* A choice where all options are wrong: Have the player decide between two options, but then have friendly NPCs tell them the choice was bad and they should have taken the other choice no matter which was chosen. This was, for example, used in Mass Effect 2. At one point the player is asked if they want to exterminate the last survivors of a dangerous alien species or let them live. If the player choses to let them live, their superiors tell them *"How could you!?! They are dangerous and will kill us all!"*. If the player kills them they say *"How could you!?! That's genocide!"*. During the first playthrough the player won't know that both choices would lead to a negative reaction, so they felt like they made a bad mistake no matter which one they picked.
> 3 votes

# Answer
**Teach the player what success is first**

In a traditional game, like a platformer, you would first need to teach the player the difference between **doing it right**, and **doing it wrong**. You teach the player that jumping over gaps is **good** and touching spikes is **bad** -force them to jump over a spike-pit.

Now that the player knows what they should be doing, you can start to bully them. Give them a gap that is slightly too large to jump across, but still looks doable. Failing the jump causes you land on a button which closes-off a door with a big prize behind it.

Congratulations! You've just made the player fail, and it's all **their fault**.
> 3 votes

# Answer
Like most things, the easiest way to create other ways to achieve an effect is to examine and find what aspect of the original example causes that effect. In this case, the player feels as if they are failing because they are **primed** to have the **expectation** that bad things in video games are their fault. This is because most games reward good performance with good results. Unfortunately, and as you guessed, this is a rather short-term (or cheap) method of evoking the feeling of failure because it relies on our cultural expectations of games, which could change at any moment.

Instead, you can use the most basic function of the brain to help you: **Association**. Whenever two event occur simultaneously or even just temporally close together, a brain immediately attempts to find which caused the other, unless prior knowledge says something else did. Here is an example...

In *Generic game 2015*, the main protagonist Bob shoots his generic spaceship at generic aliens. If the player gets over 20,000 points in a level (a somewhat difficult feat), then the attack is successfully repelled. On the other hand, if Bob acquires less than 15,000 points, the aliens will destroy a building located in the background. If the player does poorly, they know by the loss of a building. This is a successful priming.

What this means is that in player's mind, any time a building falls, the player is not doing well enough. You now have a tool to toy with their mind because, any time the event of a building falling is triggered, the player and their association will trigger the feeling of failure **whether or not it is justified**. *(stifled evil laugh)* Its probably useless at this point to say you can make building start destroying themselves and still achieve the same illusion of failure.

But there are two last things to take note of.

**1**

The first is about player knowledge. If you want the player to feel like they failed without them actually failing, the mechanics have to include that. When the mechanics include the fake fail, it gets put on a wiki. Finally, the player reads the wiki, and no longer feel any failure at all. But their is a partial solution to this.

While security through obscurity is completely hopeless, you can utilize randomness so that even if the player knows all your algorithms *to a T*, the game can generate a situation that the player is still unsure whether or not the failure queue is their fault or not. Maybe the game has chosen to drop buildings even when you gain enough points, or maybe it actually is that your failing.

**2**

The exact example I have given is a somewhat weak one. Ideally, the failure trigger should be woven into the narrative for greater effect (because that is where the characters and other objects are that carry emotional attachments). Eg: If each building being destroyed contains an important member of the story-line.
> 3 votes

# Answer
This is similar to real life: use peer pressure on your character.

In order to tell them they are failing, I would make the action (that it NOT a failure) sound bad:
1. NPCs calling this action dirty, etc.
2. having the character be PUNISHED for doing this. For example, if you buy a X, you get banned from doing Y for Z days. \[I would recommend a reward if they are stubborn enough to continue this by the 5th-10th time\]. You could also lose friends, achievement points, etc.

You could also teach the user to do one way half of his life then make a change (for example new teacher) that does this another way. Suddenly, the player has to decide whether or not to listen to the first or second way.
If you feel like it, you could implement a way to fool users that they are doing wrong by making them experience a messagebox or warning of some sort. For example, if you were playing COD and the people on your team \[bots\] tell you to stop shooting player X as he is on your team (when in reality not true). If this was GTA, then you could implement a feature where every time you went over 30 mph a tank spawns behind you (not sure if that would be that persuasive, however). In other words, just put pressure on the player in order to tilt him to the direction you are aiming at.
> 2 votes

---
Tags: game-design, psychology
---


title: Optimizing my 3D XNA game

text:
# Question
Title: Optimizing my 3D XNA game
I've come to a point where optimizing my game is very much needed.My update() routine takes 0-2ms. My draw() routine takes about 100ms when drawing 3.5M triangles (Not the amount I really have to draw, but it's easier to debug.) I've noticed that reducing draw calls is more effective than reducing triangles per draw call (and keeping the amount of draw calls the same), and would primarily like to know how to do that.

I've tried creating an array, adding items to that array every frame until it has about 65535 primitives in it (the maximum xna allows per draw call) and only drawing it then, but resizing the array is a terribly slow thing to do (drawing only 250k triangles takes about 500ms)

So long story short: In XNA, how do I properly optimize the drawing methods that use DrawUserIndexedPrimitives? Or primarily, how do I properly reduce draw calls?

# Answer
There are few simple rulrs that allways help me:

1. cull not visible meshes using frustrum based on camera view
2. minimize textures count: use tile maps, draw meshes with same textures in one line etc.
3. dont create anithing in Draw method and dont create anithing you can keep and use again, like static meshes, render targets etc.
4. if it not help use Stopwatch to see what is wrong
> 4 votes

---
Tags: xna, vb.net
---


# Question
Title: How do i set gravity towards a point in the centre in AndEngine with Box2D?
I have a scene and i can set gravity in the PhysicsWorld like

```
this.mPhysicsWorld = new PhysicsWorld(new Vector2(0, -SensorManager.GRAVITY_EARTH),false);

```

but i would like all bodies to gravitate to a point.

I tried

```
physicsWorld.setGravity(new Vector2(centerX, centerY));

```

but that has not worked- i assume because i need to calculate the vector to the centre. But I'm not sure how to do that and where to calculate it so it changes.

I would like the input (of force) to be from the touch handler of the sprite. The sprite at the moment can be moved via

```
@Override
    public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
            float pTouchAreaLocalX, float pTouchAreaLocalY) {

        //this.setPosition(pSceneTouchEvent.getX() - this.getWidth() / 2, pSceneTouchEvent.getY() - this.getHeight() / 2);

        if (pSceneTouchEvent.isActionMove() || pSceneTouchEvent.isActionDown() || pSceneTouchEvent.isActionOutside())
        {
            this.setX(pSceneTouchEvent.getX() - this.getWidth() / 4);
            this.setY(pSceneTouchEvent.getY() - this.getHeight() / 4);
        }

        return true;
    }

```

I would like to do the calculation in there so as the sprite is dragged, the vector changes, then when it's released it should 'fall' to the centre

EDIT:

Mass can be set as 1 unit since it's not relevant

Thanks for the help.

# Answer
You don't do it by trying to set the global gravity. Instead you set the global gravity to zero and then you calculate the force that your gravity would affect the object with and apply that.

Pseudo-code-wise it could look something like this;

```
Vector2 centerOfGravity = new Vector2(someX, someY);

void update(float deltaTime) {

    physicsWorld.Step(deltaTime, numberOfIterations)

    foreach Body body in allYourBodies {
       Vector2 gravityDirection = normalize(centerOfGravity - body.getPosition())
       Vector2 bodyGravity = body.mass * gravityDirection * some_scalar_to_make_it_look_right

       body.ApplyForce(bodyGravity, body.getPosition()
    }
}

```

I don't use **AndEngine** (anymore) but the **Box2D** API is similar in **libGDX** so you should be able to easily translate this example, it yields results like  or

The complete, very dirty, code I used to generate that looks like this;

package com.bornander.androidstudiosandbox;

```
    import com.badlogic.gdx.ApplicationAdapter;
    import com.badlogic.gdx.Gdx;
    import com.badlogic.gdx.graphics.GL20;
    import com.badlogic.gdx.graphics.OrthographicCamera;
    import com.badlogic.gdx.graphics.Texture;
    import com.badlogic.gdx.graphics.g2d.SpriteBatch;
    import com.badlogic.gdx.math.MathUtils;
    import com.badlogic.gdx.math.Vector2;
    import com.badlogic.gdx.math.Vector3;
    import com.badlogic.gdx.physics.box2d.Body;
    import com.badlogic.gdx.physics.box2d.BodyDef;
    import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
    import com.badlogic.gdx.physics.box2d.CircleShape;
    import com.badlogic.gdx.physics.box2d.FixtureDef;
    import com.badlogic.gdx.physics.box2d.PolygonShape;
    import com.badlogic.gdx.physics.box2d.Shape;
    import com.badlogic.gdx.physics.box2d.World;

    import java.util.ArrayList;
    import java.util.List;
    import java.util.Random;

    public class MyAndroidStudioSandboxGame extends ApplicationAdapter {
        SpriteBatch batch;
        Texture img;
        World world;
        OrthographicCamera camera;
        Box2DDebugRenderer renderer;
        List<Body> bodies = new ArrayList<Body>();

        @Override
        public void create () {
            batch = new SpriteBatch();
            img = new Texture("badlogic.jpg");

            camera = new OrthographicCamera(100, 100);
            camera.position.set(0,0,0);

            world = new World(Vector2.Zero, true);

            renderer = new Box2DDebugRenderer();

            Body planet = createCircle(5, 0, 0);
            planet.setType(BodyDef.BodyType.StaticBody);

            Random rnd = new Random();
            for(int i = 0; i < 10; ++i) {
                float angle = rnd.nextFloat() * MathUtils.PI2;
                Vector2 pos = (new Vector2(MathUtils.sin(angle), MathUtils.cos(angle))).scl(20 + rnd.nextFloat() * 30);
                Body body = createCircle(1.0f + rnd.nextFloat(), pos.x, pos.y);
                bodies.add(body);
                Vector2 dir = pos.nor();
                dir.set(dir.y, -dir.x);
                dir.scl(8);
                body.setLinearVelocity(dir);

            }

        }

        private Body createBox(float w, float h, float x, float y) {
            BodyDef nodeBodyDefinition = new BodyDef();
            nodeBodyDefinition.type = BodyDef.BodyType.DynamicBody;
            Vector2 center = new Vector2();
            nodeBodyDefinition.position.set(10, 10);

            PolygonShape shape = new PolygonShape();
            float density = 1.0f;
            shape.setAsBox(w / 2.0f, h / 2.0f);

            Body body = world.createBody(nodeBodyDefinition);
            body.setUserData(this);
            body.setTransform(x, y, 0);
            final FixtureDef nodeFixtureDefinition = createFixtureDefinition(shape, density);

            body.createFixture(nodeFixtureDefinition);
            shape.dispose();

            return body;
        }

        private Body createCircle(float r, float x, float y) {
            BodyDef nodeBodyDefinition = new BodyDef();
            nodeBodyDefinition.type = BodyDef.BodyType.DynamicBody;
            Vector2 center = new Vector2();
            nodeBodyDefinition.position.set(10, 10);

            CircleShape shape = new CircleShape();
            float density = 1.0f;
            shape.setRadius(r);

            Body body = world.createBody(nodeBodyDefinition);
            body.setUserData(this);
            body.setTransform(x, y, 0);
            final FixtureDef nodeFixtureDefinition = createFixtureDefinition(shape, density);

            body.createFixture(nodeFixtureDefinition);
            shape.dispose();

            return body;
        }

        private static FixtureDef createFixtureDefinition(final Shape shape, final float density) {
            final FixtureDef nodeFixtureDefinition = new FixtureDef();
            nodeFixtureDefinition.shape = shape;
            nodeFixtureDefinition.friction = 1;
            nodeFixtureDefinition.density = density;
            nodeFixtureDefinition.restitution = 0.1f;
            return nodeFixtureDefinition;
        }

        @Override
        public void render () {
            Gdx.gl.glClearColor(0, 0, 0, 1);
            Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

            world.step(Gdx.graphics.getDeltaTime(), 4, 4);
            camera.update();

            for(Body body : bodies) {
                Vector2 gravityDirection = (new Vector2()).sub(body.getWorldCenter().x, body.getWorldCenter().y);
                gravityDirection.scl(10);
                body.applyForce(gravityDirection, body.getWorldCenter(), true);
            }

            renderer.render(world, camera.combined);
        }
    }

```
> 3 votes

---
Tags: android, box2d, andengine
---


# Question
Title: In XNA, how do I get forms to display in front of my full-screen game?
I'm trying to open a form in front of my game, which is full-screen. However, the form seems to appear only behind the game window.

At the moment, I'm doing this:

```
protected override void Update(GameTime gameTime)
    {
        if(Keyboard.GetState().IsKeyDown(Keys.Q))
        {
            graphics.IsFullScreen = true;
            graphics.ApplyChanges();
            new Form1().Show();
            // The form is empty, just created.
        }
        base.Update(gameTime);
    }

```

I can reach the form with `Alt``Tab`, but this is unfriendly to the user.

How can I do this correctly?

# Answer
Here is the solution for you: (which I use myself)

```
Form form = new Form();

form.SetBounds(100, 100, 800, 600);
form.TopMost = true;
form.Text = "Title";

form.Show(); //You can access to parent form.
//OR
form.ShowDialog(); //You can't access to parent form.

```

---

## EDIT :

This is my method, which I use to make my game fullscreen. I find this method better than graphics.IsFullScreen.

```
[DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(String className, String windowName);

[DllImport("user32.dll", SetLastError = true)]
static extern void SwitchToThisWindow(IntPtr hWnd, bool turnOn);

System.Windows.Form gameForm;

protected override void Initialize()
{
    /* ------ OPTIONAL ------ */
    graphics.PreferredBackBufferWidth = 1280;
    graphics.PreferredBackBufferHeight = 720;
    graphics.PreferMultiSampling = false;
    graphics.ApplyChanges();
    /* ---------------------- */

    System.Windows.Forms.Application.EnableVisualStyles();
    gameForm = (System.Windows.Forms.Form)System.Windows.Forms.Form.FromHandle(Window.Handle);
    gameForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
    //gameForm.TopMost = true;
    gameForm.WindowState = System.Windows.Forms.FormWindowState.Maximized;
    gameForm.Bounds = System.Windows.Forms.Screen.PrimaryScreen.Bounds;
    gameForm.GotFocus += new EventHandler(gameForm_GotFocus);
    base.Initialize();
}

void gameForm_GotFocus(object sender, EventArgs e)
{
    gameForm.WindowState = System.Windows.Forms.FormWindowState.Maximized;
    gameForm.Bounds = System.Windows.Forms.Screen.PrimaryScreen.Bounds;
}

protected override void LoadContent()
{
    //...
    gameForm.Focus();
    gameForm.BringToFront();
    SwitchToThisWindow(gameForm.Handle, true);
}

```
> 2 votes

# Answer
you need real full-screen? many games have 3 options:

1. windowed
2. fullscreen
3. fullscreen-windowed

the last is very simple, just create a winforms window without border and stretch it to the whole size of the screen.
> 0 votes

# Answer
WinForms are not supported in XNA. You can render XNA into a form control, however, that is also not supported, however it can work.

The better option, is to use a library that provides form controls from inside of XNA. Check out http://www.xnacontrols.codeplex.com

Or you can always write your own.
> -1 votes

---
Tags: xna, windows-forms
---


# Question
Title: Why is FindObjectOfType(MyType) not finding anything?
Why would I get the following log?

* Start OpponentMotionReceiver
* motion receiver not found
* true

---

```
    public class ScoreAnimation : MonoBehaviour
    {
        private OpponentMotionReceiver cachedObject;

        private void Start()
        {
            cachedObject = FindObjectOfType<OpponentMotionReceiver>();
        }

        private void OnDestroy()
        {
                var motionReceiver = FindObjectOfType<OpponentMotionReceiver>();

                if (motionReceiver == null)
                {
                    Debug.Log("motion receiver not found");
                }

                if(cachedObject != null)
                {
                    //prints true, another proof that the gameObject is active
                    Debug.Log(cachedObject.gameObject.activeInHierarchy);
                }
        }
    }

public class OpponentMotionReceiver : MonoBehaviour
    {
        private void Start()
        {
            Debug.Log("Start OpponentMotionReceiver");
        }

        private void OnDisable()
        {
            //never enters
            Debug.Log("OnDisable OpponentMotionReceiver");
        }

        private void OnDestroy()
        {
            //never enters
            Debug.Log("OnDestroy OpponentMotionReceiver");
        }
    }

```

P.S. This is extremely simplified version of the code so that the rest brings no confusion. If you need more details, I'd be pleased to answer you!

# Answer
> 2 votes
Hopefully you are changing the scene right? Only at that time unity behaves like that.

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


# Question
Title: Threading/Streaming files while rendering the scene
I am writing a game engine and am trying to wrap my head around data streaming while rendering. What I mean by this is being able to load resources (however slow it may be) while rendering and not slowing it down visibly. My engine is not a state of the art engine by any means and renders Quake3 style maps. The files needed to load are not super large and can be easily loaded in a few seconds but I want to ability to load in as quick as possible and load connected maps while playing without slowdown. What I am looking for is a sort of functionality where I can start a function and have it either run on it's own thread or just run for a specific amount of time every frame. In other words, I give it maybe a maximum running time of 0.01 and it will return control after that amount of time, meaning I can keep my FPS completely solid. Does such a functionality exist?

I know you can use threading for something like this but I need clarification on the concept. When people use the expression "UI thread" or "I/O thread", what does this mean? Is it a thread that is always being used on a specific core so that it always has priority? Do they have a thread running for the entirety of the engine that just handles specific logic?

# Answer
> 3 votes
You should load the data from the disk, doing any conversion or processing of that data you need (ideally zero) on a background thread. Once the data is loaded, provide a signal to your main thread (via any one of many available thread sync primitives available to your language/platform) that the resource is loaded and allow the main thread to hand the resource over to the GPU.

The terms "UI thread" or "I/O thread" generally refer to the *task* the thread is designed to accomplish. The "UI thread" is often synonymous with the main thread, and is the one where the platform's UI is being run and often where the graphics API is being interacted with as well.

The term "I/O thread" generally means a thread whose sole purpose is to do heavy lifting from a disk (input and output, or I/O)... such as loading files from it.

Starting and stopping threads is more expensive than simply putting them to sleep when there is nothing to do, so you'll generally spin up the threads you'll want to use for background work -- such as loading your resources from the disk -- and leave them up for the duration of the application.

Generally you cannot interact with a graphics API from multiple threads without explicit synchronization between them (some exceptions apply, but usually not around the tasks that transfer data to the GPU), so it's best to confine access to the GPU to a single thread.

# Answer
> 0 votes
You could implement a lazy loading system. I am doing something like this in my engine.

Instead of keeping a reference for the original resource directly in the entity, you can have a reference to a proxy of that resource.

The proxy would have the necessary data for loading the resource (the path or name of the file, for example) and the loaded resource.

When the resource was requested, the proxy could internally check if it already have the loaded resource, and then return the resource.

If the resource is not yet loaded, the proxy can start the loading (in another thread), and while the loading is on route, everytime the resource was requested, the proxy returns a mock resource of that type that can be a singleton instance.

That detail is important: Do not return a null. Returning an empty mock is better because it prevents the need to spread "if (obj != null)" to keep the code safe. You can have one mock file for every resource type (a mute sound file, an empty 3d model, a 1x1 transparent texture etc.).

---
Tags: multithreading, streaming
---


title: Unity not opening

text:
# Question
Title: Unity not opening
When I start my Unity it opens up the menu where I can select a project, but when I pick a project nothing happens. The process is still running in my windows but nothing shows up. Here is my log file:

```
LICENSE SYSTEM [20151210 20:3:23] No start/stop license dates set

LICENSE SYSTEM [20151210 20:3:23] Next license update check is after 2015-12-08T13:39:36

Built from '5.3/release/package-manager-disable' branch; Version is '5.3.0f4 (2524e04062b4) revision 2434272'; Using compiler version '160040219'
OS: 'Windows 10  (10.0.0) 64bit' Language: 'da' Physical Memory: 8110 MB
BatchMode: 0, IsHumanControllingUs: 1, StartBugReporterOnCrash: 1, Is64bit: 1, IsPro: 0
Initialize mono
Mono path[0] = 'G:/Program Files/Unity/Editor/Data/Managed'
Mono path[1] = 'G:/Program Files/Unity/Editor/Data/Mono/lib/mono/2.0'
Mono path[2] = 'G:/Program Files/Unity/Editor/Data/UnityScript'
Mono config path = 'G:/Program Files/Unity/Editor/Data/Mono/etc'
Using monoOptions --debugger-agent=transport=dt_socket,embedding=1,defer=y,address=0.0.0.0:56888
IsTimeToCheckForNewEditor: Update time 1449766327 current 1449774207
C:/Users/Halkjaer/Desktop/Roguelite
Loading GUID <-> Path mappings...0.000177 seconds
Loading Asset Database...0.016957 seconds
Audio: FMOD Profiler initialized on port 54900
AssetDatabase consistency checks...0.019347 seconds
Initialize engine version: 5.3.0f4 (2524e04062b4)
GfxDevice: creating device client; threaded=1
Direct3D:
    Version:  Direct3D 11.0 [level 11.0]
    Renderer: AMD Radeon HD 7800 Series (ID=0x6819)
    Vendor:   ATI
    VRAM:     2030 MB
Begin MonoManager ReloadAssembly
Platform assembly: G:\Program Files\Unity\Editor\Data\Managed\UnityEngine.dll (this message is harmless)
Platform assembly: G:\Program Files\Unity\Editor\Data\Managed\UnityEditor.dll (this message is harmless)
Platform assembly: G:\Program Files\Unity\Editor\Data\Managed\Unity.Locator.dll (this message is harmless)
Refreshing native plugins compatible for Editor in 45.52 ms, found 0 plugins.
Platform assembly: G:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\I18N.dll (this message is harmless)
Platform assembly: G:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\I18N.West.dll (this message is harmless)
Platform assembly: G:\Program Files\Unity\Editor\Data\Managed\Unity.DataContract.dll (this message is harmless)
Platform assembly: G:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\System.Core.dll (this message is harmless)
Platform assembly: G:\Program Files\Unity\Editor\Data\Managed\Unity.IvyParser.dll (this message is harmless)
Platform assembly: G:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\System.dll (this message is harmless)
Platform assembly: G:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\System.Xml.dll (this message is harmless)
Platform assembly: G:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\System.Configuration.dll (this message is harmless)
Platform assembly: G:\Program Files\Unity\Editor\Data\PackageManager\Unity\PackageManager\5.3.0\Unity.PackageManager.dll (this message is harmless)
Initializing Unity.PackageManager (PackageManager) v5.3.0 for Unity v5.3.0f4
Setting StandaloneWindows v5.3.0 for Unity v5.3.0f4 to G:\Program Files\Unity\Editor\Data\PlaybackEngines\WindowsStandaloneSupport
Setting Advertisements v5.3.0 for Unity v5.3.0f4 to G:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\Advertisements
  UnityEngine.Advertisements.dll (Extension) GUID: 739bbd9f364b4268874f9fd86ab3beef
  Editor/UnityEditor.Advertisements.dll (Extension) GUID: 97decbdab0634cdd991f8d23ddf0dead
Setting EditorTestsRunner v5.3.0 for Unity v5.3.0f4 to G:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\EditorTestsRunner
  Editor/nunit.framework.dll (Extension) GUID: 7cbab2be89b54486bbd23a6fe637d30e
  Editor/UnityEditor.EditorTestsRunner.dll (Extension) GUID: 3c0ad459c1534645b5d603b7cc258f97
Setting GUISystem v5.3.0 for Unity v5.3.0f4 to G:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\GUISystem
  UnityEngine.UI.dll (Extension) GUID: f5f67c52d1564df4a8936ccd202a3bd8
  Editor/UnityEditor.UI.dll (Extension) GUID: 80a3616ca19596e4da0f10f14d241e9f
Setting UNetHLAPI v5.3.0 for Unity v5.3.0f4 to G:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\Networking
  UnityEngine.Networking.dll (Extension) GUID: 870353891bb340e2b2a9c8707e7419ba
  Editor/UnityEditor.Networking.dll (Extension) GUID: 5f32cd94baa94578a686d4b9d6b660f7
Setting TreeEditor v5.3.0 for Unity v5.3.0f4 to G:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\TreeEditor
  Editor/UnityEditor.TreeEditor.dll (Extension) GUID: adebbd281f1a4ef3a30be7f21937e02f
Setting UnityAnalytics v5.3.0 for Unity v5.3.0f4 to G:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\UnityAnalytics
  UnityEngine.Analytics.dll (Extension) GUID: 852E56802EB941638ACBB491814497B0
Setting UnityPurchasing v5.3.0 for Unity v5.3.0f4 to G:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\UnityPurchasing
  UnityEngine.Purchasing.dll (Extension) GUID: 8E0CD8ED44D4412CBE0642067ABC9E44
Registering custom dll's ...
Register platform support module: G:\Program Files\Unity\Editor\Data\PlaybackEngines\WindowsStandaloneSupport/UnityEditor.WindowsStandalone.Extensions.dll
Registered in 0.049048 seconds.
Non platform assembly: C:\Users\Halkjaer\Desktop\Roguelite\Library\ScriptAssemblies\Assembly-CSharp-firstpass.dll (this message is harmless)
Loading C:\Users\Halkjaer\Desktop\Roguelite\Library\ScriptAssemblies\Assembly-CSharp-firstpass.dll into Unity Child Domain
Non platform assembly: C:\Users\Halkjaer\Desktop\Roguelite\Library\ScriptAssemblies\Assembly-CSharp.dll (this message is harmless)
Loading C:\Users\Halkjaer\Desktop\Roguelite\Library\ScriptAssemblies\Assembly-CSharp.dll into Unity Child Domain
Non platform assembly: C:\Users\Halkjaer\Desktop\Roguelite\Library\ScriptAssemblies\Assembly-CSharp-Editor.dll (this message is harmless)
Loading C:\Users\Halkjaer\Desktop\Roguelite\Library\ScriptAssemblies\Assembly-CSharp-Editor.dll into Unity Child Domain
Platform assembly: G:\Program Files\Unity\Editor\Data\PackageManager\Unity\PackageManager\5.3.0\Unity.PackageManager.dll (this message is harmless)
Loading G:\Program Files\Unity\Editor\Data\PackageManager\Unity\PackageManager\5.3.0\Unity.PackageManager.dll into Unity Child Domain
Non platform assembly: G:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\Advertisements\Editor\UnityEditor.Advertisements.dll (this message is harmless)
Loading G:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\Advertisements\Editor\UnityEditor.Advertisements.dll into Unity Child Domain
Non platform assembly: G:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\EditorTestsRunner\Editor\nunit.framework.dll (this message is harmless)
Loading G:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\EditorTestsRunner\Editor\nunit.framework.dll into Unity Child Domain
Non platform assembly: G:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\EditorTestsRunner\Editor\UnityEditor.EditorTestsRunner.dll (this message is harmless)
Loading G:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\EditorTestsRunner\Editor\UnityEditor.EditorTestsRunner.dll into Unity Child Domain
Non platform assembly: G:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\GUISystem\UnityEngine.UI.dll (this message is harmless)
Loading G:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\GUISystem\UnityEngine.UI.dll into Unity Child Domain
Non platform assembly: G:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\GUISystem\Editor\UnityEditor.UI.dll (this message is harmless)
Loading G:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\GUISystem\Editor\UnityEditor.UI.dll into Unity Child Domain
Non platform assembly: G:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\Networking\UnityEngine.Networking.dll (this message is harmless)
Loading G:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\Networking\UnityEngine.Networking.dll into Unity Child Domain
Non platform assembly: G:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\Networking\Editor\UnityEditor.Networking.dll (this message is harmless)
Loading G:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\Networking\Editor\UnityEditor.Networking.dll into Unity Child Domain
Non platform assembly: G:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\TreeEditor\Editor\UnityEditor.TreeEditor.dll (this message is harmless)
Loading G:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\TreeEditor\Editor\UnityEditor.TreeEditor.dll into Unity Child Domain
Non platform assembly: C:\Users\Halkjaer\Desktop\Roguelite\Assets\AstarPathfindingProject\Plugins\DotNetZip\Pathfinding.Ionic.Zip.Reduced.dll (this message is harmless)
Loading C:\Users\Halkjaer\Desktop\Roguelite\Assets\AstarPathfindingProject\Plugins\DotNetZip\Pathfinding.Ionic.Zip.Reduced.dll into Unity Child Domain
Non platform assembly: C:\Users\Halkjaer\Desktop\Roguelite\Assets\AstarPathfindingProject\Plugins\JsonFx\Pathfinding.JsonFx.dll (this message is harmless)
Loading C:\Users\Halkjaer\Desktop\Roguelite\Assets\AstarPathfindingProject\Plugins\JsonFx\Pathfinding.JsonFx.dll into Unity Child Domain
Non platform assembly: C:\Users\Halkjaer\Desktop\Roguelite\Assets\JMO Assets\Editor\JMOAssets.dll (this message is harmless)
Loading C:\Users\Halkjaer\Desktop\Roguelite\Assets\JMO Assets\Editor\JMOAssets.dll into Unity Child Domain
Platform assembly: G:\Program Files\Unity\Editor\Data\Managed\UnityEditor.Graphs.dll (this message is harmless)
Loading G:\Program Files\Unity\Editor\Data\Managed\UnityEditor.Graphs.dll into Unity Child Domain
Platform assembly: G:\Program Files\Unity\Editor\Data\PlaybackEngines\WindowsStandaloneSupport\UnityEditor.WindowsStandalone.Extensions.dll (this message is harmless)
Loading G:\Program Files\Unity\Editor\Data\PlaybackEngines\WindowsStandaloneSupport\UnityEditor.WindowsStandalone.Extensions.dll into Unity Child Domain
Platform assembly: G:\Program Files\Unity\Editor\Data\Managed\nunit.core.interfaces.dll (this message is harmless)
Refreshing native plugins compatible for Editor in 0.22 ms, found 0 plugins.
Preloading 0 native plugins for Editor in 0.00 ms.
Platform assembly: G:\Program Files\Unity\Editor\Data\Managed\Mono.Cecil.dll (this message is harmless)
Platform assembly: G:\Program Files\Unity\Editor\Data\Managed\Unity.SerializationLogic.dll (this message is harmless)
Platform assembly: G:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\UnityScript.dll (this message is harmless)
Platform assembly: G:\Program Files\Unity\Editor\Data\Managed\ICSharpCode.NRefactory.dll (this message is harmless)
Platform assembly: G:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\System.Xml.Linq.dll (this message is harmless)
Platform assembly: G:\Program Files\Unity\Editor\Data\Managed\nunit.core.dll (this message is harmless)
Mono: successfully reloaded assembly
- Completed reload, in  0.782 seconds
Registering platform support modules:
Platform assembly: G:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\Boo.Lang.Compiler.dll (this message is harmless)
Platform assembly: G:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\Boo.Lang.dll (this message is harmless)
Platform assembly: G:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\Boo.Lang.Parser.dll (this message is harmless)
Platform assembly: G:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\UnityScript.Lang.dll (this message is harmless)
Platform assembly: G:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\Mono.Security.dll (this message is harmless)
Registered platform support modules in: 0.0837364s.
Native extension for WindowsStandalone target not found
Downloading http://update.unity3d.com/5.3/ivy.xml to C:\Users\Halkjaer\AppData\Local\Temp\unity\646921af-e00d-4550-b62c-10e4ee349599\ivy.xml
Validating Project structure ... 0.018937 seconds.
Refresh: detecting if any assets need to be imported or removed ... Refresh: elapses 0.018223 seconds (Nothing changed)
Task failed: Verifier Task

```

I was on 5.2 originally when this started happening. I have since upgraded to 5.3 in hopes that it would fix the problem, but it did not. Any help is appreciated, thanks.

# Answer
> 2 votes
Sounds more like your project isn't opening, Unity is starting fine. Create a new project and import the code, assets and settings. Something happened to your project file that corrupted it in some way.

---
Tags: unity
---


# Question
Title: How would I edit a sprite on an SNES rom?
I want to take the game Shaq Fu and change one of the sprites for my own. How would I go about doing it?

# Answer
> 6 votes
In general, you'd want to find a tool that can extract the sprite data and patch it back in to a ROM. You are more likely to find them for more popular games (such as Final Fantasy 6). Shaq Fu is, unfortunately for you, apparently not popular enough to warrant such things.

Your next step would be to look for a generic SNES sprite extractor or editing tool. The SNES used a specific tile graphics format for drawing sprite tiles, and many games would have simply stored their graphics directly in that required format in the ROM for simplicity. These generic tools can sometimes find and edit those. Search for "SNES sprite editor" or whatnot and you may find some examples.

If that doesn't work, because your game is one of the ones that opted for some unusual storage format or compression, you'll have to do things the hard way. The sprite data is still in the ROM somewhere, and will probably still be rendered normally once decoded. You can still dig through the game's assembly and find *where* the rendering is being set up (look for preparation of the appropriate OAM registers, et cetera) and hopefully work backwards from there.

---
Tags: sprites, modding
---


# Question
Title: Gamepad default trigger identification in Windows
I'm currently writing an interface driver for my Moga Power Pro controller on Windows. I'd like to release it for others to use, but first I have some questions on expected default mappings for the triggers.

Specifically, how do other gamepads map the triggers, as viewed from the Windows `joy.cpl` Game Controllers panel? And which axis are they normally mapped to? Some axes default to the center value, others can default to zero, and the different axes might be treated differently inside games. Triggers are naturally zero-to-full, but I don't want someone to download my interface driver and suddenly find the triggers are always active because Windows thinks the axis ought to be centered and reads it always tilted to one side.

I realize every controller is different, so this may be a bit subjective, but the closer I can set it to some form of standard the better. Or is this something I shouldn't even need to worry about, that games which expect a trigger input will handle on their own?

# Answer
> 0 votes
One of the problems with the DirectInput API was that it was so hardware agonistic as to be difficult for game designers to understand how to create control schemes. Previous attempts to mitigate the DirectInput 'control mapping' problem through things like *Action Mapper* didn't really pan out.

This is arguably the biggest benefit of the Xbox Common Controller initiative where PC game designers could rally around a single gamepad at least for their default control schemes. Ideally they were using XINPUT instead of DirectInput, but at least they had some idea of what the player might have in their hands.

The Xbox 360 Controller / Xbox One Controller on PC are exposed as HID devices for DirectInput to help support legacy applications as well as through the XINPUT API or on Windows 10 the new `Windows.Gaming.Input` API. For the triggers, the HID report makes an assumption that was made so that steering wheel games would work as expected: The left & right triggers are combined as follows for the Z axis:

> 0x0800 - right trigger + left trigger

DirectInput and XUSB Devices, XINPUT and Windows 8, and DirectX Tool Kit: Now with GamePads

---
Tags: windows, controllers, axis, gamepad
---


# Question
Title: Why is Unity UI Image color not being animated?
Animation is changing the color of an UI Image but the color only changes only in the inspector but not Game/Scene view.

In this video I demonstrate the problem clearly.

# Answer
> 0 votes
You need to change your `Material` on the `Image` to something that has the "Sprites-Default" shader so it can react to the changes in the color.

If you don't have the `Material` you need, here's a quick way to create one that would work for what you're trying to do: Simple Sprite Material Creation. Under "*Shader*" just select "*Sprites* \> *Default*".

---
Tags: unity, animation
---