title: Godot, hide objects

text:
# Question
Title: Godot, hide objects
Currently the way I do it, is setup an Area2d and a collision shape child for each individual node and then I attach a script to the area2d

```
extends Area2D

func _input_event(viewport, event, shape_idx):
    if event.type == InputEvent.MOUSE_BUTTON \
    and event.button_index == BUTTON_LEFT \
    and event.pressed:
        sorite.hide()

```

Is there a faster way? suppose I want to hide each object the user clicks on, and only then I want to allow him to press on `SpriteX` And I have a trillion object that can be clicked, what to do?

# Answer
> 1 votes
As Charanor stated correctly, you should not worry too much about optimising your code before you actually get into trouble. From my experience the slowest functions are never the ones you would expect :-)

Anyways, Godot offers a nice way to handle inputs using its InputMap. With the InputMap you can define actions and link them to different keys. In the long run it makes it way easier to change keys in the game.

You can find an Introduction to the InputMap in the Pong Tutorial.

For your example I would connect the Area2D-InputEvent Signal (of the Sprite) to your script (using the editor as described here). And then simply add the following code to the generated function.

```
func _on_Area2D_input_event( viewport, event, shape_idx ):
    if event.is_action_pressed("mouse_left"):
        sorite.hide()

```

Although I am not sure if it is faster it is way cleaner and as mentioned easier to change later as you just need to change the Key/Button in the inputmap.

---
Tags: godot
---


# Question
Title: Modern OpenGL, billboarding, alpha transparency
I'm having some transparency issues when rendering billboards in modern OpenGL.

I've created two billboard sprites, each one with alpha transparency, just for testing.

When I render two sprites without any transparency, it all works as expected:

Whenever I render two sprites with alpha transparency, part of one of the sprites is blocked by the other:

At first I though it had something to do with the render order, so I tried to change the order by simply render the second sprite before the first one, but then the issue is on the first sprite instead:

Blending is enabled by calling `glEnable(GL_BLEND);` at the start of the application.

I feel like I've tried every `glBlendFunc()` combination (`glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)` etc) that exist in OpenGL but nothing helps.

I've also tried disable the depthmask by calling `glDepthMask(GL_FALSE);`but that doesn't help either.

I am using VBO's (one per sprite) when rendering.

In the vertex- and fragment shader I'm not doing anything more than setting the vertex position, the texture coordinate and the pixel color.

# Answer
> 6 votes
With the help of Bálint, I successfully got the issue fixed.

Bálint suggested using the `discard` keyword in GLSL to discard pixels that are not visible (i.e, transparent).

So inside my fragment shader, I'm checking the pixel's alpha value and if it's below a certain threshold, the pixel is discarded and therefore not rendered.

```
vec4 PixelColor = texture2D(Colormap, FragmentUV);

if(PixelColor.a < 0.1)
    discard;

```

Result:

# Answer
> 2 votes
Yes it's the render order, but not in the way you think. The depth buffer only contains 1 dimensional data, it can't represent transparency.

Even if part of the texture is transparent, it will still write in the depth buffer. Because of this when the other plane gets rendered, it'll get obstructed.

It's very hard to solve it in this case, you probably have to slice the plane up into 4 squares and render them separately at which point you could just make the models have an L shape.

---
Tags: opengl, transparency, alpha, billboarding
---


title: Sphere intersection Stuck

text:
# Question
Title: Sphere intersection Stuck
I have two spheres that are bounded by spheres for collision detection. I do not want them to intersect. My intersection works. But it gets stuck. Once the function returns true, I cannot get it out. I tried

```
collideBool = ObjectOne.Intersect(ObjectTwo);

if(collide == true)
{
    leftright = leftright;
    updown = updown;
}
else
{
if(GetAsyncKeyState(VK_RIGHT))
leftright -= dt;
if(GetAsyncKeyState(VK_LEFT))
leftright += dt;
if(GetAsyncKeyState(VK_DOWN))
updown += dt;
if(GetAsyncKeyState(VK_UP))
updown -= dt;
}

collide = false;

```

My sphere gets stuck. What is a way around this?

# Answer
Check for collision against the new position and undo if it would cause a collision.

```
float oldleftright = leftright, oldupdown = updown;

if(GetAsyncKeyState(VK_RIGHT))
    leftright -= dt;
if(GetAsyncKeyState(VK_LEFT))
    leftright += dt;
if(GetAsyncKeyState(VK_DOWN))
    updown += dt;
if(GetAsyncKeyState(VK_UP))
    updown -= dt;

bool collide = ObjectOne.Intersect(ObjectTwo);
if (collide)
{
    leftright = oldleftright;
    updown = oldupdown;
}
collide = false;

```
> 1 votes

---
Tags: collision-detection
---


# Question
Title: How do I manually define save paths in GMS?
I want to know if it is possible to set the path for my game's save data in GameMaker: Studio outside of the two default options I am given in the program. The options I get are:

```
%LocalAppData%\<game_name>

```

and

```
%AppData%\<game_name>

```

I can't seem to find a text box or text feild that let's me set something different. I feel like there should be one for advanced users so that path variables and wildcards can be used in the save data path.

I also tried opening the game's config `.gmx` and setting the path there. Unfortunately it did not work as the only values that *do* work are `0` & `1` which represent the default path options respectively. Is this possible? Am I missing something?

# Answer
## Short answer:

*You can't do it.*

## Longer answer:

Game Maker Studio does not support a user-specified path for it's game-saving functionality. **However, what you are trying to do is possible with the file system API in GML.** Without using GML, you are limited to using the default paths for game saves.

Personally, I would use plain text files to save your game data in.

See also:
> 1 votes

---
Tags: game-maker, windows, savegame, settings
---


# Question
Title: Are wheeled vehicles usually controlled by force applied to wheels or is movement simulated by a force applied to the vehicle?
I'm building a tank in my game and I was hoping to have moving wheels with rotation and shocks. I can get the wheels to bounce and rotate but they do not actually propel the car forward.

Should I not be trying to apply a force to the wheels and instead just show the wheel rotating as I apply a force to the body of the tank?

EDIT: ALRIGHT! I did it! I rigged the tank! But the question still remains, is vehicle movement with spinning wheels usually just an animation with a force applied to the car or is it not ridiculous to apply a force to the wheels?

# Answer
> 1 votes
It depends on the design of the game. And the time that you have to implement your simulation.

If you need a realistic simulation, you'll want to model the wheels, the engine, the weight, the feedback forces, etc. along with their interaction. This is more complex. And requires much more time to tweak all the parts.

If you're looking for a more simple looking simulation, you can simply use the rigid body for the whole vehicle and compute the wheels movement out of it. This is more simple.

---
Tags: c++, physics, vehicle
---


# Question
Title: View individual UI Rect boxes when multiple UI elements are selected?
I have 2D UI layout with multiple text boxes over the canvas, I need to easily be able to see where the Rect boxes for each are positioned, so that I can see where the safe areas are for placing buttons etc.

Selecting each individual item shows its own individual Rect box, but selecting multiple items just shows one big box around all of them.

**Is there a way of selecting multiple items and see each individual Rect box?** It's extremely time consuming having to go and check each one individually.

# Answer
There's no setting for this in Unity, however, a custom script can do something like this. Here's a complete script I wrote, you'll just need to add it to any object in the scene. It will run in edit mode and draw red lines around each element and its descendants (assuming they have a `RectTransform`).

Everything selected:

A child element selected:

```
using UnityEditor;
using UnityEngine;

[ExecuteInEditMode]
class UISelector : MonoBehaviour {
    void OnDrawGizmos() {
        if (Selection.activeTransform != null) {
            if (Selection.activeTransform.GetComponent<RectTransform>() != null) {
                DrawChildRects(Selection.activeTransform.GetComponent<RectTransform>());
            }
        }
    }

    void DrawChildRects(RectTransform transform) {
        DrawRect(transform);
        foreach (RectTransform rect in transform) {
            DrawChildRects(rect);
            DrawRect(rect);
        }
    }

    void DrawRect(RectTransform rect) {
        Vector3[] points = new Vector3[] {
              new Vector3(rect.rect.min.x + rect.position.x,
                rect.rect.min.y + rect.position.y),
              new Vector3(rect.rect.min.x + rect.position.x,
                rect.rect.min.y + rect.position.y + rect.rect.height),
              new Vector3(rect.rect.min.x + rect.position.x,
                rect.rect.min.y + rect.position.y + rect.rect.height),
              new Vector3(rect.rect.max.x + rect.position.x,
                rect.rect.max.y + rect.position.y),
              new Vector3(rect.rect.max.x + rect.position.x,
                rect.rect.max.y + rect.position.y),
              new Vector3(rect.rect.max.x + rect.position.x,
                rect.rect.max.y + rect.position.y - rect.rect.height),
              new Vector3(rect.rect.max.x + rect.position.x,
                rect.rect.max.y + rect.position.y - rect.rect.height),
              new Vector3(rect.rect.min.x + rect.position.x,
                rect.rect.min.y + rect.position.y),
            };
        Handles.color = Color.red;
        Handles.DrawLines(points);
    }
}

```
> 3 votes

---
Tags: unity, gui, text
---


# Question
Title: Quickly Converting RenderTexture to Texture2D in Unity3D
I have a screenshot preview at the end of the game's level. When I am loading the screenshot, it makes the game freeze for a moment. What may I do so there would be no freeze when I am loading that screenshot? Here is myc ode:

```
private IEnumerator ShowScreeshotPreview()
        {
    screenshotTexture = new Texture2D(Screen.height, Screen.height, TextureFormat.RGB24, false);
            for (int i = 0; i < 9; i++)
            {
                yield return null;
            }
            RenderTexture.active = Singletons.Get<SpecialEffectsHelper>().MainCharacterScript.GetComponent<GeneratorScript>().screenshotTexture;
            screenshotTexture.ReadPixels(new Rect(0, 0, Screen.height, Screen.height), 0, 0);
    screenshotTexture.Apply();
            RenderTexture.active = null; //Added to avoid errors

            screenshotPrview.mainTexture = screenshotTexture;
    ScreenshotPreviewAnimator.SetBool("visible", true);
            screenshotLoaded = true;

            yield return null;
        }

```

