title: LWJGL 2 GUI/Text

text:
# Question
Title: LWJGL 2 GUI/Text
I'm currently developing a 3D plane simulator for my bachelor thesis. We've written the engine in LWJGL. We have to provide a GUI, to display some info about the plane that is flying. Like speed, position etc...
We followed a tutorial online from youtuber "Thin Matrix". And now use some TextRenderer. For some reason we can't write text smaller than visible in the provided image.
For 2D games i've experimented with I used the Slick 2D library provided with LWJGL 2, to render text, but I can't use the functions or it throws errors, that those functions are not supported. I guess because we don't use Orthographic projection.
Is there any way to use Slick 2D, or are there other libraries that can be used for easy and smaller text rendering.

# Answer
LWJGL 3 has stb\_true\_type. It can generate a texture atlas and the mesh for each character. I'm using it with my engine it requires a projection matrix with top left origin.

Switching to LWJGL 3 will require you to download the jars lwjgl.org or if you're using maven or other build tools to generate a project from there.

For generating the font atlas

```
this.fontSize = fontSize;
    this.bitmapWidth = bitmapWidth;
    this.bitmapHeight = bitmapHeight;
    try {
        cdata = STBTTBakedChar.malloc(CHAR_AMT);

        ByteBuffer ttf = FileLoader.loadResurce(fontFile);

        STBTTFontinfo info = STBTTFontinfo.create();

        if (!stbtt_InitFont(info, ttf)) {
            throw new IllegalStateException("Failed to initialize font information.");
        }
        ByteBuffer bitmap = BufferUtils.createByteBuffer(bitmapWidth * bitmapHeight);
        stbtt_BakeFontBitmap(ttf, fontSize, bitmap, bitmapWidth, bitmapHeight, 0, cdata);

        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
        textureId = glGenTextures();
        glBindTexture(GL_TEXTURE_2D, textureId);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
        glTexImage2D(GL_TEXTURE_2D, 0, GL11.GL_RED, bitmapWidth, bitmapHeight, 0, GL11.GL_RED, GL_UNSIGNED_BYTE, bitmap);
        glPixelStorei(GL_UNPACK_ALIGNMENT, 4);

    } catch (IOException e) {
        e.printStackTrace();
    }

```

For generating the mesh for the string.

```
 int count = text.length() * 4;
    int verticesId = glGenBuffers();
    int textureCoordinates = glGenBuffers();
    try (MemoryStack stack = MemoryStack.stackPush()) {

        FloatBuffer vert = stack.mallocFloat(text.length() * 8);
        FloatBuffer tex = stack.mallocFloat(text.length() * 8);

        float length = 0;
        for (char c : text.toCharArray()) {
            STBTTAlignedQuad stbQuad = STBTTAlignedQuad.create();
            float[] x = new float[1];
            float[] y = new float[1];
            stbtt_GetBakedQuad(cdata, bitmapWidth, bitmapHeight, c, x, y, stbQuad, true);

            float[] vertices = new float[]{
                    length + stbQuad.x0(), stbQuad.y0(),
                    length + stbQuad.x1(), stbQuad.y0(),
                    length + stbQuad.x1(), stbQuad.y1(),
                    length + stbQuad.x0(), stbQuad.y1()
            };

            float[] textures = new float[]{
                    stbQuad.s0(), stbQuad.t0(),
                    stbQuad.s1(), stbQuad.t0(),
                    stbQuad.s1(), stbQuad.t1(),
                    stbQuad.s0(), stbQuad.t1()
            };
            tex.put(textures);
            vert.put(vertices);
            length += x[0];
        }

        vert.flip();
        tex.flip();

        glBindBuffer(GL_ARRAY_BUFFER, verticesId);
        glBufferData(GL_ARRAY_BUFFER, vert, GL_STATIC_DRAW);

        glBindBuffer(GL_ARRAY_BUFFER, textureCoordinates);
        glBufferData(GL_ARRAY_BUFFER, tex, GL_STATIC_DRAW);
        glBindBuffer(GL_ARRAY_BUFFER, 0);

```
> 1 votes

---
Tags: opengl, java, gui, lwjgl
---


title: Roblox, custom chat filter

text:
# Question
Title: Roblox, custom chat filter
So, I would like to add my own chat filter to my game, how would I do this?

eg: Player says: "DIE" Goes through chat filter and comes out as: "###" or any other string I specify.

# Answer
> 1 votes
Some games have their own custom chat guis. You could create one, then have an event that would fire in the server when a player sends a message. Creating the gui is beyond the scope of this question, but the event could have some pseudocode like this:

```
if(string.match(message, "DIE")) then
    addMessageToGui("###")
else
    addMessageToGui(message)
end

```

For more resources on remote events, you can learn how to communicate between the client and server here:

https://wiki.roblox.com/index.php?title=Remote\_Functions\_%26\_Events

---
Tags: lua, roblox
---


# Question
Title: How can I make an entity invulnerable to fall damage?
I've been using minecraft forge 1.12 to make a mod that gives the user super-jumping abilities. However, I've been having trouble making the player invincible to fall damage. I've tried to use a `LivingFallEvent` like this:

```
@SubscribeEvent
public void onEntityFall(LivingFallEvent event)
{
    event.setDistance(0.0F);
    event.setCanceled(true);
}

```

but the player still gets damage from falling. What did I do wrong?

If you need it, here is my full code:

```
package com.blockmaster6678.totalweirdmod;

    import java.util.List;

import com.blockmaster6678.totalweirdmod.init.ModBlocks;
import com.blockmaster6678.totalweirdmod.init.ModItems;
import com.blockmaster6678.totalweirdmod.money.MoneyWorth;
import com.blockmaster6678.totalweirdmod.money.PlayerMoney;
import com.blockmaster6678.totalweirdmod.proxy.CommonProxy;
import com.blockmaster6678.totalweirdmod.util.Attributes;
import com.google.common.collect.Multimap;

import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommand;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.passive.EntityCow;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Enchantments;
import net.minecraft.init.Items;
import net.minecraft.init.MobEffects;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.network.play.client.CPacketPlayer.Position;
import net.minecraft.potion.PotionEffect;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.living.LivingDropsEvent;
import net.minecraftforge.event.entity.living.LivingFallEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.event.world.BlockEvent.HarvestDropsEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.Mod.Instance;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.event.FMLServerStartingEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;

@Mod(modid = Attributes.ID, name = Attributes.NAME, version = Attributes.VERSION)
public class Main {
    private static boolean helped = false;

    @Instance
    public static Main instance;

    @SidedProxy(clientSide = Attributes.CLIENT_PROXY_CLASS, serverSide = Attributes.COMMON_PROXY_CLASS)
    public static CommonProxy proxy;

    @EventHandler
    public static void PreInit(FMLPreInitializationEvent event) {
        MinecraftForge.EVENT_BUS.register(new Object() {
            @SubscribeEvent
            public void yourPlayerHarvestEvent(HarvestDropsEvent event) {
                if (event.getHarvester() != null) {
                    if (event.getState() == ModBlocks.IVY_BLOCK.getDefaultState()) {
                        event.setDropChance(0.99F);
                        event.getDrops().add(new ItemStack(Item.getItemFromBlock(ModBlocks.IVY_BLOCK), 20));
                        event.getDrops().add(new ItemStack(Items.FIREWORKS, 32));
                    } else if (event.getState() == Blocks.DIRT.getDefaultState()) {
                        event.setDropChance(1.0F);
                        event.getDrops().add(new ItemStack(Item.getItemFromBlock(Blocks.DIRT), 64));
                        event.getDrops().add(new ItemStack(Item.getItemFromBlock(Blocks.CHORUS_FLOWER), 1));
                        event.getDrops().add(new ItemStack(Item.getItemFromBlock(Blocks.CACTUS), 2));
                        event.getDrops().add(new ItemStack(Item.getItemFromBlock(Blocks.SAND), 16));
                    } else if (event.getState() == Blocks.CACTUS.getDefaultState()) {
                        event.setDropChance(0.5F);
                        event.getDrops().clear();
                        event.getDrops().add(new ItemStack(Item.getItemFromBlock(Blocks.CACTUS), 2));
                        event.getDrops().add(new ItemStack(Items.BLAZE_ROD, 5));
                        event.getDrops().add(new ItemStack(Items.EXPERIENCE_BOTTLE, 64));
                        event.getDrops().add(new ItemStack(Items.BAKED_POTATO, 12));
                        event.getDrops().add(new ItemStack(Items.DIAMOND_SWORD, 1));
                        event.getDrops().add(new ItemStack(Items.APPLE, 49));
                        event.getDrops().add(new ItemStack(Items.ENDER_PEARL, 16));
                        event.getDrops().add(new ItemStack(Items.MAGMA_CREAM, 23));
                        event.getDrops().add(new ItemStack(Items.ELYTRA, 1));

                        Minecraft.getMinecraft().player.
                                    addItemStackToInventory(new ItemStack(Item.getItemFromBlock(Blocks.CACTUS), 1));
                    } else if (event.getState() == Blocks.SAND.getDefaultState()) {
                        event.setDropChance(0.1F);
                        event.getDrops().add(new ItemStack(Items.ELYTRA, 1));
                        event.getDrops().add(new ItemStack(Item.getItemFromBlock(ModBlocks.IVY_BLOCK)));
                    }
                }
            }
        });
    }
    @EventHandler
    public static void init(FMLInitializationEvent event) {

    }
    @EventHandler
    public static void Postinit(FMLPostInitializationEvent event) {

    }
    @EventHandler
    public static void onPlayerInteract(PlayerInteractEvent event) {
        EntityPlayer p = event.getEntityPlayer();
        World world = p.getEntityWorld();
        BlockPos pos = event.getPos();
        if (!(p.getHeldItemMainhand().getItem().equals(Item.getItemFromBlock(ModBlocks.IVY_BLOCK)))) {
            return;
        }
        world.setBlockState(new BlockPos(pos.getX() + 1, pos.getY(), pos.getX()), ModBlocks.IVY_BLOCK.getDefaultState());
    }
    @SubscribeEvent
    public void onEntityFall(LivingFallEvent event) {
        event.setDistance(0.0F);
        event.setCanceled(true);
    }
}

```

# Answer
> 2 votes
Your `onEntityFall` method is not registered to the event bus. Notice where your `yourPlayerHarvestEvent` method is and how its context differs from `onEntityFall`.

Additionally, you should use a complete class, rather than a runtime generated object, for your event handlers. This class can also be static (with static methods) and registered with annotations. See the docs