# Answer
> 2 votes
You can't do anything to prevent the freeze. The `Texture2D.Apply()` method is expensive. The larger the texture dimensions, the longer the freeze.

You can't manipulate Unity objects, such as `GameObject` or `Texture2D`, in a separate thread. In some cases, you can prepare the data on another thread, to be used by or with the Unity objects in the UI thread. However, in your case, it won't help; you have to call `Texture2D.Apply()` in the UI thread.

# Answer
> 0 votes
The solution is not to prevent the freeze, but to force it to happen at some earlier time when it will not be as noticeable to the user.

I suggest having a loading screen during which you call that up for the first time, to display for a single frame, invisibly. This will force the load at that point. The load screen may have a spinner or whatever that would be expected to periodically pause, so the user will tolerate any pauses at this point. Then, by the time you call it in-game, everything will look normal as there will now be no freeze.

---
Tags: c#, unity, loading, screenshot
---


# Question
Title: How do people implement pathfinding movement?
I understand how A\* works, but I don't understand how movement is implemented, e.g. creating a list of directions and then going through that list until every direction is empty. How does that work?

EDIT: Node based.

# Answer
Create a list of directions and go through them. If you get knocked off course, just adjust slightly. Readjust completely if there's a bigger unexpected obstacle.
> 0 votes

# Answer
Assuming for the moment that you want simple linear motion with 0-time turns and constant speed, the basic method is to generate the points along the path that you are going to move through and follow the lines between the points using linear interpolation (AKA Lerping).

At each movement phase you find the vector to the next point in your path and move towards it by whatever fraction of your movement speed you can. If you reach it then you discard that point, pull the next one from the queue and repeat until you have moved the full allotment. Once you reach the final position - with or without movement left over - you can signal that you are done moving.

This should handle minor changes in position from outside forces - being knocked back by an attack, pushed around by environmental factors, etc - as long as the movement doesn't put you in a position that will require a whole new path.

The actual movement calculations are reasonably easy. Get the difference between your current point and the target as a vector, scale it to be no longer than your movement speed, change position and check to see if you have movement left over.

I whipped up some code:

```
public class Mobile
{
    public Point2D Position { get; set; }

    private Point2D _lastMoveDir = Point2D.Up;
    public Point2D LastMoveDir { get { return _lastMoveDir; } }

    public double Speed { get; set; }
    public readonly Queue<Point2D> MoveQueue = new Queue<Point2D>();

    private Point2D? currMove = null;

    // Process move queue, updates Position
    public bool DoMove()
    {
        // check current move target
        if (currMove == null)
        {
            // if no more moves then exit, else get next move
            if (MoveQueue.Count == 0)
                return false;
            currMove = MoveQueue.Dequeue();
        }

        // total distance to move is the same as speed
        double distance = Speed;

        // Use as much movement as possible
        while (currMove != null && distance > 0)
        {
            // Find next position along the path
            Position = CalculateMove(Position, currMove.Value, distance, out distance, out _lastMoveDir);

            // Get next move if any movement left over
            if (distance > 0)
            {
                if (MoveQueue.Count == 0)
                    currMove = null;
                else
                    currMove = MoveQueue.Dequeue();
            }
            // test if at target (with error margin)
            else if (Math.Abs(currMove.Value.Subtract(Position).LengthSquared) < 1E-10d)
                currMove = null;
        }
        // return true if still moving
        return currMove != null || MoveQueue.Count > 0;
    }

    // Move in the direction of the target point as far as we can
    private static Point2D CalculateMove(Point2D ptFrom, Point2D ptTo, double distance, out double remaining, out Point2D moveDir)
    {
        remaining = 0;
        // get direction of movement as unit vector
        moveDir = ptTo.Subtract(ptFrom).Unit();
        // get available movement length
        var dirlen = moveDir.Length;
        // if less available length, update vars for this move
        if (distance > dirlen)
        {
            remaining = distance - dirlen;
            distance = dirlen;
        }
        // find location to move to relative to current position
        var offset = moveDir.Multiply(distance);
        // return it
        return ptFrom.Add(offset);
    }
}

```

Apart from the inconsistent naming conventions (I know, I'm terrible) and some sloppy techniques, this does produce the kind of movement I describe above. It's supported by a fairly simple `Point2D` struct which should be easy enough for you to replace with your own preferred variant.

The code above also tracks the last move direction so that you can rotate your game object to face the direction of movement if desired.

---

If you want a more interesting motion than linear interpolation there are a whole range of curve generators out there that you can use. My preference for this kind of thing is the Catmull-Rom algorithm. It - and several others - generates path segments that vary in length depending on the tightness of the curve. Tighter curves have shorter segments and you can use that to control speed to simulate slowing down for turns and accelerating down the straighter sections.

The downside in this instance is that it requires a fair amount of calculation to get right, so pre-calculation is a very good idea. Unfortunately that means it won't handle nudges anywhere near as well as the simple linear interpolation code.
> 1 votes

---
Tags: algorithm, path-finding
---


title: How does mouse input work in 3d games?

text:
# Question
Title: How does mouse input work in 3d games?
How does a game process cursor movements? I know it calculates offset from the middle of the screen, but how? What constraints is that cursor having? Is it locked to the middle of the screen/a certain area/teleported to the middle of the screen?

Those are my questions.I didn't ask this question for game development(but i didnt find a better subsection for it), as I want to emulate this 'different' mouse input (vs desktop usage) to fix the bug that many remote computer software have(if possible, not sure it is) on linux, by emulating the mouse movement restrictions in a game (agiain, not sure if it's possible).

# Answer
> 1 votes
This is probably better suited in stack overflow (i found a few duplicates) but,
There are a few ways this is done:

On linux, it looks like you might get similar behavior to #1 using XGrapPointer: https://www.x.org/releases/current/doc/man/man3/XGrabPointer.3.xhtml

---
Tags: 3d, mouse
---


title: Unity remove logo in splash screen

text:
# Question
Title: Unity remove logo in splash screen
Heavily related to this question, as of now, Unity's TOS has changed dramatically. And searching in the TOS, it looks like I'm allowed to remove the Unity logo in my exported game. Looking at Section 4.1, it still retains:

> You will not remove, alter or obscure any copyright, trademark, service mark or other proprietary rights notices incorporated in or accompanying the Services.

However looking at how "Services" is defined in the first paragraph of the TOS:

> Unity Technologies ApS (“Unity”, “our” or “we”) provides game-development and related software (the “Software”), development-related services (like Unity Analytics (“Developer Services”)), and various Unity communities (like Unity Answers and and the Made with Unity Platform (“Communities”)), provided through or in connection with our website, accessible at unity3d.com or unity.com (collectively, the “Site”). Except to the extent you and Unity have executed a separate agreement, these terms and conditions exclusively govern your access to and use of the Software, Developer Services, Communities and Site (collectively, the “Services”)

It does not seem to include the exported game itself. And even if Section 4.1 says "accompanying the services", I assume it still wouldn't include the game as the game does not need to accompany them. Otherwise it would be illegal to remove the logo from the splash screen from a game made in Unity Pro since the TOS applies to all tiers of Unity. Furthermore, I haven't found anywhere that says you can't modify or hack into the produced executables (I even looked in here which contains another part of the TOS). Does this mean I can remove the logo from the splash screen no matter what Unity tier (personal, plus or pro) I'm using?