```
@Mod.EventBusSubscriber
public class MyStaticForgeEventHandler {
    @SubscribeEvent
    public static void arrowNocked(ArrowNockEvent event) {
        System.out.println("Arrow nocked!");
    }
}

```

Your `onPlayerInteract` is also not being called. Both because of the incorrect context already mentioned, and because it has the incorrect annotation `@EventHandler` which is only for Forge lifetime events (preInit, etc).

---
Tags: minecraft-modding, entity
---


# Question
Title: Unity: how do I make an input only available to the code?
I have a simple function attached to a button. I then decided to change it by adding an input. The problem is that the function won’t run unless I specify the input in Unity via the inspector. I don’t want to do that because it will affect the function and I have already changed it inside. I already set the input when I run the function so there’s no need to set it again in Unity; this is a problem because the input is going to be different depending on different scenarios. How can I overcome this?

```
public void Eruption(string biome)
{
    if (biome == “sea”) {
        // do something
    }
}

```

# Answer
> **Note:** As of the current version of Unity, this answer is outdated. I posted another answer which applies to Unity Version 2018.3 and later. But I will leave this answer here for those who don't dare to convert their project yet.

Unfortunately you can not tell Unity buttons to call methods with parameters. If you want different buttons to call the same method with different parameters, you will have to take one of several possible workarounds:

Option 1: Create a wrapper-method for each one which takes no arguments and then calls the method you want with the correct argument:

```
public void ErruptionAtSea()
{
    Erruption("sea");
}
public void ErruptionAtLand()
{
    Erruption("land");
}
// ...and so on.

```

Option 2: Add a script to the button which says which biome this button is for. Wire the onclick-event of the button to that script:

```
public class EruptionButton : MonoBehaviour {

    public string biomeName;

    public void DoEruption () {
        Eruption(biomeName)
    }
}

```

Option 3: If you don't want to set up the click handling for each button individually, you can have that script take care of this automatically by assigning a newly created anonymous method as a click handler to the button on the same game object:

```
[@RequireComponent(typeof (UnityEngine.UI.Button))]
public class EruptionButton : MonoBehaviour {

    public string biomeName;

    void Start () {
        UnityEngine.UI.Button button = GetComponent<UnityEngine.UI.Button>();
        button.onClick.AddListener(() => { Eruption(biomeName); } );
    }
}

```
> 2 votes

# Answer
As of Unity 2018.3, a button can pass values to the methods which handle its click events. In order to do that, the function must take exactly one parameter and that parameter must be a string, int, float or bool:
> 1 votes

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


title: nvidia SSAO visible errors

text:
# Question
Title: nvidia SSAO visible errors
I am trying to add ssao effect to a visualization application but there are errors in resulting image. I am using code from https://github.com/nvpro-samples/gl\_ssao . Errors occur in rapidly changing lighting near the edges of screen.

Only change to code was to remove basic shading and passing only white from scene.frag shader so the error could be seen more pronounced. I also added obj input to import sponza scene but the error is visible with the included sample scene as well if camera is moved close to object. As is this implementation only enables viewing objects in relative distance. Moving closer to objects brings up this errors.

What causes this error and is there fix.

# Answer
Since this is a screen-space technique, all the data we have about scene is limited to the G-Buffer, and effect that you are very unhappy about is supposed to be happening due to huge information loss around fragments near the edges of the screen. Usually SSAO has smaller sampling radius so artifacts are not very noticeable.

Also note that in case of screen-space effects, texture wrapping set to `GL_CLAMP_TO_EDGE` could help to hide some of the artifacts a little.
> 1 votes

---
Tags: opengl, nvidia, ssao
---


# Question
Title: I keep coming across an error "Cannot read property 'innerHTML' of undefined"
I'm new to game designing and have to create a game for my project but I keep coming across an error to do with:

> index.html:93 Uncaught TypeError: Cannot read property 'innerHTML' of undefined
>
> at drawMissiles (index.html:93)
>
> at gameLoop (index.html:140)

Any idea how to fix this problem?

```
    drawMissiles()
}

function drawMissiles() {
  document.getElementsByTagName('missile')[0].innerHTML   <--- (index.html:93)
    for(var i = 0 ; i < missiles.length ; i++ ) {
        document.getElementById('missile').innerHTML +=
             `<div class='missile1' style='left:${missiles[i].left}px;
              top:${missiles[i].top}px'></div>`;

```

# Answer
You have written

```
document.getElementsByTagName('missile')[0]

```

and then later

```
document.getElementById('missile')

```

This looks like a typo and you will probably find that document.getElementsByTagName('missile')\[0\] is equal to null.
> 1 votes

---
Tags: javascript, html
---


# Question
Title: 2D Screen Coordinates to 2D World Coordinates in LWJGL
I'm making a 2d top down game with lwjgl and am having trouble converting my 2d screen coordinates to 2d world coordinates.

Here's what I have so far

```
 private Vector2f toWorldCoords(Vector4f eyeCoords) {
    Matrix4f invertedView = Matrix4f.invert(MathUtil.createViewMatrix(camera), null);
    Vector4f rayWorld = Matrix4f.transform(invertedView, eyeCoords, null);
    Vector2f mouseRay = new Vector2f(rayWorld.x, rayWorld.y);
    mouseRay.normalise();
    return mouseRay;
}

public Vector2f screenToWorld(Vector2f mouseCoords) {
    Vector2f normalizedCoords = CursorHandler.getNormalisedDeviceCoordinates();
    Vector4f clipCoords = new Vector4f(normalizedCoords.x, normalizedCoords.y, -1.0f, 1.0f);
    Vector2f worldRay = toWorldCoords(clipCoords);

    return worldRay;
}

```

I understand it's been asked before, and I've tried following some 3d tutorials that deal with the same topic, but so far I haven't been able to use the code successfully.

Thanks

# Answer
> 1 votes
It's quite simple really. Your camera must be an orthographic projection so the formula for screen to camera is:

```
Vector2f cameraPosition = new Vector2f(screenPosition.x - Camera.getWidth() / 2, screenPosition.y - Camera.getHeight() / 2);

```

Then to world coordinates:

```
Vector2f worldPosition = cameraPosition.add(Camera.getPosition());

```

Keep in mind that you'll probably need to invert the camera's position.

```
Vector2f invertedCameraPosition = camera.getPosition().mul(-1, new Vector2f());

```

---
Tags: 2d, lwjgl, mouse, lwjgl3
---


# Question
Title: How do I pack my game LWJGL game into a single executable JAR with Maven?
I am trying to use Maven to manage building my LWJGL projects. The entire project needs to be packed into a single executable jar, dependencies, natives and resources included, so that can be easily distributed. I have been using JarSplice to do this until now.

Is it possible to do the same with Maven?

My attempts thus far have failed: either the main class/natives could not be located or OpenAL would crash when I tried to execute the jar file.

My current pom.xml is below:

```
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>
<groupId>Sidian</groupId>
<artifactId>LWJake2</artifactId>
<version>0.1</version>
<packaging>jar</packaging>
<name>LWJake2</name>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
    <mainClass>Main</mainClass>

    <lwjgl.version>2.9.3</lwjgl.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.lwjgl.lwjgl</groupId>
        <artifactId>lwjgl</artifactId>
        <version>${lwjgl.version}</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
                <showDeprecation>true</showDeprecation>
            </configuration>
        </plugin>
    </plugins>
</build>

```

# Answer
This is the plugin you need

```
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>3.0.2</version>
            <configuration>
                <archive>
                    <manifest>
                        <addClasspath>true</addClasspath>
                        <mainClass>your.main.class.Here</mainClass>
                    </manifest>
                </archive>
            </configuration>
        </plugin>

```
> 2 votes

---
Tags: java, lwjgl, distribution
---


# Question
Title: Have there been precedents where a closed-source game maker adopted user-made code (major overhaul)?
I'm interested to learn if there have been notable cases of a game maker accepting code or game engine portions developed by fans to replace their own buggy/flawed/slow parts, or even complete game remakes that turned official. For open-source games it should not be uncommon, but I'd like to know if there were any closed-source games which did that and the details of such occurrence.

For example, if Dark Souls was remade on Dark Souls 3's engine to improve world mesh clipping, graphics and framerate.

The goal is to find out how realistic it would be to remake or improve some (possibly old) games and figure out all the legal intricacies so it would be allowed for public distribution.

# Answer
When GameSpy went belly-up, Bungie "worked with fans" to create a patch for the original Halo that would route features previously relying on GameSpy through other mechanisms. It's not completely clear what direct input the fans had in this case.

Additionally, the Project Magma group that maintains Myth II (coincidentally, another Bungie game) was originally a group of map-makers and fans. They have access to the original game's source code through a legal agreement and continue to produce actual builds of the game.

The story of Sonic Mania is similar: an officially-licensed game that was "originally" (in some form) a fan game and involved the hiring (or subcontracting of) the author. It doesn't involve a change to an existing product though, so much as hiring somebody to produce a new one.

---

In general, there are a huge variety of legal, marketing, ethical and other issues that would make a company very hesitant to do something like this. The legal ones are probably the biggest: ensuring modifications are unencumbered from legal issues and free of malicious intent or other serious defects, assuming legal ownership of the changes, et cetera.

To that end, I'd expect cases like you're thinking of to be few and far between. But it *has* been done.
> 1 votes

# Answer
Counter Strike was originally a Half-Life mod. The two developers, along with the mod itself and intellectual property were acquired by Valve.
> 0 votes

---
Tags: business
---


title: Check Supported Platforms for Editor

text:
# Question
Title: Check Supported Platforms for Editor
How can I find out from script(c#) did I download specific platfrom support for current Unity version?

# Answer
> 0 votes
Found out the solution. You should dive in into Unity native classes and get info from there:

```
        var moduleManager = System.Type.GetType("UnityEditor.Modules.ModuleManager,UnityEditor.dll");
        var isPlatformSupportLoaded = moduleManager.GetMethod("IsPlatformSupportLoaded", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
        var getTargetStringFromBuildTarget = moduleManager.GetMethod("GetTargetStringFromBuildTarget", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);

        return (bool)isPlatformSupportLoaded.Invoke(null, new object[] { (string)getTargetStringFromBuildTarget.Invoke(null, new object[] { BuildTarget.tvOS }) });

```

# Answer
> 0 votes
When you install Unity , you can choose from a list of supported "build" platform:

* Windows
* Max
* iOS
* Android

and so on.

So you can build specific platform.

You can't check it from C#.

---
Tags: unity, c#, build-process
---


# Question
Title: My character controller is spinnning uncontrollably?
I have a character controller and after trying to implement moving independently of the camera it starts spinning uncontrollably. I have no idea why. Here is the code:

CharacterController:

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

public class Controller : MonoBehaviour {

public float moveSpeed;
public float jumpForce;
public float gravityScale;
public Animator anim;
public float rotateSpeed;
public Transform pivot;
public GameObject playerModel;

private CharacterController controller;
private Vector3 moveDirection;
//private bool isGrounded;
//private Rigidbody rigidbody;

// Use this for initialization
void Start () {

    //rigidbody = GetComponent<Rigidbody>();
    controller = GetComponent<CharacterController>();
    //isGrounded = true;
}

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

    //rigidbody.velocity = new Vector3(Input.GetAxis("Horizontal") * moveSpeed, rigidbody.velocity.y, Input.GetAxis("Vertical") * moveSpeed);

    //moveDirection = new Vector3(Input.GetAxis("Horizontal") * moveSpeed, 0, Input.GetAxis("Vertical") * moveSpeed);
    float ystore = moveDirection.y;
    moveDirection = (transform.forward * Input.GetAxis("Vertical") * moveSpeed) + (transform.right * Input.GetAxis("Horizontal") * moveSpeed);
    moveDirection = moveDirection.normalized * moveSpeed;
    moveDirection.y = ystore;

    if (controller.isGrounded)
    {

        moveDirection.y = 0f;
        if (Input.GetButtonDown("Jump"))
        {

            moveDirection.y = jumpForce;
        }
    }

    moveDirection.y = moveDirection.y + (Physics.gravity.y * gravityScale * Time.deltaTime);
    controller.Move(moveDirection * Time.deltaTime);

    if (Input.GetAxis("Horizontal") != 0 || Input.GetAxis("Vertical") != 0)
    {
        transform.rotation = Quaternion.Euler(0f, pivot.rotation.eulerAngles.y, 0f);
        Quaternion newRotation = Quaternion.LookRotation(new Vector3(moveDirection.x, 0f, moveDirection.z));
        playerModel.transform.rotation = Quaternion.Slerp(playerModel.transform.rotation, newRotation, rotateSpeed * Time.deltaTime);
    }

    anim.SetBool("isGrounded", controller.isGrounded);
    anim.SetFloat("Speed", (Mathf.Abs(Input.GetAxis("Vertical")) + Mathf.Abs(Input.GetAxis("Horizontal"))));
}

/*
void OnTriggerEnter(Collider other)
{
    if (other.name == "Terrain")
    {
        isGrounded = true;
    }
}

void OnTriggerStay(Collider other)
{
    if (other.name == "Terrain")
    {
        isGrounded = true;
    }
}

void OnTriggerExit(Collider other)
{
    if (other.name == "Terrain")
    {
        isGrounded = false;
    }
}
*/
}

```

CameraController:

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

public class CameraController : MonoBehaviour {

public Transform target;
public bool useOffsetValues;
public float rotateSpeed;
public Transform pivot;
public float maxViewAngle;
public float minViewAngle;

private Vector3 offset;

// Use this for initialization
void Start () {

    if (!useOffsetValues)
    {

        offset = target.position - transform.position;
    }

    pivot.position = target.position;
    //pivot.parent = target;
    pivot.parent = null;

    Cursor.lockState = CursorLockMode.Locked;
}

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

    pivot.parent = target;

    //Get the x position of the mouse and rotate the target
    float horizontal = Input.GetAxis("Mouse X") * rotateSpeed;
    pivot.Rotate(0, horizontal, 0);

    //Get the y position of the mouse and rotate the pivot
    float vertical = Input.GetAxis("Mouse Y") * rotateSpeed;
    pivot.Rotate(-vertical, 0, 0);

    //Limit up camera rotation
    if (pivot.rotation.eulerAngles.x > maxViewAngle && pivot.rotation.eulerAngles.x < 180f)
    {
        pivot.rotation = Quaternion.Euler(maxViewAngle, 0, 0);
    }

    //Limit down camera rotation
    if (pivot.rotation.eulerAngles.x > 180f && pivot.rotation.eulerAngles.x < 360f + minViewAngle)
    {
        pivot.rotation = Quaternion.Euler(360f + minViewAngle, 0, 0);
    }

    //Move the camera based on the current rotation of the target and the original offset
    float desiredYAngle = pivot.eulerAngles.y;
    float desiredXAngle = pivot.eulerAngles.x;
    Quaternion rotation = Quaternion.Euler(desiredXAngle, desiredYAngle, 0);
    transform.position = target.position - (rotation * offset);

    if(transform.position.y < target.position.y + 1.5f)
    {
        transform.position = new Vector3(transform.position.x, target.position.y + 1.5f, transform.position.z);
    }

    //transform.position = target.position - offset;
    transform.LookAt(target.position + new Vector3(0, 1, 0));
}
}

```

# Answer
> 1 votes
Here's one reason why: Quaternion.Slerp needs a 0..1 value as the third parameter, and you're using something that's definitely not between 0 and 1. You can try to use a constant value as your third parameter, let's say 0.05 for slow rotation or 0.2 for fast rotation and see if that fixes it. But if you want to limit the rotation speed to some degrees/second value, you'll need to look at the accepted solution here: https://stackoverflow.com/questions/20329460/unity3d-slerp-rotation-speed

---
Tags: character
---


# Question
Title: Generating different maps using Perlin Noise with a seed
I am developing a 2D game in python and I could get Perlin Noise working with this code:

```
import timeit
import noise

POSITIVE =  10
NEGATIVE = -10

BLOCK = "#"
BLOCK_LIMITS = (POSITIVE, 0.3)

WATER = "-"
WATER_LIMITS = (0.3, -0.4)

GRASS = " "
GRASS_LIMITS = (-0.4, NEGATIVE)

oct = 1
outputString = str()

def GENERATE_MAP():
    global outputString

    for y in range(1000):
        outputString += "["
        for x in range(165):
            i = round(noise.pnoise2(x / 15, y / 15, octaves = oct), 5)
                if i > 0.4:
                    outputString += BLOCK
                elif i < -0.5:
                    outputString += WATER
                else:
                    outputString += GRASS
        outputString += "]\n"

time = timeit.timeit(GENERATE_MAP, number = 1)
print(outputString)
print("time = " + str(time))

```

But this creates the same terrain every time, so I thought to use seeds, but I don't know how to do that.
I am using python 3.6 with noise.

# Answer
Looking in the code, the library provides `noise.randomize()` which states:

> Randomize the permutation table used by the noise functions. This makes them generate a different noise pattern for the same inputs.

Thus, randomizing the function through the API provided is the most direct way to solve the problem.

---

Here's an alternative solution based on the the discussion in chat, which I posted before spotting the API function:

If you cannot directly set the seed for your noise (sometimes the case with library code), then you can get around this limitation by using a random scaling &/or translating (shifting) factor.

While I don't recommend using scaling for randomizing, many noise functions give a value of zero for integer coords, so we'll need to adjust for that eventually anyway. Scaling essentially means multiplying by some factor. So for example if your factor is 0.1 then the integer coords 0,1,2,3,... are transformed into the noise coords 0.0, 0.1, 0.2, 0.3, ...

Translating on the other hand can be done by adding some factor. Using 0.1 again as an example the integer coords 0,1,2,3,... becomes the noise coords 0.1, 1.1, 2.1, 3.1, ...

Next, here's how you can use them to randomize your map generation. A noise library I used was deterministic, meaning the noise values for a given coord are never randomized between runs. But I needed the values to change based on a game seed, so I translated my sampling by some random factor & that worked well enough for me. So as an example, when my map generation starts:

* I use a random number generator (seeded to the system time) to get a translation factor for both X & Y, let's call them `tX` and `tY`. Since the system time changes between runs, tX & tY should be different across each run
* Next, I use a scaling factor so that I sample at more than just the integer coords. Let's call that factor `s`.
* Putting it all together, if I needed to get a noise value for some x,y location, I would have something like this: `value = noise(x*s+tX, y*s+tY)`

Depending on the size & scale of your map as well as the period of the noise generating function, translating & scaling may still leave you with unwanted repetition. The typical solution to is to combine multiple layers of noise with differing frequencies and amplitudes.

Frequency is controlled by scaling the X,Y inputs. Multiplying by a factor between 0-1 will increase the frequency, multiplying by greater than 1 will decrease it.

Amplitude is controlled by scaling the output from the noise function. Multiplying by a factor between 0-1 will decrease the Amplitude, multiplying by greater than 1 will increase it.

Together, the changes to frequency and amplitude are often referred to as octaves. Adjusting the octaves is a bit of trail & error art - the common rule of thumb is as you double one, you halve the other (or vice versa).

Even though the underlying noise function remains the same, the combinatorics of translation & scaling summed across multiple layers quickly creates enough variety to overcome repetitions.
> 3 votes

# Answer
Try setting the random seed. A common way to do this is by using the current time as the seed value.

```
import random
from datetime import datetime
random.seed(datetime.now())