(My aim is to actually move it to a dedicated credits section accessible from the title screen of the game rather than having it appear in the splash screen. Players of the game will still know that it's made in Unity.)

# Answer
> 3 votes
1. The exported game still includes the Unity engine Software.
2. Unity are the ones that should be contacted with request for clarifications and executing a separate agreement that would let you move the logo.
3. Consult a lawyer.

# Answer
> 6 votes
The option to remove the Unity logo from the splash screen is one of the perks of the paid tiers (Plus and Pro).

So the simple answer is: **pay for Unity**, and you can use the built-in features to turn off the logo.

---
Tags: unity, legal, copyright, publishing, trademark
---


# Question
Title: Unity Engine 2D rigidbody inaccurate jumping whilst on a platform that moves downwards
I'm currently hard at work on a little platformer in the Unity3D engine, utilizing its 2D capabilities.

Now I have been having a problem where eventhough an object is clearly grounded it somehow doesn't register as such on every frame and thus the jump function, which only runs when the object is grounded, won't work. This so far only seems to happen whilst the player is on a platform that is currently moving downwards.

Now I'm not the best at 2D physics in Unity, so as such I decided to see what everyone here thinks might be the problem.

For illustration purposes here is what it looks like in the editor:

The white block is the player character, the blue block is the platform (currently moving down) and the red line is a raycast that checks wether or not the player character is grounded.

I hope you guys can figure out what's wrong. All I have so far is that it seems 50/50 wether or not the player is grounded during a frame on the platform, whilst said platform is moving down.

Hereby also my code for the player:

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

public class CharacterMovement : MonoBehaviour {

private bool left = false;
private bool right = false;

float velX = 0;
float velY = 0;

[SerializeField]
private float gravity;

[SerializeField]
private float speed;
[SerializeField]
private float maxSpeed;

[SerializeField]
private float jumpForce;
[SerializeField]
private float jumpSpeed;

bool isGrounded = false;
float groundedTime = 0;
float distanceToGround = 0;
float distanceSide = 0;

bool plug = false;
int plugCounter = 0;

void Start () {
    distanceToGround = this.GetComponent<Collider2D>().bounds.extents.y;
    distanceSide = this.GetComponent<Collider2D>().bounds.extents.x;
}

void Update () {

    Grounded();
    WalkingInput();
    Walking();
    Jumping();

    Debug.Log(isGrounded);

    this.GetComponent<Rigidbody2D>().velocity = new Vector2(velX, this.GetComponent<Rigidbody2D>().velocity.y);

    //Debug.Log(this.GetComponent<Rigidbody2D>().velocity.x + " " + this.GetComponent<Rigidbody2D>().velocity.y);

}

void Grounded()
{
    LayerMask mask = (1 << 8);
    mask = ~mask;
    if (Physics2D.Raycast(new Vector3(this.transform.position.x - distanceSide, this.transform.position.y - distanceToGround - 0.04f, this.transform.position.z),
                          Vector3.right,
                          distanceSide * 2,
                          mask))
    {
        isGrounded = true;
        groundedTime += Time.deltaTime;
    }
    else
    {
        isGrounded = false;
        groundedTime = 0;
    }

    //debugging ray
    Debug.DrawLine(new Vector3(this.transform.position.x - distanceSide, this.transform.position.y - distanceToGround - 0.04f, this.transform.position.z),
                   new Vector3(this.transform.position.x - distanceSide, this.transform.position.y - distanceToGround - 0.04f, this.transform.position.z) + new Vector3(distanceSide * 2, 0, 0),
                   Color.red);

}

void WalkingInput()
{
    if (Input.GetButtonDown("Left"))
    {
        left = true;
    }
    if (Input.GetButtonUp("Left"))
    {
        left = false;
    }

    if (Input.GetButtonDown("Right"))
    {
        right = true;
    }
    if (Input.GetButtonUp("Right"))
    {
        right = false;
    }
}

void Walking()
{

    if (left == true && velX >= -maxSpeed)
    {
        if(velX > 0)
        {
            velX = 0;
        }

        velX -= speed * Time.deltaTime;

        if (isGrounded)
        {
            if (velX < -maxSpeed)
            {
                velX = -maxSpeed;
            }
        } else
        {
            if (velX < -jumpSpeed)
            {
                velX = -jumpSpeed;
            }
        }
    }
    if (right == true && velX <= maxSpeed)
    {
        if (velX < 0)
        {
            velX = 0;
        }

        velX += speed * Time.deltaTime;

        if (isGrounded)
        {
            if (velX > maxSpeed)
            {
                velX = maxSpeed;
            }
        }
        else
        {
            if (velX > jumpSpeed)
            {
                velX = jumpSpeed;
            }
        }
    }

    if(left == false && right == false || left == true && right == true)
    {
        velX = 0;
    }

}

void Jumping()
{
    if (Input.GetButtonDown("Jump") && isGrounded)
    {
        Debug.Log("ActuallyJumped");
        this.GetComponent<Rigidbody2D>().AddForce(new Vector2(0, jumpForce));
    }

}

}

```

and the code for the platform:

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

public class MovingPlatform : MonoBehaviour {

[SerializeField]
Transform pointA;

[SerializeField]
Transform pointB;

[SerializeField]
float platformSpeed;

private float wayThere = 0;

bool going = true; //true = going to b, false = going to a

void FixedUpdate()
{
    if (going == true)
    {
        Vector2 offset = DetermineOffset(pointA.transform.position, pointB.transform.position);
        this.GetComponent<Rigidbody2D>().velocity = new Vector2(offset.x * platformSpeed * Time.deltaTime, offset.y * platformSpeed * Time.fixedDeltaTime);
        if (Vector2.Distance(this.transform.position, pointB.transform.position) < 0.2f)
        {
            going = false;
        }

    }
    else
    {
        Vector2 offset = DetermineOffset(pointB.transform.position, pointA.transform.position);
        this.GetComponent<Rigidbody2D>().velocity = new Vector2(offset.x * platformSpeed * Time.deltaTime, offset.y * platformSpeed * Time.fixedDeltaTime);
        if (Vector2.Distance(this.transform.position, pointA.transform.position) < 0.2f)
        {
            going = true;
        }
    }
}

private Vector2 DetermineOffset(Vector2 PointA, Vector2 PointB)
{

    int x = 0;
    int y = 0;

    if(PointB.x > PointA.x)
    {
        x = 1;
    }
    else if (PointB.x < PointA.x)
    {
        x = -1;
    }
    else
    {
        x = 0;
    }

    if(PointB.y > PointA.y)
    {
        y = 1;
    }
    else if (PointB.y < PointA.y)
    {
        y = -1;
    }
    else
    {
        y = 0;
    }

    return (new Vector2(x, y));

}

}

```

Also the editor setups for both the character and the platform in that order:

All in all I hope one of you good people can help me out on this one and thanks already!

EDIT: Changed the code for the platform to use velocity instead of rigidbody.moveposition. This works better. The bug is now non-existant on low speeds, it is still visible at high speeds. I think it might have to do with how Unity calculates rigidbody gravity because it becomes 0 when a rigidbody is grounded which means that currently the rigidbody is grounded, then it falls, then is grounded, then it falls which would explain the 50/50 ratio as well. I do however find it strange that this would work fine at a lower speed though.

If someone somehow can still manage to find out how to do this at faster speeds I'd be more than happy!

EDIT2: Answered my own question in the end. Check the answers to see how I fixed it.

# Answer
Alright! So I finally figured it out! DmGregory was right and it was a problem with my raycast. However because I couldn't for the life of me figure out how a boxcast is supposed to be done the right way and it didn't quite seem like the type of thing I need, and it's way more expensive on performance than a raycast or a linecast, I decided to switch to the following piece of code in my `Grounding();` function

```
LayerMask mask = (1 << 8);
    mask = ~mask;
    if (Physics2D.Linecast(new Vector2(this.transform.position.x - distanceSide, this.transform.position.y - distanceToGround),
                           new Vector2(this.transform.position.x + distanceSide, this.transform.position.y - distanceToGround - 0.1f),
                           mask))
    {
        isGrounded = true;
        groundedTime += Time.deltaTime;
    }
    else
    {
        isGrounded = false;
        groundedTime = 0;
    }

    //debugging ray
    Debug.DrawLine(new Vector3(this.transform.position.x -distanceSide, this.transform.position.y - distanceToGround, this.transform.position.z),
                   new Vector3(this.transform.position.x + distanceSide, this.transform.position.y - distanceToGround - 0.1f, this.transform.position.z),
                   Color.red);

```

Basically all it is is the raycast is now diagonal. I am gonna add another one that goes at a diagonal the other way (just make sure we covered most corners). Overall thanks for the answers everyone and I hope this'll help someone in the future.
> 0 votes

# Answer
You can try calling the `Grounded()` and `Jumping()` methods from `FixedUpdate()`, because it uses the Physics Engine, with a fixed delta time. Perhaps it happens during the difference between delta time and fixed delta time.

Read more on Unitys execution order.
> -1 votes

---
Tags: unity, c#, physics, rigidbody, moving-platforms
---


title: Precision issue bouding sphere

text:
# Question
Title: Precision issue bouding sphere
I tried to make two spheres with bounding sphere to detect collision so they stop when they collide. But it seems that im having a precision issue. They stey stuck together because of small decimal keeping it stuck. Is there a way around this? Since they are in a 3d space, adding or subtracting a little off seems impossible and expensive. How can I solve these precision issues?

```
 oldleftright = leftright, oldupdown = updown;

if(GetAsyncKeyState(VK_RIGHT))
    leftright += 0.0001;
if(GetAsyncKeyState(VK_LEFT))
    leftright -= 0.0001;
if(GetAsyncKeyState(VK_DOWN))
    updown -= 0.0001;
if(GetAsyncKeyState(VK_UP))
    updown += 0.0001;

collide = test.Intersect(test2);
if (collide)
{
    leftright = oldleftright;
    updown = oldupdown;
}
collide = false;

```

# Answer
If I understand the problem correctly here is how I usually solve it: check if the two sphere are approaching themselves or not.

If yes then they are actually colliding and the result of delta\_Speed dot delta\_Position will be \> 0 (the angle between the two vector wil be \< 90°)

In code you will have:

```
vector3 deltaPos = pos1 - pos2;
vector3 deltaSpeed = speed1 - speed2;
bool collide = deltaPos * deltaSpeed > 0.0f; //deltaPos.x*deltaSpeed.x + deltaPos.y*deltaSpeed.y + deltaPos.z*deltaSpeed.z > 0.0f

```
> 0 votes

---
Tags: c++, directx11, precision
---


# Question
Title: Logic and view separation but the view is generated by the logic
We are working on a simple turn-based card game. We would like to implement it using a design which let us create additional "monsters" and "events" later on (so the code should be flexible).

Also, we would like to separate the actual logic (who does what) from the presentation (view/rendering) so we could write a different renderer whenever we want (Unity, WPF, etc.)

This game is already playable on paper (we have a table, figures, cards, etc.) but we would like to speed up some things (for example the battle). And this would be a learning project. This is the reason why we would like to implement it in a nice way (instead of just "hacking" things together).

The main concept of the MVC pattern is to have the model, controller and view separated. In a fully-separated design the view can display the model by asking the controller to give some data. The view can also ask the controller to modify the model based on its input. However the controller has no knowledge about the view.

Our problem is that we would like to "generate the view" based on the "controller" (action). This might sound a little wierd but let me give you some examples:

In this game we have some special "event cards" and these are doing different things when the player meets with them. For example the "Wise" gives the player x gold based on a roll OR it gives the player his treasure if he has any. Since we are not storing the actual map in this program (we are playing on a physical table) the GM (Game Master) must choose the operation based on the current state of the game. This means that when the GM selects the "Wise" there should be two buttons, like "Give treasure" and "Give gold". This is when the controller/model/action defines the view.

Something like this:

1. GM selects the player
2. The player makes some action in real-life
3. When the player enters a zone where an "event card" can be found, the GM selects the right "event card" on his tablet (for example)
4. Then the selected event card defines the possible actions which defines the view (since the GM has to press some buttons)

It is not important that if we are generating the view (using a layout and filling it with text and buttons) or if we are creating the views by hand. The main problem is that we don't know how to "glue" them together. When the GM selects an event card, which view should we generate? Which button should execute which action? Sometimes a specific action requires another view to be shown. This seems like a hard coupling between the logic and the view.

Here is a mini code-snippet (note this is not the actual code, it's just an example).

```
interface IEventCard
{
    void Selected();
}

class Wise : IEventCard
{
    void Selected()
    {
        // add "Give treasure" action
        // add "Give gold" action
    }
}

class GameManager
{
    IList<IEventCard> cards;

    void Initialize()
    {
        // create cards
        cards = new List<IEventCard>();
        cards.Add(new Wise());
        // ...
    }

    // called from the UI
    void Select(int id)
    {
        IEventCard card = cards[id];
        card.Selected();

        // it should open a view
        // the view should be populated with:
        // - the name and description of the event card
        // - buttons that execute the corresponding action
        // some of these actions should open another views
        // for example the "give treasure" action should open the "inventory screen" which lets the GM select the item
        // or the "give gold" action should open a "roll the dice" window first to determine how much gold the player should get
        // etc.
    }
}

```

Sorry if it's hard to understand my description, I've tried to explain things as short as possible. We would appreciate if you could give us some tips, preferable some code snippets.

# Answer
I think the problem here is that your model is too simple. You are correct in that the controller should get all the required details for the view however your example only shows what the card should do once it is selected.

I think that your `IEventCard` should implement a method for the button amount, the button text and the card text which should help generate the view.

To make it more friendly in the future you could also add a heuristic to the card which makes it trigger when it is most appropriate. That way your controller knows nothing about the actual cards and just selects the appropriate action. If I implemented this I would have a method like `EventLikelyHood` which I would call when an event card is needed I would then pass all the possible things that affect what card should be picked as parameters or even better as a structure that contains all the variables (so that you don't have to amend existing cards everyone you need to add something). So say your players enter an event zone the controller would cycle though all cards and get a number for the likelihood that the event would happen and store them or keep a record of which card currently has the highest chance. When all cards have been tested you execute the highest card.

Now you have all the details needed for the UI the controller only knows about the cards and not the data and your view only has relative information.
> 1 votes

---
Tags: architecture
---


title: Single-player in a co-op focused game

text:
# Question
Title: Single-player in a co-op focused game
I'm currently planing a game idea, a coop crew based space shooter, where the focus is set heavily on the coop part. Depending what role you have, complexity varies: Gunners and Pilots are pretty easy, while engineers and doctors are way more complex. Crews may contain two to maybe 8 people.

This is only an example for a coop game, while there are many others out there.

But my thinking was, what about the people that want to play alone? Or in less big crews on bigger ships.

As I said, there are many other games out there that try to solve that problem. **Lovers in a difficult space time** has an A.I. that is basically a commendable token, **Guns of Icarus** has simple A.I. dudes, while **Endless Dungeon** let's you play all of your characters RTS style.

In my case, writing an A.I. that does everything is problematic. Gunner and Pilot would be possible, but Engineer is to complex. And making the A.I. simply perfect could and would break the gameplay. Making them less reliable would force me to implement some sort of crew management just for Single-player. Doable but not the focus.

My question is: What other options for a coop game are there to make it playable and enjoyable for Single-player?

I'm looking for answers not just fitting for my game, but coop games in general.

# Answer
Have a linear single player campaign which is heavily scripted.

During the course of the campaign, put the player into each of the multiplayer coop-roles once. Do that by putting them through a series of scenario with each scenario being completely focused on fulfilling that one role.

Due to the linearity and scripting, any AI actors which appear don't need much autonomous intelligence. They just need to perform actions when the script tells them to. A linear campaign also allows you to cheat a lot. For Example: You can have a battle where the player is assisted by an AI ship. During that battle, the AI ship is actually indestructible. When the battle is over, simply claim that the AI ship got damaged badly and needs to be repaired.
> 3 votes

# Answer
My answer would be **not to** do a single player mode.

> coop crew based space shooter, where the focus is set heavily on the coop part

As you said you are making your game with the idea that it is a **coop game**, then my opinion would be to really focus on this aspect of the game. There are plenty of awesome solo space shooters and providing an average experience for solo players isn't your goal. That being said, I think it's very important that you make the game playable in local with 3 other friends or more if you find a way.

You could really bring something new to the table by focusing on the multiplayer. I'll take for instance Rocket League that is a really good multiplayer game and has encountered a good success : the game provides a good AI but nobody plays the game with only bots. The game really worked on the multiplayer aspect by adding a lot of modes, personnalization etc.

If you really want the game to be played alone you could provide a basic AI to fill up the slots if there aren't enough players but my advice would be not to spend too much time on this. Some kind of solo training or challenges would be another solution, like surviving for the longest time possible or defeating pre-defined waves of enemis as seen in Geometry Wars.
> 1 votes

---
Tags: game-design, multiplayer, single-player
---


# Question
Title: Unity: Smoothing between two floats which are continuously changing
I'm looking for some help with smoothing between an original float and a target float, where the original float is consistently changing (potentially interfering with interpolation techniques and or Mathf.SmoothDamp)

I tried Mathf.SmoothDamp with the below:

(float rocketBoostPower is a global variable)

```
float yVelocity = 0.0F;
float tempForce = rocketBoostPower + Input.GetAxis("Mouse Y") * shiftSpeed / 5f;
rocketBoostPower = Mathf.SmoothDamp(rocketBoostPower , tempForce, ref yVelocity, 0.5f);

```

This doesn't change the force at all however, it just stays locked in place.

I'm currently using the below to change my power, however I want to smoothly change the power instead of just incrementing sharply on each Update frame:

```
rocketBoostPower += Input.GetAxis("Mouse Y") * shiftSpeed / 5f;

```

Please can someone help? I need the assumption that every update will receive a new rocketBoostPower value, whilst still smoothing its previous value.

# Answer
> 2 votes
Use a lerp (linear interpolation) instead. It's used as so:

```
float f = Mathf.Lerp(a,b,t);

```

f will be set to a "blend" of a,b based on t. When t = 0, f = a. When t = 1, f = b. You can take advantage of this to create some nifty smooth transition functions.

The easiest is just:

```
rocketBoostPower = Mathf.Lerp(rocketBoostPower , tempForce,t);

```

Which brings rocketBoostPower closer to tempForce by t "percentage" every time it's called.

**Note:** because you're blending from and setting to the same var, rocketBoostPower will **NEVER** equal tempForce unless t = 1.

---

https://en.wikipedia.org/wiki/Linear\_interpolation here's a wiki article for further reading. Interpolation is a HUGELY useful concept in game dev, and I highly recommend doing further research

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


title: box2d prismatic joint friction

text:
# Question
Title: box2d prismatic joint friction
I know it is possible to add friction to rev joints by enabling motor and adding `maxMotorTorque`. I want the same for prism joint but only `maxMotorSpeed` option is available which didn't quite work for me. Is there another way?

# Answer
> 1 votes
The function you are looking for is `SetMaxMotorForce`. This function is analogous to `SetMaxMotorTorque` for `b2RevoluteJoint`s.

---
Tags: box2d, joints
---


title: Box2D Get Bounding Box of a Body

text:
# Question
Title: Box2D Get Bounding Box of a Body
In Box2D, I was curious if it's possible to get a bounding box of a body already created in the world.

So basically, the Body is created, it's interacting with the world and such. And I needed that Body's bounding box. Is it possible?

# Answer
In Box2D, bodies don't have bounding boxes associated with them, fixture do. So you need to iterate over all the fixtures and generate a new AABB. Something like this:

```
b2AABB aabb;
aabb.lowerBound = b2Vec2(FLT_MAX,FLT_MAX);
aabb.upperBound = b2Vec2(-FLT_MAX,-FLT_MAX);
b2Fixture* fixture = body->GetFixtureList();
while (fixture != NULL)
{
    aabb.Combine(aabb, fixture->GetAABB());
    fixture = fixture->GetNext();
}

```
> 10 votes

# Answer
just using the fixture aabb also includes the shape radius - if you want to get the real aabb without the radius of the shape, do it like this:

```
b2AABB aabb;
b2Transform t;
t.SetIdentity();
aabb.lowerBound = b2Vec2(FLT_MAX,FLT_MAX);
aabb.upperBound = b2Vec2(-FLT_MAX,-FLT_MAX);
b2Fixture* fixture = body->GetFixtureList();
while (fixture != nullptr) {
     const b2Shape *shape = fixture->GetShape();
     const int childCount = shape->GetChildCount();
     for (int child = 0; child < childCount; ++child) {
            const b2Vec2 r(shape->m_radius, shape->m_radius);
            b2AABB shapeAABB;
            shape->ComputeAABB(&shapeAABB, t, child);
            shapeAABB.lowerBound = shapeAABB.lowerBound + r;
            shapeAABB.upperBound = shapeAABB.upperBound - r;
            aabb.Combine(shapeAABB);
    }
    fixture = fixture->GetNext();
}

```
> 1 votes

# Answer
Really, a for loop is usually better for iteration. Taking @noel 's answer:

```
b2AABB aabb;
aabb.lowerBound = b2Vec2(FLT_MAX,FLT_MAX);
aabb.upperBound = b2Vec2(-FLT_MAX,-FLT_MAX);
for (b2Fixture* fixture = body->GetFixtureList(); fixture; fixture = fixture->GetNext())
{
    aabb.Combine(aabb, fixture->GetAABB());
}

```

The expression `fixture`, taken as boolean, is, I understand, equivalent to `fixture != NULL`.
> 0 votes

# Answer
This is what I generally use:

```
Rect aabb = someNode->getBoundingBox();
DrawNode* drawNode = DrawNode::create();
drawNode->drawRect(aabb.origin, aabb.origin + aabb.size, Color4F(1, 0, 0, 1));
this->addChild(drawNode, 100);

```

Where this is some parent node. I've even added this to the node itself (e.g. someNode) and that also seems to work, just make sure your z-index is high enough.
> 0 votes

---
Tags: physics, box2d
---


# Question
Title: Preventing a Child object (eg. some weapon) from going inside other objects in the scene?
I have Cube with a sword like object as its child object. But when the cube moves in the scene the sword goes into the other objects in the scene. The sword have a *BoxCollider* attached to it but the scene contains objects that are stationary and don't have a *Rigidbody* attached as I don't want them to be controlled by *physics*, same for the sword. If I attach *Rigidbody* to it then it will be displaced from its main position on collision.

I tried to render only the Cube including the sword with one *camera* having higher depth value then the *main camera* in the scene. If my game was in first person then this works fine but In 3rd person when object get behind other objects in the scene we can still see the object.

How can I prevent the sword from going into other object without being controlled by *physics*?

***Image:***

# Answer
> 1 votes
Put the colliders on the the objects in your scene that you don't want the sword to pass through and leave off the rigidBody. You don't have to have a rigidBody on those objects for the collision detection to make the object have a physical presence in the scene, and if it is an object that does need a rigidBody, you can mark the body as `isKinematic` in the editor. That means it will not accept an in-coming force (therefore it wont get moved).

You may want to read up on the Unity Docs on RigidBody and Colliders because depending on how you set this up will change how you script things like `OnCollision()`

---
Tags: unity, collision-detection, camera
---


# Question
Title: What do I need to legally use copyrighted music in my game?
I asked the singer of a song I am using, and he agreed to me using his music, provided I credit him. Do I need anything else, such as an agreement or signature?

# Answer
First and foremost, I am not a lawyer. You should *always* consult a lawyer in regards to legal questions - the legal system is often very fickle, and often changes dramatically from location to location.

---

## Can you legally use this music piece? It is impossible to tell.

You tell us you have permission from the *singer*. The first thing you need to find out is whether the singer actually holds *all* copyright reservations for the piece. The singer *performing* in the piece does not necessarily mean *anything*, in regards to copyright. Do your research. Find out who actually *wrote* the piece. Find out if it is a solo work, or a collaboration. Find out if the original writers actually *own* the copyright; under certain circumstances, the actual copyright could still belong to somebody entirely differant.

Do *not* assume that any one person retains all copyright on the simple basis that they are the one *performing* the piece. It is also worth considering that you could still be receiving the wrong information from the artist; perhaps they do not realise that the ten second sample they took from another song could impose *serious* copyright infringement. Perhaps they know very well, but would rather just say they hold all rights, to ensure further publicity.

## What should I do to legally acquire use of a song?

The only *effective* way to legally acquire the use of a song is to *consult a lawyer*. Preferably a copyright lawyer, as they will be more knowledgeable of the particular domain of law you are trying to follow. I say *effective*, because there is no *sure-fire* way to ensure legal process; at least, not in regards to ensuring you do not get sued. The potential copyright holder could still sue you after *all* assurances have been made. It is then up to the courts to decide whether you have legitimate ground; in the mean time, you could be up for very expensive legal fees.

### On receiving confirmation for use

You also want to consider the form of your original "contract". How has the artist approved usage of their song? Via electric message? You would have to prove that you were actually talking to the artist; and *not* somebody else. It does not matter who that "somebody else" could be - a friend, a family member or somebody hacking in to the account - this assurance could easily be thrown out on the *chance* that it was not the original artist replying to your messages.

If this "contract" was verbal, you're in even more trouble. In many cases, a verbal contract is referred to as "non-binding". It is not that they have no *merit*, but it is often hard to prove that they actually said what you claim they said. It becomes a case of "he said, she said", which again, often offers no bearing in court.

### On writing up a written contract

Do not bother signing a legal contract, yourself, without a lawyer. In some cases, a contract is null and void simply on the basis that the parties signed *without* a lawyer.

---

## TL;DR: If you want to legitimately use somebody else's song in your game, you should consult a lawyer. If you can not afford to consult a lawyer, you can not afford to defend your right to use the song, should any issues actually come about.
> 41 votes

# Answer
The singer is just a small part of a music track. It consists of:

* The vocals provided by the singer
* The text of the lyrics
* The composition of the melody
* The arrangement of the melody
* The performance of musicians playing the melody
* Individual audio samples used in the song
* The final audio mix of all these things together

All these creative inputs can be provided by different people and when any of these people feels that their copyrights are violated by you they might cause you trouble. So you need to make sure that you own the rights to **all** of this before you use a song in your game.

To make things simpler, most record labels secure the exclusive and redistributable rights to all these things before they publish a song, making it possible for them to relicense the whole song as a whole.

A common clause for art license contracts is that the licensor guarantees that they own all the copyrights and that they are liable in case that turns out to be wrong. You might want to ask a lawyer specialized in copyright law to draft the contract.
> 16 votes

# Answer
In the 90s I worked for the largest computing magazine in Hungary and we had a cover CD, some 30 000 copies a month. We offered up and coming musicians to put their music there for free. This was insanely popular with our audience and the musicians both. A bit later the collective rights management agency in the country sued us and won because the law said you needed to pay them a fee per copy per minute. This is called a mechanical royalty. So even if the copyright holder grants you a license and very glad actually to spread their music you might not be in the clear. Definitely lawyer up.
> 7 votes

# Answer
## Licensing from the authors

This can be complicated if a copyright collecting agency or a licensing agency in involved. If you deal directly with the authors, they can issue you a license.

If that license is exclusive, we want to make sure it is not fake, thus we want the license written and signed by the author or digital and digitally signed. The author may want to seek legal advice to do this.

---

Authors, because - as the other answers have stated - the audio recording involves diverse intellectual property, including the interpretation of the lyrics and melody, samples, audio composition, etc.

You have permission from the singer of the music you want, is the singer also the writer of the song? What about the people who play instruments? Did they use any samples from third party? In addition, somebody composed and edited the final recording, what about that intellectual property?

This can be further complicated. For example, if I want to record a song that written by another musician, I need to license that song, and the license I acquire may or may not allow me to license my recordings of it.

---

## Licensing from a licensing agency

You must find out if a licensing agency manages the particular work, in accordance to depending on local law.

In some places, the law states that authors needs an affiliation to a licensing agency appointed by the government in order to legally earn revenue form their work, this is not true worldwide. Furthermore, in some countries, the author needs to apply for a special permit to license their work outside of a licensing agency.

If there is a licensing agency managing the copyright of the work, that agency will define the procedure to follow to license the work, and how to pay any loyalties.

---

Licensing agencies should make it easy for authors to license their work and earn loyalties from them. They serve as intermediary between the licensee and the author, and often charge a fraction of the loyalties (although there are other business models and payment schemes for the authors, those are particular of the agency in question).

Consider, for example, a T.V. show that used music from a particular artist. Evidently, the T.V. producer has to acquire a license for that music. Furthermore, according to that license, reruns of the T.V. show may generate loyalties for the author. A licensing agency will keep track of that, and keep the revenue stream flowing... for a fee.
> 5 votes

---
Tags: copyright, music
---


title: Javascript Branching Dialogue

text:
# Question
Title: Javascript Branching Dialogue
I found this question with a really amazing answer How do I implement branching dialogue in javascript?

Unfortunately I can't seem to understand how to get this to work since the code posted isn't complete.

I've gotten my script to print out everything up to the decisions the player has to make, but I just can't understand how to feed the answer back into the script and give the player back the appropriate response.

Here's what I have so far

```
var current_step;

var story = [
  { m: "Hi!" },
  { m: "This is my new game." },
  { question: "Do you like it?", answers: [
    { m: "yes", next: "like_yes" },
    { m: "no", next: "like_no" },
  ] },
  { label: "like_yes", m: "I am happy you like my game!", next: "like_end" },
  { label: "like_no", m: "You made me sad!", next: "like_end" },
  { label: "like_end" },
  { m: "OK, let's change the topic" }
];

function execute_game() {
  var current_line = 0;
  while (current_line < story.length) {

    current_step = story[current_line];

    if (undefined !== current_step.m) {

      display_message(current_step.m);

      if (undefined !== current_step.next) {

        current_line = find_label(current_step.next);

      } else {

        current_line = current_line + 1;

      }

    } else if (undefined !== current_step.question) {

      display_message(current_step.question);
      display_answers(current_step.answers);
      return;

      // display the question: current_step.question
      // display the answers: current_step.answers
      // choose an answer
      // and change current_line accordingly

    }
  }
}

function display_message(varStore) {
    document.getElementById("container").innerHTML += varStore + "<br>";
}

function display_answers(varStore) {
    for (i = 0; i < varStore.length; i++) {
        document.getElementById("container").innerHTML += "<a href='" + varStore[i].next + "'>" + varStore[i].m + "</a><br>";
    }
}

```

What do I need to do from here?

# Answer
> 0 votes
One option would be to use hashkey navigation.

Have the links point to `href`'s beginning with a `#` followed by the label of the next line of dialog.

The original intended purpose of this syntax are links within a HTML document. But the fact that clicking on them does not trigger a page reload makes them very useful for Javascript single-page applications like yours. They trigger the `window.onhashchange` event, which can then check `location.hash` to get the href of the link the user clicked on.

Here is a little proof-of-concept consisting of a javascript snippet which must run on page load and a piece of HTML which uses it:

```
window.onhashchange = function() {
   alert("You clicked on " + location.hash);
}
```

```
<a href="#Answer1">Click!</a>
<a href="#Answer2">Click!</a>
<a href="#Answer3">Click!</a>
```

But hashkey links have a side-effect you should be aware of: They generate history-entries in the user's browser history. See what happens when you run the code snippet above, click on some of the links and then click your browser's back-button. The user can navigate back and forth in your story using their web browser.

Another option which doesn't have this side effect is to use click handlers instead of links.

Create a HTML node (I would recommend a `<button>`, but it works with anything that looks clickable) and then assign an `.onclick` event handler to it.

```
function display_answers(varStore) {
    var container = document.getElementById("container")
    varStore.forEach(function(answer) {
        var answerButton = document.createElement("button");
        button.innerHTML = answer.m;
        button.onclick = function() {
            goto(answer.next);
        }
        container.appendChild(button);
    });
}

```

Note that I am using the `Array.prototype.forEach` function instead of a `for`-loop. That's not just a stylistic choice. This pattern makes sure that the current value of the variable `answer` is captured when the new anonymous function is created which then gets assigned to the onclick-handler.

This code also calls a new `function goto(label)` which you will have to implement on your own. But that shouldn't be hard: it needs to do the same thing `execute_game()` does, just start from the given label and not from line 0.

---
Tags: javascript
---


title: My model is drawn wrong in 3d

text:
# Question
Title: My model is drawn wrong in 3d
I'm learning OpenGL and now after I made everything I needed, I started with 3D, my first problem is that my mesh doesn't draw like I intended...

Here's my rectangle (uses GL\_TRIANGLES):

```
std::vector<GLfloat> Vpos =
{
    0.5, 0.5, //0.0,
    0.5, -0.5, //0.0,
    -0.5, -0.5, //0.0
    - 0.5, -0.5, //0.0
    - 0.5, 0.5, //0.0,
    0.5, 0.5, //0.0
};//comms are the 3d version

```

And here I draw my array:

```
glDrawArrays(GL_TRIANGLES, 0, verNum / 2); //it is binded with vertex array, I use shaders

```

And my fragment shader is:

```
#version 330

in vec2 passTextureCoords;

out vec4 outColor;

uniform sampler2D ourTexture;

void main()
{
    outColor = vec4(0.0, 1.0, 0.5, 1.0);// texture(ourTexture, passTextureCoords); I don't have a texture so I use a lightgreen for debug proposes
}

```

Also my vertex shader:

```
#version 330

layout (location=0) in vec3 inVertPos;
layout (location=1) in vec2 inTexCoords;

out vec2 passTextureCoords;

void main()
{
    gl_Position = vec4(inVertPos.x, inVertPos.y, inVertPos.z, 1.0);
    passTextureCoords = inTexCoords;
}

```

Thanks for help by now, I pretty sure that I missed something small but important.

# Answer
> 1 votes
1) When you comment in or out elements of your `Vpos`, it changes the stride length of your inVertPos attribute. It looks like the stride is wrong and the zeros for the Z are getting into your X/Y coordinates. I strongly suspect that your stride is still being calculated incorrectly, based on the points being rendered in your screenshot (notice they match exactly my demo of "incorrect code" with a bad stride of `8`)

2) Your `Vpos` vector is missing some commas. This also breaks your square.

```
// this vector only has one element in it!
vector<float> demo = {
   0.0
   - 1.0
};

```

```
cv.width = document.body.clientWidth;
cv.height= document.body.clientHeight;

var gl = cv.getContext('webgl')
var frag = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(frag, 'void main() { gl_FragColor = vec4(1); }');
gl.compileShader(frag);
var vert = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vert, `
attribute vec3 pos;
void main() { gl_Position = vec4(pos, 1); }`);
gl.compileShader(vert);
var prog = gl.createProgram();
gl.attachShader(prog, vert);
gl.attachShader(prog, frag);
gl.linkProgram(prog);
gl.useProgram(prog);
gl.enableVertexAttribArray(0);
var buf = gl.createBuffer();

// correct
var verts = [
    0.5,  0.5,  0.0,
    0.5, -0.5,  0.0,
    -0.5, -0.5, 0.0,
    - 0.5, -0.5, 0.0,
    - 0.5, 0.5, 0.0,
    0.5, 0.5,   0.0,
    ];
gl.viewport(0, 0, cv.width / 2,cv.height);
gl.bindBuffer(gl.ARRAY_BUFFER, buf);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(verts), gl.STATIC_DRAW);
gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 12, 0);
gl.drawArrays(gl.TRIANGLES, 0, verts.length / 3);
// incorrect
var verts = [
    0.5,  0.5,  0.0,
    0.5, -0.5,  0.0,
    -0.5, -0.5, 0.0
    - 0.5, -0.5, 0.0
    - 0.5, 0.5, 0.0,
    0.5, 0.5,   0.0,
    ];
gl.viewport(cv.width / 2, 0, cv.width / 2,cv.height);
gl.bindBuffer(gl.ARRAY_BUFFER, buf);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(verts), gl.STATIC_DRAW);
gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 8, 0);
gl.drawArrays(gl.TRIANGLES, 0, verts.length / 3);
```

```
#cv { background:#59e; width:100%; height:400px; }
```

```
(left: correct. right: incorrect)
<canvas id=cv>
```

---
Tags: opengl, c++
---


title: Placing a gameobject with restrictions

text:
# Question
Title: Placing a gameobject with restrictions
I am newbie in programming and I am making a tower defense game 2d. My problem is I want to make a restriction to place a tower only, if the mother tower is in place or within its range. I'm sorry if my explanation is a bit confusing. For example, you can oly place a certain tower within the range of the mother tower and only if that mother tower is placed. I don't exctly know if I have to create a function for this or create a range game object for the placement attached to the mother tower. Any help and tips would be appreciated, thank you. This is by the way unity C#.

# Answer
That's simple! All you have to do is, first to find the mother tower by name by going `GameObject mother = Find("Mother")` or whatever you call it. Check `if (mother != null)`, and if so take the Euclidean distance between the mother's Vector2 and the tower's Vector2 like `Vector2.Distance(mother.transform, tower.transform)` (assuming you have tower defined as another GameObject for your tower.

All together now:

```
GameObject mother = Find("Mother");
if (mother != null) {
    if (Vector2.Distance(Input.mousePosition, mother.transform.position) < 20) { // replace that with your range
        // place your tower on click
    } else
        print("Too far m8");
} else
    print("Build a mother first m8");

```
> 1 votes

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


# Question
Title: Is there a main UI renderer in Unity? I changed the transparency and now everything is translucent
I was trying to change the transparency of a `Button` object. I tried a few things like:

* `button.GetComponent<Renderer>().material.color = translucentColor`
* `button.GetComponent<CanvasGroup)().alpha = 0.5f`

And a few other things, I'm not sure. But the weirdest thing happened. I changed some value of something to like half alpha, and suddenly, every UI element in my game is permanently translucent! Even though I reverted that code, I can't figure out what has turned permanently translucent.

Is there some sort of god object attached to the canvas whos properties can be changed at run time and then set forever? I'm a bit new to Unity so seeing this behavior is very unnerving and weird.

I'm poking around in Unity's editor UI and I see something called the `Default UI Material` at white at half transparency. Could that be it?

If so, is that changeable? It's all grayed out.

# Answer
> 4 votes
This sounds like a bug or oversight in Unity.

Normally a line like this:

`someObject.GetComponent<Renderer>().material` ...

will create a *copy* of the current material being used, unique to this object, specifically so that whatever you do to the material next *won't* spill over onto other objects sharing that material, or alter the source asset in your project files.

(You can use the `.sharedMaterial` property instead to avoid this copy if you're being careful and want to control how many material copies get instantiated)

Unfortunately, the `.material` property on UI renderables like `Image` does not have this copy behaviour.

So this:

`someObject.GetComponent<Image>().material` ...

hands you the *actual original source material* the object is currently using, without copying it.

And if you didn't set a custom material on the UI, then this gives you a reference to the global default UI material and lets you change it in code, even though it's treated as non-editable in the editor interface. It seems like mucking with this should at least generate a warning.

Fortunately, changing the material directly is not the preferred way to apply colour changes to UI (which might be why this seeming inconsistency slipped through). Instead, most UI renderables expose colour properties for this purpose, which can apply tints on top of the material colour, letting us draw lots of differently-coloured UI in batches without lots of costly material changes.

So you'd do something like:

```
myButton.GetComponentInChildren<Image>().color = translucentColor;

```

That way you tint just the button's backing image, not everything in the UI!

To fix the default UI material, all I had to do was close my project and re-open it. It seems Unity doesn't serialize changes to the default UI material (fortunately!)

# Answer
> -2 votes
Each component type in your envoironment should have a different material. Therefore, if you want to change the transparency of the button, it won't change the transparency of other objects.

---
Tags: unity
---


# Question
Title: Want event to occur when button is held but not when clicked
I'm wondering if there is a way to have an event occur when the left mouse button is held down, but not to occur when it is initially clicked. I think you can do something like...

```
if (Input.GetMouseButtonDown(0))
{
    // do stuff
}
else if (Input.GetMouseButton(0))
{
    // do other stuff
}

```

It looks at first like this would work because when left click is clicked it would execute the first if statement and not test for the second. And if left click is held it would fail the first if condition. But, does this in fact work? Do you actually enter the second if statement when attempting to click because you actually hold it down for slightly longer than a true click since this is happening in Update?

Now, I want to do this in one condition. Something like...

```
if (!Input.GetMouseButtonDown(0) && Input.GetMouseButton(0))
{
    // do the stuff that should happen when mouse is held but not clicked
}

```

but I don't think this works either. Any pointers?

For Context, I want to have something happen in every case when mouse button is held down, and only happen in some cases when mouse button is clicked.

```
if (Input.GetMouseButtonDown(0) && !UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject()
|| !Input.GetMouseButton(0) && Input.GetMouseButton(0))

```

This doesn't work though

# Answer
> 2 votes
I don't use Unity, but I'll give it my best shot. One way to approach this problem is by defining a counter variable, that increments each tick of the game that the mouse is held down. Then, you could use the following logic (in pseudo-code):

```
if (mouseIsDown && timeSinceMouseDown > 0) {
    // held down and not just clicked
}

```

# Answer
> 0 votes
Input.GetMouseButtonDown() returns true when the click begins.

Input.GetMouseButtonUp() returns true when the click ends.

Input.GetMouseButton() returns true if the button is being clicked.

So you need to use the third function.

---
Tags: unity
---


title: How do I set up a delay mid-function?

text:
# Question
Title: How do I set up a delay mid-function?
I'm trying to set up a delay so that the UI element I'm using to darken and obscure the player's buttons doesn't disappear the second the enemy begins their turn.

Any help would be very appreciated, as I'm super-new and probably making a bit of a hash of things.

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

public class TurnController : MonoBehaviour {

static bool playerTurn;
public static GameObject ControlBlocker;

// Use this for initialization
void Start () {
    playerTurn = true;
    ControlBlocker = GameObject.Find("Control Blocker");
    UIController();
}

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

}

public static void TurnChange()
{
    if (playerTurn == true)
    {
        playerTurn = false;
        UIController();
    }
    else if(playerTurn == false)
    {
        playerTurn = true;
        UIController();
    }
}

public static void UIController()
{
    if (playerTurn == true)
    {
        print("PlayerTurn");
        //Delay here/////////////////////////////////////////
        ControlBlocker.SetActive(false);
    }
    else if (playerTurn == false)
    {
        print("EnemyTurn");
        ControlBlocker.SetActive(true);
    }
}

```

EDIT

So after some Google-fu I've made some changes that allow the code to compile with what looks like a working co-routine;

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

public class TurnController : MonoBehaviour {

public static TurnController instance;
static bool playerTurn = true;
public static GameObject ControlBlocker;

private void Awake()
{
    instance = this;
}

// Use this for initialization
void Start () {
    ControlBlocker = GameObject.Find("Control Blocker");
    ControlBlocker.SetActive(false);
}

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

}

public static void TurnChange()
{
    if (playerTurn == true)
    {
        playerTurn = false;
        print("TCnowFalse");
        instance.StartCoroutine(UIController());
    }
    else if(playerTurn == false)
    {
        playerTurn = true;
        print("TCnowTrue");
        UIController();
    }
}

public static IEnumerator UIController()
{
    if (playerTurn == true)
    {
        print("PlayerTurn");
        //Delay here
        yield return new WaitForSeconds(2);
        ControlBlocker.SetActive(false);
    }
    else if (playerTurn == false)
    {
        print("EnemyTurn");
        ControlBlocker.SetActive(true);
    }
}

```

BUT - Even with this the functionality still isn't working.

The playerTurn == true section of UIController never fires. PlayerTurn never prints to console and the ControlBlocker stays in place.

playerTurn == false works fine however, and TurnChange is working fine too as it prints both messages to the console when appropriate.

Stuck again!

# Answer
Generally this kind of functionality is achieved through Coroutines (functions that can "pause," yielding their execution to later frames).

Here's Unity's documentation explaining what they are / how to use them. https://docs.unity3d.com/Manual/Coroutines.html

Your function as a coroutine would look like this:

```
public static IEnumerator UIController()
{
    if (playerTurn == true)
    {
        print("PlayerTurn");
        yield return null; //Different types of delays, including WaitForSeconds are available. See the docs for how they're used
        ControlBlocker.SetActive(false);
    }
    else if (playerTurn == false)
    {
        print("EnemyTurn");
        ControlBlocker.SetActive(true);
    }
}

```

Just make sure to call it using "StartCoroutine()" rather than calling the function outright.
> 1 votes

---
Tags: unity
---


# Question
Title: Game engine design choice, favour data oriented design over oop?
I have a scene, in the scene there are multiple systems. Transformsystem, collidableSystem etc ... Currently, these do nothing except returning a bool if the parameter component matches the system:

```
bool DrawableSystem::match(Component* component)
{
    return dynamic_cast<Drawable*>(component) != 0;
}

```

The parent class handles everything else:

```
class System
{
protected:
    std::vector<Component*> _components;
    std::map<int, int> _idToOffset;
public:
    System();
    ~System();

    void initiate();
    void update(long);
    void remove(unsigned int);
    Component& getComponent(unsigned int);
    bool contains(unsigned int);
    void add(Component*, unsigned int);

    virtual bool match(Component* component) = 0;
};

```

The match method is used in scene when i for example instantiate an entity (I dont really have an entity class, its just a vector of components). It returns the id which is used when interacting with the components representing that entity.

```
unsigned int Scene::instantiate(std::vector<Component*> components)
{
    _currentId++;

    for (Component* component : components) {
        for (System* system : _systems) {
            if (system->match(component)) {
                system->add(component, _currentId);
                break;
            }
        }
    }

    return _currentId;
}

```

This will make it so that the vector \_components in each system consists of only components associated with that system.

The current design is very maintainable and extendable, i don't have to modify any code in scene when adding a new type of component or system as you can see:

```
Scene::Scene() {
    _currentId = -1;
    _systems.push_back(new TransformSystem());
    _systems.push_back(new DrawableSystem());
    _systems.push_back(new CollidableSystem());
    _systems.push_back(new ScriptableSystem(*this));
}

Scene::~Scene()
{
    for (System* system : _systems) {
        delete system;
    }
}

void Scene::initiate()
{
    for (System* system : _systems) {
        system->initiate();
    }
}

void Scene::update(long dt)
{
    for (System* system : _systems) {
        system->update(dt);
    }
}

unsigned int Scene::instantiate(std::vector<Component*> components)
{
    _currentId++;

    for (Component* component : components) {
        for (System* system : _systems) {
            if (system->match(component)) {
                system->add(component, _currentId);
                break;
            }
        }
    }

    return _currentId;
}

void Scene::addComponent(Component* component, unsigned int id)
{
    for (System* system : _systems) {
        if (system->match(component)) {
            system->add(component, id);
        }
    }
}

bool Scene::exists(unsigned id)
{
    for (System* system : _systems) {
        if (system->contains(id)) {
            return true;
        }
    }
    return false;
}

void Scene::destroy(unsigned int id)
{
    for (System* system : _systems) {
        if (system->contains(id)) {
            system->remove(id);
        }
    }
}

```

But from what i've heard oop should not be used extensively like i do when designing a game engine.

I tried a purely data oriented design in the beginning but it started to get difficult to modify when i got up to around 4 different systems / component types.

Worth mentioning is that this is my first time making a game engine or anything remotely that complex so i can't really plan everything out in detail and just implement it by looking at an UML diagram. I constantly come up with better architectural choices for how the systems / scene communicate, additional method that could be useful etc ...

Do you gain so much in performance using a data oriented approach that reducing maintainability / modifiability would be worth it? It does not feel like it at all in my case, but i'd really like to learn how they do it in the industry and start learning "the right way" from the start. Are there other potantial gains with dod that i haven't thought about?

# Answer
> But from what i've heard oop should not be used extensively like i do when designing a game engine.

I'm not sure where you heard this, but it sounds like junk advice. OO design and patterns are *perfectly fine* to use in a game engine, and are used often. There are certainly ways to abuse OO design and produce horrible monstrosities, and you should avoid those. But you shouldn't get on the dogma bandwagon of "no OO anywhere" unless you *absolutely* know what you are doing and why.

Object- and data- oriented designs are not mutually exclusive, either. Good OO is useful and enabling. Good DO is useful and enabling. Great game engines use both. *Bad* implementations of either are harmful, and should be avoided.

> Worth mentioning is that this is my first time making a game engine or anything remotely that complex so i can't really plan everything out in detail and just implement it by looking at an UML diagram.

You're going to get this wrong and fail. Many times. Many, *many* times. Don't stress out about "doing it the right way" or emulating the industry in any fashion (more on that later). Focus instead on making something that actually *is* a *game* engine: that is, something you can make a game with, as demonstrated by the fact that you *have* a game to show off with it. It can be a simple game: Asteroids, Breakout, even Pong. But by forcing yourself to use the thing in the context it's intended for, rather than just theorizing about it, you will gain a better understanding of reality and what the pros and cons of any given architectural decision are. I encourage you, for example, to go back and examine *why* your initial "pure data-oriented" approach fell flat. Beyond just "it got difficult." Really understand why your design choices *made* things difficult.

> Do you gain so much in performance using a data oriented approach that reducing maintainability / modifiability would be worth it?

Maybe. "Data oriented" approaches are simply approaches that are focused on understanding the shape of your data and the transforms you need to make on it to make them work. It's not just "stuff everything into a vector, and it will be fast" (although that's true often, it's not *always* the way to go for a good data-focused approach). That's why they're not incompatible with OO approaches; you can do both, as long as you understand the data and what is (and isn't) important about it.

At this point, what will limit the performance of your solutions right now is you, the programmer. Not the broad-strokes architecture you use.

> i'd really like to learn how they do it in the industry and start learning "the right way" from the start.

"The industry" is not a uniform body, and "they" do things wildly differently from person to person and (and here's the important part), *not all of them are good*. Being in the industry just means somebody is paying you to write games, which implies some particular minimum ability bar, but it hardly means everybody in the industry is brilliant at every aspect of building a game. Don't fall into that sort-of hero-worship trap. You can trust, but verify: reach conclusions on your own.

Similarly there is no one "right way," beyond the way that involves careful study of what you are doing, why, and whether or not it meets your goals. There are several wrong ways, though. Don't stress about getting things right the first time because that is *impossible*. Instead, allow yourself to be detached from the emotional investment of your solutions and understand when you come across better ideas or new implementations that you can simply refactor your existing code (which helps you in turn build a whole different set of useful skills).
> 2 votes

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


# Question
Title: SharpDX(DirectX 11) N-tier layering of images
I have an project I'm looking for a better solution to. I have a need to render n images over each other the previous one. So I have loop if you will. This should simulate alpha bending via basic combining the target and overlay pixel color values. Please see code below.

```
public void Render()
    {
        Device3DModule.DeviceContext.ClearRenderTargetView(Device3DModule.RenderTargetView, Colors.Blue.ToDXColor());

        CompositeShader.Apply();

        foreach (var image in Images)
        {
            Texture2D target = null;
            var pass01 = true;

            foreach (var imageChannel in image)
            {
                if(!imageChannel.IsVisible || imageChannel.Image == null) continue;

                imageChannel.Pass01 = pass01;

                Device3DModule.DeviceContext.PixelShader.SetShaderResource(1, imageChannel.Image);
                imageChannel.CopyToDeviceBuffer(ref m_ChannelSettingBuffer);

                QuadMesh.Draw();

                target?.Dispose();

                target = new Texture2D(Device3DModule.Device, Device3DModule.RenderTarget.Description);
                Device3DModule.DeviceContext.CopyResource(Device3DModule.RenderTarget, target);

                ShaderResourceView = new ShaderResourceView(Device3DModule.Device, target);
                Device3DModule.DeviceContext.PixelShader.SetShaderResource(0, ShaderResourceView);

                pass01 = false;
            }

            target?.Dispose();
            ShaderResourceView.Dispose();
        }
    }

```

Does anyone have a better idea?

# Answer
the way I have done it via shader is to take the 2 images, and lerp each pixel (sample really) between source and destination. Using a value between 0 and 1 to weight the lerp between each pixel. Its gives a good representation, and gives you access to additional sampling features like bilinear/trilinear/ansiotropic filtering.

The other benefit of doing this is, if the textures are different sizes then the sampling will take into account this as well (using uv's obviously).

There is additional set up like creating a fullscreen quad, but I think it gives you the best outcome for all the other issues you have to deal with (sizing etc).

For multiple images \> 2, you could set your loop up as.

Create 2 backbuffers as rendertargets / shader resources.

Set first first 2 images to blend -\> render to a first backbuffer. Next loop, set 1 texture source to the previous backbuffer and the other to your next image, set rendertarget to backbuffer 2.
each loop, just swap between backbuffers as render target/shader resource. for each layer, you can set your blend amount as you see fit.

Anyway, goodluck.
> 0 votes

---
Tags: c#, directx, sharpdx
---


# Question
Title: DX11 render 800x600 scene without a window
Normally I would create a hidden overlay window and render my DX scene into that, but I think it is possible to render without a window at all as well, is this true? The goal for me is to render on top of all running Windows applications without using a `TOPMOST` window.

Does someone know how this would approximately be achieved? Thanks!

# Answer
Firstly, you can render to a target backbuffer without a swap chain. That's possible, the issue you really have is basically taking over a section of the users desktop to have priority on the desktop. I believe the ability to do this removed back in win 98 days (someone can confirm).

So really, you are left with doing annoying things to bring this to the front. That being, you either can use a windows form or a UWP, but they are in a window. You can though remove the frame of the form firstly to make it look like it has no parent window (UWP does this well). But then you are left with then bringing it to the front of everything, you can do that with a thread that constantly checks if it is in focus and bring it in focus/to the front. But this has the issue that it then takes focus off other applications which makes it aggravationware. I haven't seen other methods that can simulate your requirements, but that's the way I would look to solve for it (for now!).
> 1 votes

# Answer
You can render to the full screen by setting the DXGI\_SWAP\_CHAIN\_FULLSCREEN\_DESC struct's Windowed property to TRUE. You can use this struct by creating your swap chain with the IDXGIFactory2::CreateSwapChainForHwnd method.
> -1 votes

---
Tags: directx, rendering, directx11, windows
---


title: Add action to GameObject

text:
# Question
Title: Add action to GameObject
So I'm creating a Unity project that has a bunch of buttons (like hundreds) that each do a different thing when pressed. This is a 3D project and these buttons are also 3D. I already know how to detect if the player has pressed a button, so I just need to know how to attach an action to one of these buttons.

Should I create a script for each? From what I've found, it's very memory-expensive and will definitely drop FPS especially for hundreds of buttons.

Should I try to use a UnityEvent? I don't know if this helps for what I'm doing...?

# Answer
You have to write your actions as public functions in a script, let's call it MyActions.cs, and define you functions like this :

```
  public void myActionForButtonA()
  {
      Debug.Log("Clicked on button A");
  }

  public void myActionForButtonB()
  {
      Debug.Log("Clicked on button B");
  }

```

Then to add a function to a button you have basically two options :

## Add it from code

You can add a listener to a button from the code like this :

```
 private Button myButton;

  void Start()
  {
      myButton = GetComponent<Button>();
      myButton.onClick.AddListener(() => myAction());
  }

  void myAction()
  {
      Debug.Log("This is a custom action.");
  }

```

## Add it from the inspector

Select your *Button* object in the hierarchy, open the *Button component* of your object and then in the *On Click ()* section, select your script (MyActions.cs) and the right function to perform (myActionForButtonA for the button A as you guess).
> 1 votes

# Answer
Probably you can try to make a base class and make new class inheriting from the base when you want a button to do something different:

For example, a base class like this:

```
public abstract class BtnHandler
{
    public abstract void OnClicked();
}

```

Then you make a new class to handle button A action:

```
public class BtnAHandler : BtnHandler
{
    public override void OnClicked()
    {
        // do the what this button supposes to do
    }
}

```

Assign the BtnAHandler class to your button A in the scene. In you clicking detection method, you will have:

```
void ClickedOnButton(3DButton btn)
{
    btn.GetComponent<BtnHandler>().OnClicked();
}

```

This is a very simple setup. You could go a little complicated by adding different parameters, different state of clicking, etc.

Generally speaking, using some inheritance ideas in your codes will make it easier to maintain and easy to scale.

Thanks!
> 0 votes

---
Tags: unity, algorithm
---


title: Spawn system not working correctly

text:
# Question
Title: Spawn system not working correctly
I try to spawn one or two obstacle at the same time given the position rightpos, midpos, and leftpos but i keep getting the spawn position to only rightpos and midpos.

```
     void Start () {
     rightpos = new Vector2(2f,6f);
     midpos = new Vector2 (0f,6f);
     leftpos = new Vector2 (-2f, 6f);
 }

 // Update is called once per frame
 void Update () {
     if (spawn_activate == true) {
         number_of_spawn = Random.Range (1, 2);
         spawn_activate = false;
     }
     if (number_of_spawn > 0) {
         spawnposition = Random.Range (0, 2);
         if (spawnposition == 0) {
             Instantiate(obstacle,rightpos,Quaternion.identity);
         }
         if(spawnposition == 1) {
             Instantiate(obstacle,midpos,Quaternion.identity);
         }
         if(spawnposition == 2) {
             Instantiate(obstacle,leftpos,Quaternion.identity);
         }
         number_of_spawn -= 1;
     }
 }

```

# Answer
> 1 votes
https://docs.unity3d.com/ScriptReference/Random.Range.html

```
Returns a random integer number between min [inclusive] and max [exclusive] (Read Only).
Note that max is exclusive, so using Random.Range( 0, 10 ) will return values between 0 and 9.

```

You should try

```
 void Update () {
     if (spawn_activate == true) {
         number_of_spawn = Random.Range (1, 3);
         spawn_activate = false;
     }
     if (number_of_spawn > 0) {
         spawnposition = Random.Range (0, 3);
         if (spawnposition == 0) {
             Instantiate(obstacle,rightpos,Quaternion.identity);
         }
         if(spawnposition == 1) {
             Instantiate(obstacle,midpos,Quaternion.identity);
         }
         if(spawnposition == 2) {
             Instantiate(obstacle,leftpos,Quaternion.identity);
         }
         number_of_spawn -= 1;
     }
 }

```

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


# Question
Title: Import Unity Package Into Specific Folder
Everytime i do import custom `unity` package file, I alwasy get **Messy Folder and files** in root of Asset Folder.

Any Idea how to solve this ?

Many Thanks in advance...

# Answer
The way I do it is that I always create a new project first where I import the unity package file. I then change the structure of the project as I want it to look in my final project. Finally I select the files i want to export and then i right click on them and choose "Export as UnityPackage", Open your final project and import your newly created Unity package and voilà.
> 1 votes

---
Tags: unity, unityscript, file, import
---


# Question
Title: How to spawn GameObject exactly in front of another object?
I'm working on a 3D game in Unity and I'm having a problem trying to spawn an object exactly in front of a wall in my game, like hanging a picture on it. I don't want the object to look like it's too far from the wall or overlapping the wall.

```
public void SpawnPrefab(Transform prefab)
{
    compSize = prefab.gameObject.GetComponent<Collider>().bounds.size.z;
    Vector3 mousePosition, targetPosition;
    InputManager inputManager;
    inputManager = prefab.gameObject.GetComponent<InputManager>();
    mousePosition = Input.mousePosition;
    targetPosition = Camera.main.ScreenToWorldPoint(new Vector3(mousePosition.x,mousePosition.y,mousePosition.z + compSize/2 + wallSize/2));
    prefab.localPosition = targetPosition;
    if(isAlreadyClicked == false)
    {
        GameObject comp = (GameObject) Instantiate(prefab.gameObject, new Vector3(prefab.transform.position.x, prefab.transform.position.y, prefab.transform.position.z + compSize/2 + wallSize /2), prefab.transform.rotation);
        isAlreadyClicked = true;
    }
}

```

I tried adding float value on the `mouseposition.z` like `mouseposition.z + <somefloatvalue>` but it doesn't seem working like how I wanted because I have different object with different sizes, where some objects spawn at the back of the wall, while some will spawn too far at the front from the wall.

Update: I managed to get the accurate z position for the spawning process, but there's something wrong with its x and y position, it's not spawning based on the mouseclick position.

```
public void SpawnPrefab(Transform prefab)
{
    clicked = false;
    compSize = prefab.gameObject.GetComponent<Collider>().bounds.size.z;
    Vector3 mousePosition, targetPosition;
    InputManager inputManager;
    inputManager = prefab.gameObject.GetComponent<InputManager>();
    mousePosition = Input.mousePosition;
    targetPosition = Camera.main.ScreenToWorldPoint(new Vector3(mousePosition.x,mousePosition.y,mousePosition.z));
    ray = Camera.main.ScreenPointToRay(targetPosition);
    float rayDistance;
    if(plane.Raycast(ray, out rayDistance))
    {
        prefab.localPosition = ray.GetPoint(rayDistance);
        Debug.Log("clicked");
        if(isAlreadyClicked == false)
        {
            OnClickedButton();
            GameObject comp = (GameObject) Instantiate(prefab.gameObject, new Vector3(targetPosition.x, targetPosition.y, frontWall.gameObject.transform.position.z + compSize - wallSize), prefab.transform.rotation);
            isAlreadyClicked = true;
            Debug.Log(clicked);
        }
    }
}

```

I don't know what is happening...

# Answer
This example might be what you are looking for :

```
Ray myRay;      // initializing the ray
RaycastHit hit; // initializing the raycasthit
public GameObject objectToinstantiate;

void Update ()
{
    myRay = Camera.main.ScreenPointToRay (Input.mousePosition); // telling my ray variable that the ray will go from the center of
// my main camera to my mouse (This will give me a direction)

     if (Physics.Raycast (myRay, out hit)) { // here I ask : if myRay hits something, store all the info you can find in the raycasthit varible.
// things like the position where the hit happend, the name of the object that got hit etc..etc..

         if (Input.GetMouseButtonDown (0)) {// what to do if i press the left mouse button
             Instantiate (objectToinstantiate, hit.point, Quaternion.identity);// instatiate a prefab on the position where the ray hits the floor.
             Debug.Log (hit.point);// debugs the vector3 of the position where I clicked
         }// end upMousebutton
     }// end physics.raycast
}// end Update method

```

Source : this Unity question.

This looks a lot simpler than what you were doing and using this you will make sure that the coordinates of the prefab are exactly where you want them to be. You will just have to adjust the Z axis as you did before.
> 1 votes

---
Tags: unity, coordinates, spawning
---


# Question
Title: How to activate Xbox controller vibrations in Unity?
Is there any way to toggle the XBOX controller vibrations in Unity ? I came across Handheld.Vibrate() but it seems like it's not meant for controllers.

# Answer
> 3 votes
Yes, you're right: The Handheld class just covers handheld devices but not controllers.

There is a library called XInput which should cover your needs. You'll find it on GitHub: https://github.com/speps/XInputDotNet. It is compatible with Unity 4 and 5.

Specifically for the XBox Controller and how to let it vibrate, this might help you: http://answers.unity3d.com/answers/375451/view.html

---
Tags: unity, input
---