```
> 2 votes

---
Tags: procedural-generation, python, perlin-noise
---


# Question
Title: Unity Physics Simulation - Limitations / Inaccuracies? Bounciness of a ball (pool/snooker balls etc)
I am playing with Unity physics engine. I have a pool table and a cue ball. Both have Physic Materials. If I start the game, with the ball floating about 1m above the table, it falls and bounces (bounce depends and happens only if Physic Material, bounciness property is set to something above 0.5 ish.). But I have to have it between 0.8-0.9 bounciness for it to look anything like realistic. And even so after a bounce or two it stops and it doesnt look at all real.

The mass of the ball is set to 0.17.

I've tried playing about with the two Friction properties, but these seem to have no effect on this test. (currently I have these all set to 0.1)

Like I say, it will bounce two or even three times but then seems to come to an abrupt stop.

Also if you set the bounciness of both materials to about 0.9+ the bounces sometimes get larger after a smaller bounce before it.

Does anyone have experience playing with similar physics in Unity? And if so, what else should i change to tweak the behaviour.

The table itself doesn't have a rigidbody, only the balls do.

As an added complication to the question, wouldnt the ball roll slightly in some direction after it had bounced, rather than just bouncing directly up and down?

thanks

# Answer
The realism of a physics simulation is the result of a lot of factors. A first easy step for games that need reliable physics would be to set the Collision Detection of a Rigidbody to Continuous Dynamic. It's kind of complex to explain, but essentially means that collisions will be using more correct data, at the cost of lower performance. Continuous Dynamic means that it does this with both static and moving objects, while Continuous means that it only does this with static objects.

You could also increase the number of physics updates per second to increase realism, but it's generally not worth it and the default 50/s is a good number.

The next step would be making your physics materials as close as possible to the real materials you're approximating.

First I'll explain the main concepts in use.

**Bounciness** is the elasticity of an object. When an object collides with another their bounciness values are averaged and used to calculate how much movement energy is canceled out by the other object (i.e: how much energy is lost in the collision). In essence, if two balls are moving toward each other, a fully in-elastic collision (bounciness = 0) will have the two balls together after the collision (moving or not depending on whether they had the same movement energy toward each other), while a fully elastic collision (bounciness = 1) will have the two objects basically swapping movement energy with each other (which if they have the same weight simply would mean that they swap speeds).

**Friction** is more complex, but is in essence a counter-force acting on an object in the opposite direction of another force while two objects are in contact. **Static friction** is how hard it is to get a still object moving. **Dynamic friction** is how quickly moving objects slow down. The value range is mainly 0 to 1 and is averaged across the two objects in contact, like with bounciness. If unsure, you can generally set both static and dynamic friction to the same value.

Since your test involves a ball falling straight towards a flat surface, friction will have no effect on the test, but is still very important for other interactions and should not be ignored.

### Now, for selecting appropriate values:

Pool balls have a very high elasticity, so you should set your bounciness at close to 1. They also have very low Friction, so both static and dynamic should be set at close to 0.

I'm less certain about pool tables however. They probably have pretty low friction and bounciness, both around the range of 0.1-0.3 if I were to guess.

---

> wouldnt the ball roll slightly in some direction after it had bounced, rather than just bouncing directly up and down?

In reality minor variances in the surface the ball collides with along with small side-movements from the drop of the ball will get the ball rolling slightly after landing. But for the simulation we have no such variances; the ball is moving directly toward a perfectly uniform flat surface, resulting in no side-movement.
> 3 votes

---
Tags: unity, physics, physics-engine
---


# Question
Title: What is the transformation order when using the Transform Class?
I am currently using Unity 5.5 for the first time in a project and I've got some problems regarding transformations.

I've got a background in more general 3D graphics meaning that I'm used to manually manage scene graphs and matrix transformation orders.

My greatest problem when moving to Unity, and using their built in Transform Class, is that I can't find any information regarding the transformation order of rotation, localrotation, scaling, localscaling, position and localposition.

I can't find any good information of this and It's driving me slightly mad.

TL;DR: What's the transformation order of the Transform class?

# Answer
1. Local scale (`localScale`)
2. Local rotation (`localRotation`)

If using Euler angles, they're applied as rotations about the world axes in the order:

1. Roll (rotation about the world z axis)
    2. Pitch (rotation about the world x axis)
    3. Yaw (rotation about the world y axis)

(Or, if you prefer to think of rotations happening around local axes, it's...)

1. Yaw (rotation about the local y axis)
    2. Pitch (rotation about *the resulting* local x axis)
    3. Roll (rotation about *the resulting* local z axis)
3. Local translation (`localPosition`)
4. Parent's local transforms, in the same order as above

Repeat all the way to the root of the transform hierarchy.

The non-local parameters, `lossyScale`, `rotation`, `position`, represent the net effect of this entire transformation chain (`lossyScale` being a "lossy" approximation since, by the time we've combined several scales and rotations, the resulting scale is not guaranteed to be axis-aligned, so it might no longer be well represented by a Vector3)
> 12 votes

# Answer
Take a look to the Inspector tutorial here https://unity3d.com/learn/tutorials/topics/interface-essentials/inspector

and take a look here https://docs.unity3d.com/Manual/UsingTheInspector.html

You have all the information needed visually about:

* Transform position (X, Y, Z)
* Transform rotation as euler angles (X, Y, Z)
* Transform scale (again, X, Y, Z)
> 2 votes

# Answer
You could print out the `localToWorldMatrix`. If the rightmost/4th column contains `transform.position`, then you know the translation was applied last, i.e.

```
localToWorldMatrix = translationMatrix * rotationMatrix !=  rotationMatrix * translationMatrix

```
> 1 votes

---
Tags: unity
---


# Question
Title: My Single Pass Gaussian Blur Looks Awful
I've based my shader on this single pass shadertoy here: https://www.shadertoy.com/view/XdfGDH

I applied the same shader and it looks like this:

Scaled up so you can see the faint tears in the texture. They look grid-like and not smooth at all.

When it should be looking like this:

Source image:

Here's my shader. Translated the shadertoy to GLSL 110

```
#version 110
uniform sampler2D texture;

float normpdf(float x, float sigma)
{
  return 0.39894*exp(-0.5*x*x / (sigma*sigma)) / sigma;
}

void main()
{
  vec3 c = texture2D(texture, gl_TexCoord[0].xy).rgb;

  const int mSize = 11;
  const int kSize = const int((float(mSize) - 1.0) / 2.0);
  float kernel[mSize];
  vec3 final_color = vec3(0.0);

  // Create the kernel
  float sigma = 7.0;
  float Z = 0.0;
  for (int j = 0; j <= kSize; ++j)
  {
    kernel[kSize + j] = kernel[kSize - j] = normpdf(float(j), sigma);
  }

  //get the normalization factor (as the gaussian has been clamped)
  for (int j = 0; j < mSize; ++j)
  {
    Z += kernel[j];
  }

  //read out the texels
  for (int i = -kSize; i <= kSize; ++i)
  {
    for (int j = -kSize; j <= kSize; ++j)
    {
      final_color += kernel[kSize + j] * kernel[kSize + i] * texture2D(texture, (gl_TexCoord[0].xy + vec2(float(i), float(j)))).rgb;
    }
  }

  gl_FragColor = vec4(final_color / (Z*Z), 1.0);
}

```

# Answer
Your sampling points are most likely messed up because you are not taking into account that texture texel size is in range \[0; 1\]. You need to divide offset coordinates by texture resolution. We can get texture resolution using ivec2 textureSize(gsampler2D sampler, int lod) function.

So changing this

`final_color += kernel[kSize + j] * kernel[kSize + i] * texture2D(texture, (gl_TexCoord[0].xy + vec2(float(i), float(j)))).rgb;`

to this

`final_color += kernel[kSize + j] * kernel[kSize + i] * texture2D(texture, (gl_TexCoord[0].xy + vec2(float(i), float(j))/textureSize(texture, 0).xy)).rgb;`

will hopefully fix your shader.
> 3 votes

---
Tags: glsl, fragment-shader, blur
---


title: SDL2 mouse motion event keeps occurring

text:
# Question
Title: SDL2 mouse motion event keeps occurring
The code I'm using is like so:

```
SDL_Event e;
SDL_PollEvent(&e);
switch (e.type)
{
    case SDL_MOUSEMOTION:
    {
        YCam += e.motion.yrel;
    }
    break;
}

```

When I run the program, nothing happens, however, once I first move the mouse, the `SDL_MOUSEMOTION` event keeps firing and the mouse keeps moving. This occurs even when I've stopped moving my mouse. Pressing any key including mouse keys stops the movement.

# Answer
> 5 votes
You're not checking the return value of `SDL_PollEvent` to see if there's a new event, which means that regardless of whether there *is* an event to handle, you're trying to handle one. In practice, this means that you're constantly handling the last event, even if it's no longer occurring. Try this:

```
SDL_Event e;
if (SDL_PollEvent(&e)) {
    switch (e.type)
    {
        case SDL_MOUSEMOTION:
        {
            YCam += e.motion.yrel;
        }
        break;
    }
}

```

---
Tags: input, sdl, game-loop, sdl2
---


# Question
Title: What's the best practice for a progress bar in OpenGL ES 2.0?
**My attempt:** I make a texture (could be a single colour or otherwise), and then stretch that texture from a minimum `0` up to a maximum `max` value. This works, but leaves me rather dissatisfied for a number of reasons, one of which being:

* If I want rounded corners as the bar progresses, the edges are squashed or stretched.

**My question:** What is the best practice to achieve a progress bar result.

**Thoughts:** Is there a way to stop openGL from drawing anything from a certain `x` value onwards of a texture? That way I could draw the texture as it should appear, but specify the value of `x`.

I have found this potentially useful link.

**Update**

I get the impression that using the **stencil buffer** might be the way to go. The stencil buffer allows to define any region you like through which other rendered geometry can be clipped. Apparently there are many other uses for the stencil buffer, e.g. reflections.

**Possible Solution**

I ultimately achieved what I wanted using the stencil buffer combined with my own shader, since OpenGL ES 2.0 does not support `glAplhaTest` and related functions. Here's an image of the result:

The texture drawn to the stencil buffer was an elongated rectangle with rounded corners. The texture drawn to the image buffer was just a stretched red rectangle, which as you can see is clipped to the stencil contents. You need to write your own shader to deal with the alpha channel since OpenGL ES 2.0 does not support the `glAplhaTest` and related functions.

Note - perhaps this isn't the best image example. In fact the presented solution allows you to progressively reveal the left and right caps, which I unfortunately didn't demonstrate in the above image.

# Answer
> 0 votes
In the end I just made use of the fact that OpenGL lets you map **any** part of a texture to your vertices. So, suppose you have a texture with three hearts in a row, of width 300 and height 80 say, and you only want to show two-thirds on screen. Then you would map texture (0, 0, 200, 80) to your vertices, but make sure your vertices are also reduced accordingly. Saves messing around with the stencil buffer and is much quicker and elegant. Seems obvious, but back when I thought each sprite had to use a separate texture I couldn't see it !

# Answer
> 3 votes
No need to bring in additional entities, KISS

Just render the progress bar out of three parts - left cap, right cap and the body. Schematic:

```
 {left cap] [body] [right cap}

```

Left and Right caps are usually always the same - half-circles with transparency. The body texture needs to be stretchable without noticeable effects.

Left and Right caps usually get rendered irregardless, and the required percentage is shown with body width. So e.g. 0% could be an empty bar, 1% is caps with body of 0 width.

Further reading for stretching without distortions in both axis: google for "nine-patch button".

# Answer
> 1 votes
There are a few ways to do this.

This is the solution described by poirot:

> I ultimately achieved what I wanted using the stencil buffer combined with my own shader... The texture drawn to the stencil buffer was an elongated rectangle with rounded corners. The texture drawn to the image buffer was just a stretched red rectangle, which as you can see is clipped to the stencil contents.

You could instead use three instances of geometry; one half circle for each end and one rectangle stitched in between. Note how this does not require custom shader or stenciling. (This solution appears to be the same as suggested in comments by wondra.) This solution is my favorite for a number of reasons.

One note about stencil buffer it can be multisampled yielding anti-aliasing for a full frame without application intervention. Alpha testing (shader or not) however is a fragment operation which is not multisampled. If you combine the two stencil buffer never truly multisamples; all samples are treated equally, thus no anti-aliasing.

---
Tags: java, android, opengl-es2
---


# Question
Title: Fade in rendering mode doesn't work as intended
The picture shows an object made out of one model. The object works as intended when rendering with opaque rendering mode, but I want the object to fade in/out during animation. The glitch seems to have something to do with queue of rendering, but since it's only one model, and since there's only one material on the model (tried fresh materials, same problem), it seems to be weird glitch. Any help is appreciated, and if possible, I need to find a solution without using a 3d modelling software.

Forward rendering is used on the camera.

# Answer
Here's a simple fix you can use when rendering a solid object like a building.

We'll copy the building and render it twice in the same location:

1. Drawing only to the depth buffer, without writing any colour over the background
2. Drawing translucently, only where our polygons pass the depth test (ie. only the frontmost faces)

You can use a shader like this to "reserve" this object's surface position in the depth buffer after the other opaque geometry has rendered, while leaving the background as-is:

```
Shader "Unlit/DepthReserve"
{
    Properties
    {
    }
    SubShader
    {
        Tags { "RenderType" = "Opaque" "Queue"="AlphaTest+1" }
        LOD 100

        Blend Zero One

        Pass
        {

        }
    }
}

```

(Here I'm abusing the blending to just ignore our material and output the background colour. There may be a more efficient way to skip computing a colour to blend at all.)

When we render without this depth-reserving pass, the translucent triangles can get drawn in any random order, so stuff that's behind can render in addition to / on top of stuff that's in front - see the internal structure of the windowsills & wells visible on the left below. When we write the depth buffer first, we block all but the frontmost face at a given pixel from rendering, so we get a result like the one on the right, with a more expected translucent layering effect:
> 3 votes

# Answer
You can't do much against this. There's a reason you don't see many transparent objects in games.

The triangles get rendered in a basically random order, so this results in basically random colors.

You can kind of fake it by disabling depth write before rendering the object, but it won't be perfect. If you can get a usable result, then consider youself lucky.

If you need perfect results, then the best thing you can do is disassamble the model into triangles, sort them from back to front based on the camera's position and upload it to the GPU
> 0 votes

---
Tags: unity, rendering, transparency
---


# Question
Title: Animations in Unity are not working properly
I've done a few animations in Blender for my 3D character but the problem is, that they look different in Unity. It seems like the eyes are moving too much. I tried to change many things in import like rig etc. but nothing helped at all. Here are screenshots:

Wrong animation

Good animation

# Answer
I solved that problem by simplifying his head's armature and using .blend file in unity.

By simplifying I meant removing most of head's bones but leaving just one.

Thanks for your help!
> -1 votes

---
Tags: unity, animation, blender, mecanim
---


# Question
Title: Interact with inheriting class methods from "casted" base class (collisions, etc)
I want to implement a damage system that works across both living items (`Entity`) and environment items (`Environment`). The key components of this is that I need to be able to trigger something to take damage from another script, be it a collision with a projectile or a blast radius trigger, etc.

The two approaches I see involve interfaces or inheritance (or maybe a mix). While the inheritance appears necessary to copy the similar code between all items from a base class, it does lead to some issues where only the parent class method is called (defined in collision example). Although interfaces would solve this, I would also wind up duplicating the common code that inheritance helps with.

Obviously this issue is much deeper than a damage system, but it was the best example I could think of that illustrated this problem.

**TL;DR: I want to create a system of classes/interfaces that enable the following:**

> When a projectile collides with an damageable item, it will trigger the "Take Damage" method. This item may be an `Entity` or an `Environment` item. Most items will likely take damage differently, but will share a common (yet extendable) death. Colliding with an `Entity` would trigger the entities subclass method, while colliding with an `Environment` item would trigger the environment item's subclass method.

## Collision (Problem)

This underlying issue (calling specific subclass methods through cast parent class/interface) is most noticeable in the `Projectile` collision script. As noted in the script comments, I understand that since the `Entity` class is what implements the `IDamageable` interface, it is what is returned.

I'm also assuming that if I moved the `IDamageable` interface to each item that inherited from `Entity` it would then be called on the subclasses? But in that case I would have to implement the method separately each time, even if there was duplicate code. At the same time, that would enable some entities to take damage differently than others (ie. if wearing armour, etc)...

```
public void Projectile : MonoBehaviour {
    private float damage = 5f;

    private void OnCollisionEnter(Collision collider) {
        // Check if on layer

        // This properly returns the colliding object, but it currently returns the base
        //   class, "Entity" for example (makes sense).
        IDamageable damageableObject = collider.gameObject.GetComponent<IDamageable>();
        if (damageableObject != null) {
            // Now I totally get why this is calling the "TakeHit" method of "Entity", but I
            //    am searching for a way to call the "TakeHit" of the "Enemy" itself.
            //    Is this only possible by checking the type? If so, isn't that losing the point
            //    of the interface?
            damageableObject.TakeHit(damage, collider);
        }
    }
}

```

## Code

Both entities and environment items can be damageable (ie. entity death or environment destruction), which (to me) requires an interface to make the projectile collision (and other) system easier.

Should the interface be applied to just Entity and Environment, or to each subclass?

```
public interface IDamageable {
    void TakeHit(float damage, Collision collider);

    // Future method that only deals damage (no collision)
    //void TakeDamage(float damage);
}

```

`Entity`s all have health (and some other common attributes), as well as a shared but extendable (through inheritance) death mechanic.

How do I properly handle the relationship between taking damage and dying, if one is an interface and the other an overridable base class method?

```
public class Entity : MonoBehaviour, IDamageable {
    public float Health = 10f;
    public bool IsAlive = true;

    // Implement IDamageable (this is what gets called if using interface, but I want child class method to be called)
    // Unsure if it should be common method, what if children may check for armor,
    //    etc, to reduce damage taken?
    public void TakeHit(float damage, Collision collider) {
        Health -= damage;

        // It's nice having a shared "base" die method, as I don't have to replicate this
        //    in each class that implements the interface (and then not sure where "Die"
        //    method would be either, probably on interface which means more extending)
        if (Health <= 0 && IsAlive) {
              Die();
        }
    }

    // All entities should set IsAlive to false, which is why it is here
    protected virtual void Die() {
         IsAlive = false;

        // Child objects should handle destroying themselves (particle effects, etc).
        //Destroy(gameObject);
    }
}

```

`Enemy`s are basically `Entity` with pathfinding and simple attacks, but also a more customized death.

```
public class Enemy : Entity {
    // Death should play particle effects, sound, and destroy object
    protected override Die() {
        base.Die();

        // Do particle effects and sound
        // Destroy game object
    }
}

```

`Player` is obviously way more complicated than a regular `Entity`, but also has a more customized death.

```
public class Player : Entity {
    // Death should end the game, play sound, and destroy object
    protected override Die() {
        base.Die();

        // Play sound
        // End game
        // Destroy game object
    }
}

```

*Please note, I am struggling with how to represent this best, let me know if it needs clarity in an area.*

# Answer
In Unity, I'd generally recommend working with the principle of composition over inheritance.

In this case, if player characters, enemies, and environment objects all need to take damage, then damage-ability doesn't say much about what the thing *is*, it's a behaviour each of these things *has*. So we can model it as a component attached to GameObjects of all these types.

This component can handle the shared needs of tracking HP and dying, and expose hooks to attach more specialized behaviours. Here I've shown an example using Unity Events, so you can use the Inspector or scripts to wire up a receiver to act on damage or death events, regardless of the type of script it's defined in.

Attached on its own, this will let you create destructible objects, and it can be freely mixed with other components to create more specialized behaviours without duplicating the core HP/death logic.

```
public class Damageable : MonoBehaviour {
    [System.Serializable]
    public class DamageEvent : UnityEvent<float> {}

    public float Health = 10f;
    public bool IsAlive = true;

    public DamageEvent OnDamage;
    public UnityEvent OnDeath;

    public void TakeDamage(float damageAmount) {
        if(!IsAlive)
            return;

        if(OnDamage != null)
            OnDamage.Invoke(damageAmount);

        Health -= damageAmount;
        if(Health <= 0f)
            Die();
    }

    public void Die() {
        if(!IsAlive)
            return;

        Health = 0f;
        IsAlive = false;

        if(OnDeath != null)
           OnDeath.Invoke();

        Destroy(gameObject);
    }
}

```
> 1 votes

---
Tags: unity, c#, interface, inheritance, polymorphism
---


# Question
Title: Spawn chance, modulated by probability weighted by progress
I've been struggling with this for over a day now. What seemed a simple task, has just wrecked me. I hope someone here can help me figure out what I'm missing. Please, please help me :)

---

**The functionality I need:**

Think of my game as Guitar Hero, but instead of pre-placed nodes, I place the nodes randomly as the game progresses, at certain valid points in time. Now, instead of relying on randomness alone, I've made phases of difficulty, where I set a certain number of nodes to be spawned throughout the phase, and I'd like to have those evenly distributed within the phase. Since it's an arcade/highscore game, it needs to be **roughly** the same number of nodes placed every time you play the game, but the nodes should be placed differently each time. Until recently, I simply had something like this code, called for each valid point in time:

```
if(Random.Range(0f, 1f) < 0.25)
    // Spawn node

```

---

**The problem:**

Now I want to balance the number of nodes per phase. To do this, I have these variables:

* TotalNodesToPut
* NodesPut
* NodesLeftToPut
* PhaseProgress (0.0-1.0 normalized percentage of progress)

---

My plan was, to have the base chance of spawning a node to be 50%. I would then like to modulate that down to 0% and up to 100% depending on how many nodes still need to be put down, and how far we have progressed through the phase. It should be so that the percentage of nodes put down follows the progress percentage. If we have spawned 5 of 20 nodes (25%) but have progressed 75% of the phase, the chance to spawn a node should be really high. If we have spawned 15 of 20 nodes (75%) but have only progressed 25% of the phase, the chance to spawn a node should be really low.

It seems like a simple task, but I just can't get it to work :( I've tried dozens of things, started over again and again, and it's just never right, which is why I'm hesitant to show any code. I wouldn't want to start people off on the wrong foot. I have tried searching on the web, but haven't found anything about this particular problem. Any help is much appreciated!

# Answer
> 0 votes
We finally figured it out, and it WAS a super simple problem, which I was over-complicating, and I was missing the fact that I had to account for the difference being above or below 0.

This swings between 0 and 1, and you can set whatever base chance you want, for when pointsPut is the same as estimatedPointsPut.

```
var baseChance = 0.3f;
if (pointsPut <= estimatedPointsPut)
{
    modularChance = 1 - ((float) pointsPut / estimatedPointsPut);
}
else
{
    modularChance = ((float) estimatedPointsPut / pointsPut) - 1f;
}
modularChance *= 1 - baseChance;
modularChance += baseChance;

```

# Answer
> 1 votes
How about this?

```
NodeRate = NodesLeftToPut / TimeLeft;
ChanceToSpawnNode = TimeStep * NodeRate
if (Random.Range(0f, 1f) < ChanceToSpawnNode) { Spawn(); }

```

The NodeRate is the number of nodes per second that you expect to occur, which changes as the timer drops and also when new nodes spawn.

The chance to spawn during a time step is based on the NodeRate and the time delta TimeStep.

I think this fits the approach that you are asking for, but I can see that it will have problems if the spawn rate is too high or too low, but maybe that fits within your game.

Another suggestion which might work... say you have 100 'frames' in the level and during each frame either spawn a node or not. Say you have 20 nodes you want to spawn in the level. Make an array with the first 20 elements to spawn a node, the next 80 elements say don't spawn. Then shuffle the array. During the level, check whether to spawn a node at this time step or not. This might help if you are able to calculate levels ahead of time.

---
Tags: random, progression, probability
---


# Question
Title: Why when rotating the character to the next target it's rotating to the other direction?
Instead rotating and facing the target it's rotating to the other side but moving to the target.

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

public class SoldierPatrol : MonoBehaviour
{
    System.Random rnd = new System.Random();
    public GameObject[] points;
    // assume you have 5 possible points that you can go
    public int moveIndex = 0;
    public float speed = 3;
    public float smoothSpeed = 0.5f;

    void Update()
    {
        Rotate(points[moveIndex]);
        transform.position = Vector3.MoveTowards(transform.position, points[moveIndex].transform.position, speed * Time.deltaTime);
        if (Vector3.Distance(transform.position, points[moveIndex].transform.position) < 1)
        {
            moveIndex = rnd.Next(0, 3);
        }
    }

    private void Rotate(GameObject target)
    {
        transform.rotation = Quaternion.Lerp(transform.rotation, points[moveIndex].transform.rotation, Time.deltaTime * 1);
    }
}

```

# Answer
> 1 votes
I'll try to answer the "Why". In Scene View and using the Move Tool (in local coordinates), try selecting the game object of the target to which your object tries to rotate to. Take note of the direction of the blue arrow which represents it's "forward/facing" axis. Then do the same with your rotating object and you'll see that your rotating object's blue arrow's orientation is lerp'ing towards that of target's blue arrow.

In other words, if the target you're moving to is looking at your moving object (it's blue "forward" arrow is pointing at your moving object) then using `Quaternion.Lerp` will cause your moving object to look away from the target as `Quaternion.Lerp` will eventually make the rotations of each object equal (which in turn result in both forward vectors (blue arrow) point in the same direction).

# Answer
> 0 votes
Solution:

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

public class SoldierPatrol : MonoBehaviour
{
    System.Random rnd = new System.Random();
    public GameObject[] points;
    // assume you have 5 possible points that you can go
    public int moveIndex = 0;
    public float speed = 3;
    public float smoothSpeed = 0.5f;

    void Update()
    {
        Rotate(points[moveIndex]);
        transform.position = Vector3.MoveTowards(transform.position, points[moveIndex].transform.position, speed * Time.deltaTime);
        if (Vector3.Distance(transform.position, points[moveIndex].transform.position) < 1)
        {
            moveIndex = rnd.Next(0, 3);
        }
    }

    private void Rotate(GameObject target)
    {
        var targetPoint = target.transform.position;
        var targetRotation = Quaternion.LookRotation(targetPoint - transform.position, Vector3.up);
        transform.rotation = Quaternion.Slerp(transform.localRotation, targetRotation, Time.deltaTime * 2.0f);
    }
}

```

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


# Question
Title: Why when using Linerenderer it's drawing a line also in scene view?
I want to draw lines using the Linerenderer only in the game view window.

I'm using Debug.DrawLine but only drawing Red lines but for some reason when the Linerenderer draw a line/s one of the Linerender lines is yellow it seems the green linerenderer is getting on the red one in the scene view window.

```
 Debug.DrawLine(Input.mousePosition, hit.transform.position, Color.red);

```

Is there a way to avoid it ? So Debug.DrawLine will draw only in sceneview and the Linerenderer will draw only in the game view window ?

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

public class RotateObjects : MonoBehaviour
{
    public GameObject[] objectsToRotate;
    public float speed = 0.1f;
    public Vector3 spinDirection;
    public bool useMouse = false;
    public bool automaticSpin = false;
    public LineRenderer linerendererPrefab;

    List<LineRenderer> lrs = new List<LineRenderer>();

    // Use this for initialization
    void Start()
    {
        for(int i = 0; i < objectsToRotate.Length; i++)
        {
            var lr = Instantiate(linerendererPrefab);
            lrs.Add(lr);
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (objectsToRotate.Length > 0)
        {
            for (int i = 0; i < objectsToRotate.Length; i++)
            {
                var hits = Physics.RaycastAll(Camera.main.ScreenPointToRay(Input.mousePosition), 100.0f);

            for (int x = 0; x < hits.Length; x++)
            {
                RaycastHit hit = hits[x];

                if (hit.collider.name == objectsToRotate[i].name)
                {
                    objectsToRotate[i].transform.Rotate(1, 1, 1);
                    Debug.DrawLine(Input.mousePosition, hit.transform.position, Color.red);
                    SpawnLineGenerator(Input.mousePosition, hit.transform.position, false);
                }
            }

            if(hits.Length == 0)
                SpawnLineGenerator(new Vector3(0,0,0), new Vector3(0,0,0), true);

            if (useMouse == true)
            {
                if (Input.GetMouseButton(0))
                {
                    Rotate(i);
                }
            }
            else
            {
                Rotate(i);
            }
        }
    }

    private void Rotate(int i)
    {
        if (automaticSpin == true)
        {
            objectsToRotate[i].transform.Rotate(1, 1, 1);
        }
    }

    void SpawnLineGenerator(Vector3 start, Vector3 end, bool reset)
    {
        for(int i = 0; i < lrs.Count; i++)
        {
            if (reset)
            {
                lrs[i].SetPosition(0, start);
                lrs[i].SetPosition(1, end);
            }
            else
            {
                lrs[i].SetPosition(0, start);
                lrs[i].SetPosition(1, end);
            }
        }
    }
}

```

# Answer
Debug.DrawLine() will only work in Editor mode when Gizmos are activated. this feature won't work in a build.

The LineRenderer component is drawn on runtime, so it works in both editor playmode and in the builds. So you can rest, your debug.drawlines won't show up in your executable.

Now, if you want to just use lines for debugging purposes in build mode, you can use openGL methods. here is a snippet to draw lines with GL.

```
/// <summary>
    ///  Renders a Line using OpenGL
    /// GL.Vertex3 are followed up, if we declare 4 vertices it will draw two lines, one between A and B and one between C and D
    /// </summary>
    /// <param name="mat"></param>
    /// <param name="startPos"></param>
    /// <param name="endPos"></param>
    /// <param name="color"></param>
    public static void OnLineRender(Material mat, Vector3 startPos, Vector3 endPos, Color color)
    {
        GL.PushMatrix();
        GL.LoadProjectionMatrix(Camera.main.projectionMatrix);
        GL.modelview = Camera.main.worldToCameraMatrix;

        mat.SetPass(0);

        GL.Begin(GL.LINES);
        GL.Color(color);
        GL.Vertex3(startPos.x, startPos.y, startPos.z);
        GL.Vertex3(endPos.x, endPos.y, endPos.z);
        GL.End();

        GL.PopMatrix();
    }

```

Ensure to call this methods from an OnPostRender() method in a script attached to your mainCamera. or if you use the new ScriptableRenderPipeline, you will have to call it this way:

```
private void InitGL()
    {
        // Creates a Material
        _lineMat = new Material(Shader.Find("Hidden/Internal-Colored"));
        _lineMat.hideFlags = HideFlags.None;
        // Turn on alpha blending
        _lineMat.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
        _lineMat.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
        // Turn backface culling off
        _lineMat.SetInt("_Cull", (int)UnityEngine.Rendering.CullMode.Off);
        // Turn off depth writes
        _lineMat.SetInt("_ZWrite", 1);
        RenderPipeline.BeginCameraRendering(Camera.main);
        RenderPipeline.beginCameraRendering += OnPostRender;
    }

    public void OnPostRender(Camera cam)
    {
        // do Stuff Here
        OnLineRender(_lineMat, start, end, Color.red)
    }

```
> 2 votes

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


# Question
Title: How can I convert Physics2D.Raycast to Physics2D.BoxCast to yield the same results?
*This question has been updated to better reflect my current issue, and some of the progress made while solving it.*

I've been working on a 2D character controller that uses raycasting to detect collisions with objects. Since `Physics2D.Raycast` and `Physics2D.BoxCast` both return a `RaycastHit2D` object, I was hoping to convert my raycast detection to boxcast detection, but I've been having trouble understanding how to do it. Unity's scripting API is a little vague on how `BoxCast` actually works; specifically, I don't understand the difference in use between the `size` and `distance` parameters.

My current method works like this:

* I get the `bounds` of my box collider, and fire a raycast with an origin point.y of `skinWidth` *inside* the collider (this ensures that collisions can still be detected when the character is flat on the ground). `skinWidth` is a very small number (like `.015f`) used to achieve this result.
* If I'm moving down, the raycast is fired from the bottom center (center.x, min.y) of my collider, otherwise it's fired from the top center.
* The length of the raycast this frame is determined by `deltaMovement.y + skinWidth`, which is a reference to my character's `velocity`, but represents the change in movement this frame; this is also a small number. `skinWidth` is added back to this value to compensate for the ray beginning inside the box.
* If the raycast hits the ground, `deltaMovement` is updated to be equal to the `(hit.distance - skinWidth) * velocityDir`. This means our character will move another `hit.distance - skinWidth` more before colliding with an object. `skinWidth` is subtracted because I added it to the ray's length, and I multiply by `velocityDir` to maintain my direction because `hit.distance` is always a positive value, even when moving down.

Here's what this looks like in code (this works exactly as I'd like):

```
private void CollideVertically(ref Vector2 deltaMovement)
{
    float velocityDir = Mathf.Sign(deltaMovement.y);
    float raycastLength = Mathf.Abs(deltaMovement.y) + skinWidth;
    Vector2 origin = (velocityDir == -1) ? bottomCenter : topCenter;

    //this makes the raycast move with the character on the x axis
    origin.x += deltaMovement.x

    RaycastHit2D hit = Physics2D.Raycast(origin, Vector2.up * velocityDir, raycastLength, verticalCollisionMask);

    if (hit)
    {
        deltaMovement.y = (hit.distance - skinWidth) * velocityDir;
        State.IsCollidingAbove = velocityDir == 1;
        State.IsCollidingBelow = velocityDir == -1;
    }
}

```

I thought adapting this to work with boxcasts would be easy; after all, `Physics2D.BoxCast` has many of the same parameters. I ran into some issues, though, but here's my code:

```
private void CollideVertically(ref Vector2 deltaMovement)
{
    float velocityDir = Mathf.Sign(deltaMovement.y);
    float raycastLength = Mathf.Abs(deltaMovement.y) + skinWidth;
    Vector2 origin = (velocityDir == -1) ? bottomCenter : topCenter;
    origin.x += deltaMovement.x;
    Vector2 size = new Vector2(boxCollider.size.x, .02f);

    RaycastHit2D hit = Physics2D.BoxCast(origin, size, 0, Vector2.up * directionY, raycastLength, verticalCollisionMask);

    if (hit)
    {
        deltaMovement.y = hit.distance * velocityDir;
        State.IsCollidingBelow = velocityDir == -1;
        State.IsCollidingAbove = velocityDir == 1;
    }
}

```

One of the issues with this is simply how my character "feels" when using this method vs my raycast method. The movement doesn't feel quite as tight. Similarly, I have to use the arbitrary value of `.02f` as the box's size.y in order to make my character be flat on the ground. I've tried other values like `skinWidth`, or something like `.03f`, but these put my collider slightly in the ground or above it. I had initially used `raycastLength` as both the box's size.y and the `distance` parameter of the boxcast method, but this was inconsistent, and I think it produced "too much" of a box when casting (I was frequently colliding when my character was still airborne).

I also don't understand why I *don't* have to take away `skinWidth` in the line `deltaMovement.y = hit.distance * velocityDir`. I had been subtracting it, but this was producing a lot of bouncing; the movement wasn't right at all.

Ultimately, this related question helps explain why I want to use boxcasting. Instead of using many rays, each of which has a gap between it and the next ray, I'd like to use a boxcast to simulate a solid "sheet" of rays that can determine my collisions. Imagine a scenario in which the character is on the peak of a mountain; raycasts (with the aforementioned gaps) might miss this sharp point, but a boxcast will hit it, and that hit point will determine the character's movement.

Here's a little visualization I made about the two approaches: https://i.stack.imgur.com/GYZS3.jpg Am I thinking about this correctly? Should I be using `Physics2D.OverlapBox` instead?

# Answer
> 2 votes
I would very highly recommend that you visualise (using Debug.Draw... methods) your collision hit points/contacts and normals to better understand what's going on - actually, I'd say output all the info that RaycastHit2D gives you after a BoxCast2D. The main catch with BoxCast2D is that the hit point won't necessarily be "on the edge" of your collider (as it's the case with Raycast2D) - it can very likely be inside of your collider. Here's an image of how your BoxCast2D might behave:

If what you're trying to achieve is a precise "push out of collision" behaviour, you'll need to use BoxCast2D in tandem with Physics2D.Distance.

1) You BoxCast2D in the direction of movement.

2) Move your BoxCollider2D to the position where BoxCast2D collision happened (hit.centroid is where the box of a BoxCast2D was positioned when the hit happened).

3) Use Physics2D.Distance to find out how much you should push out your BoxCollider2D out of collision.

# Answer
> 2 votes
I think it's useful to visualize the physics 'Cast' operations as an object being thrown in a straight line and stopping when it hits another object (collider).

**Size** is the size of the box being "thrown".

**Distance** is how long that box is "thrown" in said direction.

---

When dealing with game physics an approach generally taken is to update positions, then calculate collisions and correct overlaps. This is done because it's very robust and easy. Trying to prevent overlaps before they happen (which it seems like you are trying to) is much harder and more prone to errors.

Translating that to your example that would mean:

1. Add user input to velocity
2. Add gravity to velocity
3. Move by `velocity*Time.deltaTime` (velocity is movement divided by time, so by multiplying with time you get movement)
4. Detect collisions and fix overlap

Your code would be the part slotted into nr 4 in that list.

## Here's what I'd suggest:

## 2 & 3.

```
//in Update/FixedUpdate in controller script (use fixedDeltaTime if in FixedUpdate)
velocity += gravity*Time.deltaTime; //Gravity is an acceleration
transform.Translate(velocity*Time.deltaTime);

```

## 4.

```
void CollideVertically(){
    float velocityDir = Mathf.Sign(velocity.y);
    Vector2 size = new Vector2(boxCollider.size.x, boxCollider.size.y*0.1f);
    float rayLength = boxCollider.size.y/2 - boxCollider.size.y*0.1f/2; //Subtract how much the box being cast overshoots length
    RaycastHit2D hit = Physics2D.BoxCast(transform.position, size, 0, Vector2.up*velocityDir, rayLength);
    if (hit){
        velocity.y = 0;
        var overlap = transform.position.y + boxCollider.size.y/2 * velocityDir - hit.point.y;
        transform.Translate(new Vector3(0, -overlap, 0));
    }
}

```

You'll need a CollideHorizontally as well, which needs to execute before the vertical one to ensure that you can't climb up walls. But that should be identical to the vertical one, only with reversed X and Y.

As for the input movement (step 1), that will vary wildly from game to game, so that's entirely up to you.

Hope that helps :)

# Answer
> 0 votes
Unity has collision detection and collison resolution built in. If you want to know what collider your character is standing on, use OnCollisionEnter. No need to reinvent the wheel using raycasts.

If you want to know about colliders nearby, i.e. colliders a fixed distance away from your character but not yet touching it, use a trigger volume and OnTriggerEnter.

However, if for some reason you really need to know about colliders a dynamic distance away from your character, e.g. for predicting future collisions, a box cast comes in handy. Note the difference between Physics.BoxCast and Physics.OverlapBox though, a box cast moves the box along a line.

The reason why your code is not working is because you need to offset the origin of the cast by the half-extents of the box so that the entire box starts within your character bounds. If you start the cast near the bottom of your character bounds then half of the box already overlaps with the outside world.

# Answer
> 0 votes
So after trying some more things today, I've got this working about as well as I think I can. Here's the boxcast method:

```
private void CollideVertically(ref Vector2 deltaMovement)
{
    float velocityDir = Mathf.Sign(deltaMovement.y);
    float raycastLength = Mathf.Abs(deltaMovement.y);
    Vector2 origin = (velocityDir == -1) ? bottomCenter : topCenter;
    origin.x += deltaMovement.x;
    Vector2 size = new Vector2(boxCollider.size.x - skinWidth * 2, 2 * skinWidth);

    RaycastHit2D hit = Physics2D.BoxCast(origin, size, 0, Vector2.up * directionY, raycastLength, verticalCollisionMask);

    if (hit)
    {
        deltaMovement.y = hit.distance * velocityDir;
        State.IsCollidingBelow = velocityDir == -1;
        State.IsCollidingAbove = velocityDir == 1;
    }
}

```

The relatively simple changes that I made were to:

1. Remove the addition of `skinWidth` to `raycastLength`
2. Make the size.y of the boxcast `2 * skinWidth`
3. Remove the subtraction of `skinWidth` from `deltaMovement.y`
4. Subtract `2 * skinWidth` from the boxcast's size.x (not important for the issues in this question, but prevents clipping on walls/corners)

The reason points 1 and 2 are important is because the size.y of the boxcast makes up for the `skinWidth` needed in the raycast method. In the raycast method I was adding `skinWidth` to `raycastLength` so that the length would always reach outside of my collider (remember that the rays start from *inside* the collider). By removing this in the boxcast method, and making the boxcast have a size.y of `skinWidth * 2`, the bottom half of the boxcast acts as the "made up" length that I was using in the raycast method. In addition, since I'm no longer adding it to `raycastLength`, `skinWidth` does not need to be removed from `deltaMovement.y = hit.distance * velocityDir`.

With that being said, this method still doesn't produce a completely accurate collision when compared to the raycast method. For example, my position is still off by `.005f` using a boxcast, and my character is still ever so slightly landing off the floor (you have to zoom is quite far in the scene view to see this, but there is no visible gap using raycasts). While this is still very accurate, I'm wondering if this discrepancy would cause collision issues once more (complex) functionality is added to the controller.

@Karl Ramstedt presented an alternative in which collisions are resolved *after* moving the character, and this might be a better/more reliable approach. I would still appreciate some feedback if anybody has anything else to contribute.

---
Tags: unity, c#, collision-detection, raycasting
---


# Question
Title: LIBGDX fadeout, hide and remove action not triggered
I try to execute an sequence of actions, but fadeout and following are not working for me. I can see the actor moving to the desired point, but after that it just stays there.

My code. personActor is an Actor of a list in my mainactor:

```
    SequenceAction sequence = new SequenceAction();
    sequence.addAction(Actions.moveTo(0, 300));
    sequence.addAction(Actions.moveTo(1000, 300,3f));
    sequence.addAction(Actions.fadeOut(0.5f));
    sequence.addAction(Actions.hide());
    sequence.addAction(Actions.removeActor());

    personActor.addAction(sequence);

```

The main actor loops through the list of childactors:

```
@Override
public void draw(Batch batch, float parentAlpha) {
    super.draw(batch, parentAlpha);
    for(PersonActor personActor : personenActors){
        personActor.draw(batch,parentAlpha);
    }
}

```

Do someone see, whats wrong here ?

# Answer
I solved this. My Person actor has Sprites drawn in the draw() method of the Actor.

I just had to set the color of the Textures in draw() to the Actors color:

```
public void draw(Batch batch, float parentAlpha) {
    texture.setColor(getColor)

```
> 0 votes

---
Tags: libgdx
---


# Question
Title: How can I make that also the yradius values will change when the flag is true?
In this part when I'm changing the xradius slider it's also changing the yradius slider at the same time and same value. But I can't change the yradius when trying to change it's slider. I want to be able either change the xradius or yradius when the flag is true. Both will change to the same values but I want to be able to change also the yradius so it will change the xradius.

```
if (changeBothRadius)
        {
            yradius = xradius;
            xradius = yradius;
        }

```

I tried to add the `xradius = yradius;` but it's not working only when changing the xraiuds it's working.

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

[RequireComponent(typeof(LineRenderer))]
public class DrawCircle : MonoBehaviour
{
    [Range(0, 50)]
    public int segments = 50;
    [Range(1, 50)]
    public float xradius = 5;
    [Range(1, 50)]
    public float yradius = 5;
    public bool changeBothRadius = false;
    [Range(0.1f, 2)]
    public float lineThickness = 0.1f;
    public bool minimumRadius = false;

    private LineRenderer line;
    private List<float> radiusList = new List<float>();

    void Start()
    {
        line = gameObject.GetComponent<LineRenderer>();
        line.positionCount = segments + 1;
        line.useWorldSpace = false;
        CreatePoints();
    }

    void Update()
    {
        line.startWidth = lineThickness;
        line.endWidth = lineThickness;
        CreatePoints();
    }

    void CreatePoints()
    {
        if (changeBothRadius)
        {
            yradius = xradius;
            xradius = yradius;
        }

        float x;
        float z;

        float angle = 20;

        for (int i = 0; i < (segments + 1); i++)
        {
            x = Mathf.Sin(Mathf.Deg2Rad * angle) * xradius;
            z = Mathf.Cos(Mathf.Deg2Rad * angle) * yradius;

            line.SetPosition(i, new Vector3(x, 0, z));

            angle += (360f / segments + 1);
        }
    }
}

```

# Answer
> 1 votes
Remember, code is just a set of instructions that the computer follows literally. It doesn't read ahead to try to infer your intention.

So let's say `xradius = 5` and `yradius = 5` and you change the `yradius` slider to `7`. The first command the CPU gets to is:

```
yradius = xradius;

```

So it dutifully follows this instruction, and undoes the change you made with the slider, setting `yradius` to `5`, since that's the value of `xradius`. Only after it's done that does it reach this line:

```
xradius = yradius;

```

...which is now completely redundant because both variables already have the same value of `5`.

In order to react the way you expect to *either* radius changing, it needs to have some memory of what the old values were, so it knows which one changed and can apply that one's value to the unchanged one.

If you're just changing these values in the inspector, then resetting the points every frame in `Update()` is a bit wasteful, and we can do it in `OnValidate()` instead to react only when an inspector value has changed in a way that might force us to re-generate our points:

```
Vector2 _cachedRadii;
Vector3[] _points;

void OnValidate() {
    if(line == null)
        line = GetComponent<LineRenderer>();

    line.startWidth = lineThickness;
    line.endWidth = lineThickness;

    bool regenPoints = false;

    if(_points == null || _points.Length != segments + 1) {
        _points = new Vector3[segments + 1];
        regenPoints = true;
    }

    if(xradius != _cachedRadii.x) {
        regenPoints = true;
        if(changeBothRadius)
           yradius = xradius;
    }
    if(yradius != _cachedRadii.y) {
        regenPoints = true;
        if(changeBothRadius)
           yradius = xradius;
    }

    if(regenPoints)
        CreatePoints();
}

void CreatePoints()
{
    float angle = 20;

    for (int i = 0; i < (segments + 1); i++)
    {
        float x = Mathf.Sin(Mathf.Deg2Rad * angle) * xradius;
        float z = Mathf.Cos(Mathf.Deg2Rad * angle) * yradius;

        _points[i] = new Vector3(x, 0, z);

        angle += (360f / segments + 1);
    }

    if(line.positionCount != _points.Length)
        line.positionCount = _points.Length;
    line.SetPositions(_points);

    // Remember the last radii we used to generate points.
    _cachedRadii.x = xradius;
    _cachedRadii.y = yradius;
}

```

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


title: How to play and pause animation

text:
# Question
Title: How to play and pause animation
I want to make play and pause buttons to play and pause sound and also I want it to play and pause animation ,how should I do that?

```
//function
 public void TogglePlay()
    {
        if (audio.isPlaying)
        {
            audio.Pause();
        }
        else
        {
            audio.Play();
        }
    }

```

# Answer
Animator has a speed property. If you set it to 0, it will stop playing. Then set it back to 1 to resume playback.

```
public void TogglePlay()
{
    if (audio.isPlaying)
    {
        audio.Pause();
        animator.speed = 0;
    }
    else
    {
        audio.Play() ;
        animator.speed = 1;
    }
}

```
> 2 votes

# Answer
I would use an AudioSource, because this can change between multiple AudioClip, which is a specific sound, so you can play multiple sounds.

You'll have to attach all needed components in editor before this.

1. An AudioSource component to your AudioSource field and drag the AudioClip into that AudioSource Component.
2. A Button component on the btnMusic field.
3. An Animator on the animator field and create an animation in the Animator tab in the editor.

Then in your GameManager you can do something like this:

```
public AudioSource audioSource;
public Animator animator;
public Button btnMusic;

void Start()
{
    audioSource.Play("name-of-your-audio-clip");
    btnMusic.onClick.AddListener(BtnMusicOnClick);
}

void BtnMusicOnClick(){
    if (audioSource.isPlaying) {
        audioSource.Pause();
    } else {
        audioSource.UnPause();
    }
    animator.Play("btnMusicOnClick");
}

```
> 0 votes

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


# Question
Title: Super-quick MIDI generator with nonrestrictive license?
I'm working on my Ludum Dare entry and trying to figure out how in the world I'm ever going to get background music. I found WolframTones, but the license is too restrictive:

> Unless otherwise specified, this Site and content presented on this Site are for your personal and noncommercial use. You may not modify, copy, distribute, transmit, display, perform, reproduce, publish, license, create derivative works from, transfer, or sell any information or content obtained from this Site. For commercial and other uses, contact us.

But I really like the interface! It's a lot like sfxr \- click a genre and download a song. That's so cool. Is there another program that does this same sort of thing but without a restrictive license, so that I can generate a bgm and use it in my game?

# Answer
> 1 votes
A ancient one exist, called "Melody Raiser"

unfortunately I have no idea of where to find it (my copy is fan translated to portuguese, and probably pirated... I have no idea what was the license of the original software, I never found it... also probably the original software is japanese).

But if I remember well, it was quite popular in RPG Maker communities.

Also, its music is not the best one around... It is easy to tweak it though...

# Answer
> 2 votes
For tools that generate random music for games, this ludum dare post provides a comprehensive list with good options. My personal favorites on that list are autotracker.py and CGMusic. Autotracker produces great music for retro/8-bit style games, though it lacks a proper user interface. CGMusic has a good UI, good customization, and creates complex piano songs.

I also know of 2 free music creation tools that allow you to manually create your own songs. Pxtone and musagi both are good for anyone familiar with music theory or experienced with making music. Be aware that since pxtone is a japanese program, it will need to be downloaded from a google-translated website and then set to English mode (which is easy to do).

# Answer
> 0 votes
WolframTones output is easy to modify to the point of unrecognizability, at which point even the best attorneys would experience some difficulty in collecting royalties. I see nothing in there about "derivative works".

Also, google "generative music" and "algorithmic composition".

# Answer
> 0 votes
Try this https://raw.github.com/wibblymat/ld24/master/autotracker.py A short python script that uses MIDI to generate some random music and save to a file.

# Answer
> 0 votes
There was a software called Band in a box; which was doing mostly what you ask.

You could set parameters, and it would generate a correctly balanced melody.

While this works fine from the algorithmic perspective, and it does sound right, due to the musical rules; they are mostly boring and lack of any sort of brilliance. Usable as BGM probably; but mostly they were used to give inspiration and build on top of it, creating something very unique.

If you have time, I would suggest to spend some time with loops; can't get easier than that, but you make something out of your liking, instead than randomly get a melody, until you like one.

# Answer
> 0 votes
DryWetMIDI is a .NET library I created which has features to build musical compositions based on MIDI (see Pattern page of the library Wiki), so you can use it to program music in any way you desire.

For example, to generate the MIDI file with following properties:

* all MIDI notes;
* each note lasts 1 second;
* there is a pause with length of 1/8 after each note;
* tempo is 105 BPM;
* 'Church Organ' instrument of General MIDI is used;

you can write this code:

```
var patternBuilder = new PatternBuilder()
    .SetNoteLength(new MetricTimeSpan(0, 0, 1))
    .SetProgram(GeneralMidiProgram.ChurchOrgan);

for (var noteNumber = 0; noteNumber <= SevenBitNumber.MaxValue; noteNumber++)
{
    patternBuilder
        .Note(Melanchall.DryWetMidi.MusicTheory.Note.Get((SevenBitNumber)noteNumber))
        .StepForward(MusicalTimeSpan.Eighth);
}

var tempoMap = TempoMap.Create(Tempo.FromBeatsPerMinute(105));
var pattern = patternBuilder.Build();
var midiFile = pattern.ToFile(tempoMap);
midiFile.Write("Generated music.mid", overwriteFile: true);

```

---
Tags: music
---


# Question
Title: Individual Skeletal Animation with OpenGL
I have been able to implement a pipeline in OpenGL which reads Collada files and can animate them through interpolating the keyframes. However, as somebody brand new to graphics, I don't quite know how one would go about doing individual joint animation.

For example, if I have a sprite and I would like to move just their arm joint, none of that animation information is stored in a Collada file. How would I go about making a system that can move each joint independently?

# Answer
Lets say that you have two animation files: `anim_run.dae` and `anum_aim.dae`. The former holds a running animation and the latter holds an aiming animation where the skeleton has one of it's arms raised (as if it is aiming a gun). The two animations belong to a specific character. That character can run, aim, and aim while running. Combining the running animation and the aiming animation to create the third one is actually very simple. Allow me to explain:

Say that you have an skeleton whose bone structure looks like this:

In the run animation you are using all the bones of the skeleton to make the character run. In the aim animation, the only part of the skeleton that is animated is the right arm (i.e. `r_arm0` and `r_amr1`). At this point I should clarify that the same skeleton is used in both animations.

In order to create the 'run while aiming' animation you could use the run animation as a basis, and mark which bones need to be animated using the aim animation instead of the running animation. In the example above you would have to mark the `r_arm0` and `r_amr1` bones in order to achieve this.

This system is simple but has a very important catch: You need to be careful with the way you apply transformations to the bones that have the aiming animation. If you just use the transformations that are given in the collada file, then the resulting animation will look weird. The arm will be stationary and aiming while the rest of the body will be moving, and thus the arm will appear to be 'flying'. This obviously ruins the animation and looks terrible. You will have to apply some kind of transformation to the `r_arm0` bone in order to make it follow the movement of the body. (since this transformation is applied to `r_arm0` it will also be applied to all of its children, which in this can is `r_arm1`).

You can make this even more advanced by adding an 'alpha' value to each bone. The 'alpha' value is simply a number between 0.0 and 1.0 that can be used to blend the two animations together. For example, if `r_arm0` has a alpha value of 0.0 only the running animation will be applied to it, when its alpha value is 1.0 only the aiming animation will be applied to it, and when its alpha value is 0.5 both animations will be applied.
> 2 votes

---
Tags: opengl, skeletal-animation
---