#archived-code-general

1 messages · Page 230 of 1

hazy marten
#

Yeah, there could be a few problems. Your transform position could be under the ground, your raycast might not be tall enough to hit the ground, your layermask might not include the ground layer. Also it should still work regardless, but physics functions should be called in FixedUpdate instead of Update.

#

You can use Debug.DrawLine and Debug.DrawRay to visualize raycasts to help debug them.

obtuse cape
#

Ah I fixed it

#

The raycsst was not long enough

hazy marten
#

Glad you solved it 🙂

obtuse cape
#

Thanks for ur help! Legend

#

I have a problem though. When holding the spacebar, the player is able to still jump in thr air

#

How could I fix this?

#

Nvm

safe dock
#

i was making a pickup and drop system but when i put the game on, the gun just goes in a random place, locks in, and rotates with the camera, i drop it and pick it back up, then it starts raising while im spinning the camera around, is there something i can show for help?

#

i need so much help im so confused

short osprey
#
private IEnumerator PerformDash()
    {
        isDashing = true;
        dashesRemaining--;
        Vector2 dashDirection = new Vector2(Math.Sign(inputHorizontal), Math.Sign(inputVertical)).normalized;


        if (dashDirection == Vector2.zero)
        {
            dashDirection = new Vector2(transform.localScale.x, 0).normalized;
        }

        Debug.Log(dashDirection.x + " | " + dashDirection.y);

        Vector2 targetPosition = (Vector2)transform.position + dashDirection * playerData.DashLength;

        float elapsedTime = 0f;

        while (elapsedTime < playerData.DashTime)
        {
            rb.MovePosition(Vector2.Lerp(transform.position, targetPosition, elapsedTime / playerData.DashTime));
            elapsedTime += Time.deltaTime;
            yield return null;
        }
        isDashing = false;
    }

i wrote this coroutine to dash the player character in one of 8 directions (Left Up Down Right, and 4 in betweens)
it works, except for the fact that after arriving to targetPosition you stay suspended and unable to move for a little while before it ends, and i cant figure out why for the life of me....

#

even gravity doesnt affect me

cosmic rain
#

Instead of using transform.position as a first parameter, cache the original position and use that instead.

short osprey
frail parcel
#

Trying to animate my player character running when input is detected and when it stops moving, but it never goes back to ide, here is the code, what am I doing wrong here? I checked the triggers too, they should be spelled correctly

rigid island
frail parcel
#

Uhhh I cannot see the screenshot is a little small

#

Ok thanks for being cryptic, I would like to learn why I messed up

#

I can see the little mark over the equals sign so I guess I will mess around with that, so thank you, I guess lol

spring creek
# frail parcel

Wait. I'm a bit confused. You're checking if the players distance from origin is less than .01, then you set it to Idle? Is this a game where you stay near origin and it moves you just outwards a little to simulate movement?
Just so we understand better

frail parcel
#

Honestly it's a student project so I'm trying to set up the animation and stuff. I have not made this movement script so I cannot fully say what it's doing. From my understanding and so there's more context here is this part of the scripts as well

#

We have the player look towards the mouse position and then all those vector locations the camera is facing then adding them to the players transform when they input times the speed since we have different speed types

#

That's how I understand it at least. Though I'm sure I'm not seeing the full picture

rain minnow
tawny elkBOT
frail parcel
#

Ahh I see thank you

#

Here is the code block

#

Sorry for the inconvenience

spring creek
#

I would put a couple Debug.Logs in there to see the value of move

hard viper
#

some debug.Assert never hurts

#

assert statements are like butter. even if it looks sickenning, you can’t have too much

swift falcon
#

Hey all!

#

Loup&Snoop oh yeah you're the one I talked to

#

So I was just testing some stuff in my game

#

I was using the terraria sprite as a filler, such and such

#

I am using transform.rotateAround to rotate this butter ball around the player

#

However when he moves, I use a flip function to flip him

#

But I don't want the ball's position to flip so I can't child it

#

When I move the player however, then it causes the ball to move further away from the player and still orbit

#

How do I maintain this ball's distance from the player without parenting it? I tried using transform constraints and that did not work either

#

this.transform.RotateAround(player.position, Vector3.forward, 200 * Time.deltaTime);

cosmic rain
#

What exactly are you doing in your "flip function"?

spring creek
swift falcon
#

I'm actually flipping it using transform

#

*= -1

cosmic rain
#

Yeah, that would affect all it's children.

swift falcon
#

Yeah

cosmic rain
#

Another way is to separate the controller from the visuals. Then you can do whatever you want with the visuals transform, while the orb would be parented to the controller.

spring creek
swift falcon
#

Sorry I don't know this stuff

#

Because I don't have kids

waxen burrow
#

Howdy, while making a combat system I ran into some funny type stuff that I dont really know how to put into words but basically:


public void someMethod(){
  if(itemInstance is MeleeWeapon && (Weapon)itemInstance.AttackTriggered){}

Where Item is the parent of Weapon (which contains the AttackTriggered bool) and Weapon is the parent of MeleeWeapon
I have done something similar before without issue but unsure why I am unable to cast itemInstance as a MeeleWeapon after checking that it is a Weapon

rigid island
waxen burrow
#

I get what you are pointing out however

hexed pecan
#

Does MeleeWeapon inherit from Weapon?

swift falcon
#

I'm back

#

So I have another question

#

Earlier I was making a ball revolve around the player

hexed pecan
#

if(itemInstance is MeleeWeapon meleeWpn && meleeWpn.AttackTriggered)

swift falcon
#

My idea is to revolve the ball a lot

#

And once it reaches a threshold, rotate it towards mouse pointer

#

And then shoot it

#

At that angle

#

My issue is, I've gotten mouse angle and everything

#

But when I apply:

        rb.AddForce(transform.forward * 5000, ForceMode2D.Impulse);
#

The ball just falls

#

It doesn't go at the angle I have rotated to

lean sail
waxen burrow
#

tyty

swift falcon
#

Is it due to the fact that I'm only just setting the rb to kinematic before I launch it?

#

If my code was to work, it should launch this rb at the angle I've set its rotation to, right? However the ball just drops down.

#

In the inspector, I can see that the z-angle is being set correctly

hexed pecan
#

It's 2D, you probably want transform.up/right instead of forward

#

Forward in 2D is the direction the camera is facing

swift falcon
#

Sorry this does not fix it

#

And what happens, it does not work.

swift falcon
swift falcon
swift falcon
#

Anyone?

#

I'm still stuck :(

vivid heart
#

Please give me an idea of what scripts and interfaces I would need if I had to create a money management system in the sense that - there are different characters who have certain qualities as well as money, there is a certain service that deals with transferring money from the character to the hero following certain conditions or events. Please guide me in this direction from an architectural standpoint.

lean sail
#

the script that manages money basically needs to store a float and have a way to subtract from itself and give to someone else. Then other scripts would be storing the conditions and events that you describe, all they need to do is have a reference to your money manager script and know who to give it to when the condition is fulfilled

round violet
#

Hello,
Is there a way to update the duration of a "wait for seconds" after it was entered ?

example:

some code >> starts wait for seconds (duration = 3)
some other code >> add 5 for duration to whatever is left to wait for seconds

could this work using a var ? Does the wait for seconds checks how muc his left eac htime

round violet
main shuttle
#

Yeah, I would WaitUntil your timer expires. Afaik you can't do what your saying.

round violet
#

ok ty

swift falcon
#

I'm still stuck

plucky inlet
#

Not sure where to put this. I am using the Vuplex.Webview plugin to show websites. Unfortunately, the plugin takes the chromium OS language instead of the URL it gets passed in. So if I pass in a german or english website, it always defaults to the english one inside Unity. Anyone in here with experience in that plugin and how to probably ignore the setting or override it? The documentation talks about command line tools, but they do not seem to have any effect.

round violet
plucky inlet
round violet
#

There is currently no async support in Visual Scripting so i guess ill do somehting else

swift falcon
#

Dude can someone help me please

#

I can not figure it out

#

And have trialled and errored

#

For a full day

plucky inlet
plucky inlet
#

from the video there seems to be something wrong with the whole position calculation. I would comment out line by line and see, what happens when I turn on one thing after the other.

swift falcon
#

When I do that

#

It becomes apparent that the issue is with the rigidbody not the angle

#

Since when I do a rotation test with mouse, it works well.

plucky inlet
#

And did you check the suggestion about transform.forward?

swift falcon
#

Yes

#

That's what I did in the video

#

I showed that it's the same for each transform method

plucky inlet
#

Ah , got it. I will have a look at this later more closely, if its still an issue then. Gotta go, so sorry for the quick jump in and out

swift falcon
#

Sure thank you

main shuttle
main shuttle
round violet
round violet
#

i'll try ty

gleaming burrow
#

Heyy, I have a really weird problem when I go to build my project. I have a buoyancy system set up that adds force to a list of transforms based on how far under the water they are. In the unity inspector, it's working fine, but once i build the project it stops working altogether, if anyone had any clues or tips on how I could potentially troubleshoot it further anything is appreciated, im very lost.

#

This is the code for the system. Its pretty much-written word for word from this tutorial. https://www.youtube.com/watch?v=iasDPyC0QOg

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

[RequireComponent(typeof(Rigidbody))]

public class BuoyancyObject : MonoBehaviour
{
    [SerializeField] Transform[] floaters;
    [SerializeField] float underWaterDrag = 3f;
    [SerializeField] float underWaterAngularDrag = 1f;
    [SerializeField] float airDrag = 0f;
    [SerializeField] float airAngularDrag = 0.05f;
    [SerializeField] float floatingPower = 15f;
    [SerializeField] TextMeshProUGUI Text;

    [SerializeField] WaterMannager waterManager;

    Rigidbody m_Rigidbody;

    bool underwater;

    int floatersUnderWater;

    // Start is called before the first frame update
    void Start()
    {
        m_Rigidbody = GetComponent<Rigidbody>();
        
    }

    // Update is called once per frame
    private void FixedUpdate()
    {
        if (m_Rigidbody == null)
        {
            Text.text = "NOT WORKING HERE";
        }
        

        floatersUnderWater = 0;
        for(int i = 0; i < floaters.Length; i ++)
        {
            float difference = floaters[i].position.y - waterManager.WaterHightAtPosition(floaters[i].position);

            if (difference < 0)
            {
                m_Rigidbody.AddForceAtPosition(Vector3.up * floatingPower * Mathf.Abs(difference), floaters[i].position, ForceMode.Force);
                floatersUnderWater += 1;
                if (!underwater)
                {
                    underwater = true;
                    SwitchState(true);
                }
            }
        }

        
        if (underwater && floatersUnderWater == 0)
        {
            underwater = false;
            SwitchState(false);
        }
    }

    void SwitchState(bool isUnderwater)
    {
        if (isUnderwater)
        {
            m_Rigidbody.drag = underWaterDrag;
            m_Rigidbody.angularDrag = underWaterDrag;
        }
        else
        {
            m_Rigidbody.drag = airDrag;
            m_Rigidbody.angularDrag = airDrag;
        }
    }
}

Follow me on Twitter : https://twitter.com/ABeginnersDevB1
Support me : https://www.buymeacoffee.com/VincentA
Discord : https://discord.gg/h9RCbRNTXt

This was made using Unity 2020.3 LTS and HDRP 10. Any other version may vary.

Music https://www.youtube.com/watch?v=IV8N-gy5QZg

0:00 Introduction

00:28 Scene Setup
01:11 Shader creation time...

▶ Play video
leaden ice
#

As long as it's a dev build log statements will show up in the application log

gleaming burrow
#

sorry im still a little new to unity, how do I see the log in builds?

#

never mind thankyou google XD

dawn nebula
#

Hey so I've got a question related to code architecture. I've got a game where multiple NPCs need to coordinate the completion of one big task. Imagine some Sims-like situation where for dinner to start, there needs to be 4 NPCs at a table. They need to realize it's time for dinner, where to sit at the table, and that they should eat.

I want to be able to tell an individual NPC to leave dinner to go do something else, and I also want to be able to end dinner and "free" all NPCs at any moment. Any suggestions?
The NPCs have a task-based system where I can queue up a bunch of tasks for them to do and they'll work their way through the queue.
It's the group-based tasks that I'm unsure of how to best handle.

hard viper
#

the group task just needs a central point of contact to notify a group of NPCs to remove it

#

or, you could make group tasks erase (or outprioritize) their normal queue of tasks

#

i assume one NPC can only have one group task at a time, and that one group task takes priority over any other tasks

hard viper
#

each time you check for next task to do: if priority queue has something, then do it. else do from normal queue

#

then you can ask one specific NPC to dump its priority queue at any time, which automatically returns it to its normal queue of tasks

#

and an NPC finishing a priority tasks will automatically start the next priority/normal task

#

then, for group management, group tasks would just need a manager with a collection: List<GroupTask> activeGroupTasks;
each group task has a list of all NPCs that are a part of it.

#

GroupTask : Task

#

and give Task a method public virtual void OnTaskDoneBy(NPC npc);

#

Task: OnTaskDoneBy(NPC npc) {}
does nothing

#

GroupTask: OnTaskDoneBy(NPC npc) {
participatingNPCs.Remove(noc);}

steady moat
dusk plume
#

hi

#

i want to add android build thing in my unity version

hard viper
dusk plume
steady moat
hard viper
#

a bit more, but not too tough

steady moat
#

Enough to make a difference

hard viper
#

the hard part is the command pattern-like part. the easier part is managing priority

steady moat
hard viper
#

yeah, i think that is a good idea

dawn nebula
dawn nebula
#

lol, well hopefully I don't fall into the scope creep trap 😛

hard viper
#

looking into GOAP, i think it is a good tool, but might be a lot bigger than needed here. depends on what he needs

steady moat
dawn nebula
#

Like I will never be in a situation where an AI needs to get "warm" but needs to know to get fire wood, to light a fire to get warm.

#

In my case NPCs will be explicitly told to do something, and will be given explicit instructions on what to do.

steady moat
#

Not really what you said 😛

They need to realize it's time for dinner, where to sit at the table, and that they should eat.

dawn nebula
#

Fair I could see it being interpreted like that.

hard viper
#

GOAP is going to be a bit of a rabbit hole if you don’t need it

dawn nebula
#

I was more going for "these are the steps required to do dinner".

hard viper
#

as I see it, your main options are to use a priority queue or to use GOAP

dawn nebula
#

Currently I have a priority queue.

hard viper
#

to be clear, a priority queue AND a normal queue

#

so you dequeue from priority queue if there is a high priority task available. Otherwise, you go through normal queue

#

then tasks can be assigned different priority levels

#

NPC picks the highest priority queue that has at least one task in it

#

does that make sense?

dawn nebula
#

Ya it does. Though I'm wondering if I could end up in like... priority hell 😛 where I'm like "ok this task has high priority but this would should always be higher than that."

hard viper
#

the alternative is GOAP, which requires you to construct a whole list of actions to reach a specific goal. GOAP will make the NPCs smarter, but also more difficult for player to do exactly what they want.

dawn nebula
#

So I'm wondering if I should just have 1 list that acts like a queue, but also sorts by some defined priority.

hard viper
#

i would have an array of queues

#

iterate through array, and the first queue that has something in it: go do it.

#

array index corresponds to priority

#

when a new task is added, check to see if we need to put down current task

fervent furnace
#

one binary heap is enough, you can push tasks with same priority into it

late lion
#

It shouldn't be too complicated to implement a sorted-by-priority queue, assuming tasks can't have dynamic priorities.

hard viper
#

heap is faster. but also more complex to implement, i think

fervent furnace
#

if the priority of task is dynamic, it is terrible
the only way to pop is to iterate the whole array and remove as swap back

hard viper
#

if you have dynamic priorities, then GOAP is the way to go

#

priority queue[]/heap is simple for more simple behaviour imo

fervent furnace
#

ah, you can still use sorted set, but it runs slower than heap

#

delete then insert it bask

hard viper
#

i’m assuming total distinct priority levels is a very small number

hard viper
dawn nebula
#

Though tbf the priority of tasks is less my issue. It's more the coordination of a group task.

hard viper
#

do what I said before then

#

GroupTask : Task

#

Task: public virtual void OnDoneBy(NPC npc) {}

#

GroupTask: public override void OnDoneBy(NPC npc) {
participants.Remove(npc);
if (participants.Count == 0) {
whatToDoWhenDone
}
}

#

and GroupTask has a list of participants.

#

make sense?

dawn nebula
#

who is executing that task?

rain minnow
#

the TaskMaster . . .

hard viper
#

every NPC in the participants list has that group task in their queue/heap/whatever

#

GroupTaskManager can keep a collection of active group tasks. And GroupTask can report back to it when it is complete

dawn nebula
hard viper
#

WhateverMonobehaviour decides what NPCs need to be a part of a given group task. Then it asks GroupTaskManager to assign. GroupTaskManager maintains a list of active group tasks. GroupTask’s constructor assigns the task to all the NPCs. When GroupTask is done, it tells GroupTaskManager it is done, and also tells WhateverMonobehaviour (that constrcuted it) that it is done.

safe dagger
#

Has anyone been able to get custom rich text tags working well/properly, I know of using links but that method sucks, I found a old forum post about editing the TMP_Text.cs to add my tags but I have the issue of the class being regenerated on the spot after editing it

hard viper
#

You probably need an interface: ITaskCompletionReceiver {
OnTaskComplete(Task task);}
This way GroupTasks can specifically hold a reference to the thing that needs to be notified, and tell it that it is done.

#

so WhateverMonobehaviour : ITaskCompletionReceiver

dawn nebula
#

alright I'll give something like that a try

#

I dont exactly like a task having reference to the thing that is managing it (which also has a reference to the task), but meh

hard viper
#

dinner table should get notified when a task for setting the dinner table is done

#

a building should get notified when a wall-building task is done

#

Task could also store null, to notify nothing when it is done.

dawn nebula
#

no that makes sense

dawn nebula
#

For this example.

hard viper
#

i mean the task has a reference to the building’s behaviour

#

probably a list of ITaskCompletionReceivers. So if you need to notify many behaviours when a given task is done, you can do it

tepid brook
#

Hi guys who know what is the name of the plugin to clone a project to have 2 unity windows ?

tepid brook
# leaden ice ParrelSync?

thx you, because i'm working on a phone game and its too long to build and transfer on a phone ahah

elfin quest
#

Hello everyone, I want to make fixed time jump without using rigidbody. I'm currently using bezier curves for distance jumps and it works splendid, but I'm having tuble when I want to do a static jump, since the start and end points are exactly the same. Should this approach be working anyway and I've missed something? Or does bezier curves not work with same origin and end point?

In the latter case, does anyone have a solution I can use?

leaden ice
elfin quest
#

Thanks for the reply, but the case was the first! Bezier curves work with the same start and end point, I was just using the wrong time variable. If you are interested on the solution I can share the code:

if (isSmashing)
        {
            if(currentSmashTime <= smashTime)
            {
                currentSmashTime += Time.fixedDeltaTime;
                Vector3 calculatedPoint = CalculateBezierPoint(currentSmashTime);
                skinHolder.transform.position = calculatedPoint;
            }
        }

This is called on the fixedUpdate.

 public Vector3 CalculateBezierPoint(float time)
    {
        float u = 1 - time;
        float tSquared = time * time;
        float uSquared = u * u;

        Vector3 calculatedPoint = uSquared * startPoint;
        calculatedPoint += 2 * u * time * controlPoint;
        calculatedPoint += tSquared * targetPoint;

        return calculatedPoint;
    }

This is the calculate function.

My issue was that this same character has 2 jumps, and the CalculateBezierPoint function, instead of asking for the time as an argument, it was using the time from the first jump, when I was testing the second one. I have this setup because I want the jumps to have a precise jump time, and the 2 jumps have different jumpTimes.

#

The variables startPoint, controlPoint and targetPoint are computed before the jump starts, on the same function that enables isSmashing.

vivid wind
#

When handling changing resolution or other graphics settings. Do most games load a default resolution then switch after reading the player prefs, or is there a way to get the application to load directly into the last resolution settings without having to run a script to change it?

weak dove
#

I have a scroll view populated by Buttons. It works fine, you can press the buttons but also drag to scroll up/down. The problem is these Buttons also have another component on them that implement the OnDrag events. This makes it so that you can drag on the buttons to scroll. Is there any way to disable the OnDrag events without disabling the component?

weak dove
# leaden ice what component is it?

It's a script I made to display item information in my game. It implements the OnDrag events so I can drag items between different inventory slots. In this case I don't want to be able to drag the items but I want to keep the component.

leaden ice
#

otherwise leave it off

weak dove
#

ah I didn't know about EventTriggers, thank you!

unreal pond
#

guys, I've been trying to use the the new UIBuilder ListView to create a high scores list. I've created a new Visual Tree asset for the list entry

<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" xsi="http://www.w3.org/2001/XMLSchema-instance" engine="UnityEngine.UIElements" editor="UnityEditor.UIElements" noNamespaceSchemaLocation="../../../UIElementsSchema/UIElements.xsd" editor-extension-mode="False">
    <Style src="project://database/Assets/UI%20Toolkit/UGUI/listEntry.uss?fileID=7433441132597879392&amp;guid=6ba520f1250203b4d948fbbe4b670fa3&amp;type=3#listEntry" />
    <ui:VisualElement name="parent" style="flex-grow: 1; flex-direction: row; width: auto; height: auto;">
        <ui:Label tabindex="-1" text="Label" parse-escape-sequences="true" display-tooltip-when-elided="true" name="name" class="nameLabel" style="width: 30%; margin-top: 4px; margin-right: 0; margin-bottom: 4px; margin-left: 2px;" />
        <ui:Label tabindex="-1" text="Label" parse-escape-sequences="true" display-tooltip-when-elided="true" name="score" class="scoreLabel" style="flex-shrink: 1; flex-grow: 1; width: 70%; margin-top: 4px; margin-right: 2px; margin-bottom: 4px; margin-left: 0;" />
    </ui:VisualElement>
</ui:UXML>

and I created a list to be the info for the ListView. But I son't know how to correctly do the binding, for the labels on the ListEntry visual tree asset to change according to the list content. Any Ideas how can I make that happen?

unreal pond
#

damn, it's down there in artists tools, and it's almost all code

#

thank you, I'll move the topic there

hard viper
#

holy shit that language looks like pain

queen pollen
rigid island
knotty sun
rigid island
#

i bet its not the most important problem that requires to post this many times

queen pollen
#

im on a deadline sorry

rigid island
queen pollen
#

again i already said sorry

#

mb

knotty sun
#

So take them all out and do it properly this time !code

tawny elkBOT
knotty sun
#

remove all your posts and post 1 in the correct channel and do it properly

hard viper
#

or the mods will do it for you. and you really don’t want the mods to do it for you

queen pollen
queen pollen
karmic horizon
#

Guys, why is my model not using the run animation?

leaden ice
polar marten
leaden ice
#

identify what is null on that line.

#

identify why it's null at that time.

#

fix it

#

as with all NREs

wild jasper
#

anyone any idea why the Debug in input name outputs the variable corectly but the debug in Continue says Null after that?

#

putting the things from continue into Input name makes it work but i wnat so save multiple things so this isnt an option

leaden ice
#

Could be on completely different instances of the script for example

wild jasper
#

so i input a text into a TMP input field, press enter, it shows me the correct variable, then i press the continue butteon directly underneath it wich callls Continue

leaden ice
#

Any other scripts, the buttons, the input field, etc

wild jasper
leaden ice
# wild jasper

Looks like you have two completely separate instances of the CreateCharacter script

#

Which falls in line with what I mentioned above

wild jasper
#

ohhhhhhh fuuuu thank you

#

didnt think of that at all you are my saviour

obtuse cape
#

Im trying to create a gun sway. But my pistol ends up looking down when pressing play. How am i able to change this so the pistol is aiming forward

public class GunSway : MonoBehaviour
{

    public float smooth;//float that holds the sway smoothness amount
    public float swayMultiplier;//increases/decreases the amount of sway on the gun

    private void Update()
    {
        //get the mouse inputs for both x and y 
        float mouseX = Input.GetAxisRaw("Mouse X") * swayMultiplier;
        float mouseY = Input.GetAxisRaw("Mouse Y") * swayMultiplier;

        //calculate the target rotation

        Quaternion xRotation = Quaternion.AngleAxis(-mouseY, Vector3.right);//Calculates target rotation on x axis, -mouseY because inverted otherwise
        Quaternion yRotation = Quaternion.AngleAxis(mouseX, Vector3.up);

        Quaternion targetRotation = xRotation * yRotation;//combine both x and y rotation

        //rotate the gun 
        transform.localRotation = Quaternion.Slerp(transform.localRotation, targetRotation, smooth * Time.deltaTime);

    }
}
leaden ice
obtuse cape
#

The blue arrow is not pointing out the barrel

#

i have to always set the gun x rotation to -90 since its not pointing forward

#

so how can i use the -90 rotation intstead of transofmr.local rotation

#

@leaden ice

leaden ice
obtuse cape
#

how should i import it with correct settings

leaden ice
# obtuse cape how should i import it with correct settings

Exporting from Blender to Unity can result in rotation and scale issues that are not intuitive to fix. This video teaches how to fix them for meshes attached to an armature.

Complete Playlist:
https://www.youtube.com/playlist?list=PLq7npTWbkgVBAtQs4p4iYxlfWrKRkNc6O

Relevant links:
Penguin Mesh Download - https://immersivelimit.page.link/pengui...

▶ Play video
tranquil canopy
#

Could someone help me with this log when i try to use google firebase?

rigid island
#

that thing is a shite show

#

your error seems to be related to you missing something IOS

#

probably XCode

#

the error , read it

#

usally says

polar marten
tranquil canopy
rigid island
polar marten
tranquil canopy
rigid island
#

just delete the IOS dll then

tranquil canopy
polar marten
#

@tranquil canopy how did you install the firebase package?

#

did you copy and paste something from somewhere?

#

was the thing you copied and pasted, a bunch of folders in windows into your Assets/ directory?

tranquil canopy
polar marten
tranquil canopy
rigid island
lone wagon
#

So i just opened my project i'v worked on for weeks. 2 days off and now this sht happends. Everything is deleted and terrain is completly destroyed,.
What is this sh
t??????????????

rigid island
#

lookup that error in google they have a github post on it @tranquil canopy

rigid island
tranquil canopy
lone wagon
rigid island
#

Thanks for bringing this to our attention. This issue could be solved by making sure you have the iOS build support in your Unity version.

#

try that

lone wagon
#

did already

tranquil canopy
dawn sundial
#

Hi, having an issue with my camera - it resets/turns around just once. Code looks fine (no resets after time, etc..).
Since I'm having Camera as a child of Player object (with CharacterController) I feel like it may be connected to Logic/Physics frame sync, ...

I checked profiler and saw one spike exactly when the camera glitch happened. In that very spike there is no PhysicsFixedUpdate - is that correct?
Any ideas?

Gif link: https://media.discordapp.net/attachments/834751099306508298/1179520687862448238/022b1fa5-ecca-4196-b233-3d392ccd4fca.gif?ex=657a153e&is=6567a03e&hm=ca8e53393aad8265b95d2f70dc4844402a70d012f802e02b2b1e38bf295d04a5&=

leaden ice
dawn sundial
#

Can I share the code here or better to upload it somewhere?

tawny elkBOT
dawn sundial
#

PS: I tried to move Movement to FixedUpdate and View to LateUpdate, didn't help => leads to horrible tearing of object edges which player is strafing around

leaden ice
dawn sundial
#

yep, by the "new" Unity Input System

spring creek
#

Brackeys special

leaden ice
#

Remove Time.deltaTime from the mouse rotation calculation

#

(and adjust your view sensitivity down to compensate)

dawn sundial
#

trying...

dawn sundial
leaden ice
dawn sundial
#

And thank you very much for very quick and valid explanation of the delta. I didn't realize that at all

dawn sundial
#

learning profiler.. so not sure what to look at

#

It goes from 2ms to 6.5ms on EditorLoop - nothing else. Is that too much? 6.5 ms should be nothing, right?

#

Oh, I found this: Physics Queries: 265 hmm...

lean sail
dawn sundial
#

thanks @lean sail - I think that's alright, I didn't know there is other profiling information below the one I posted - basically I was looking at CPU only but the spike is actually in PHYSICS category

leaden ice
#

but it's editor only

dawn sundial
#

hm, so you think that physics queries are alright to be 265? - I'm going to make a build and try

leaden ice
#

no definitely not

#

that's definitely a problem

lean sail
dawn sundial
dawn sundial
#

I don't know, can't see anything special.. I mean I probably see the spike, but there is just standard stuff in the editor

leaden ice
#

inside OnGUI

dawn sundial
#

Yeah, it's the only thing that consumes the most of it..

#

I have one idea

#

well I had 2 custom Editor scripts that had been using the OnGui - I compeltely removed, it didn't help :/

soft shard
trim rivet
#

Can someone explain to me why the same operation produces two different results here ?

#

I'm beyond baffled

dawn sundial
simple egret
trim rivet
simple egret
#

(If you want the upper sphere to be above the collider you should add the radius, not subtract it)

trim rivet
#

why is the bottom sphere not within the collider?

#

the distance from the center should be the same value.

dawn sundial
lean sail
#

if you want it at the bottom of the capsule (and inside), then just subtract the height and add the radius of the sphere

trim rivet
#

I just saw it, oh man I'm so stupid

#

🫂 🫂 🫂 🫂 basic Math where have you been all my life

lean sail
trim rivet
#

thanks guys

lean sail
#

turning it on should just solve this then

dawn sundial
#

wow, it really sovled the issue

lean sail
dawn sundial
#

Thank you very much! I had no idea there is such an option and no idea why it was off (reading the documentation - it says it should be on by default).

lean sail
#

I saw that as well, no idea why mine was off either

dawn sundial
#

thanks a lot, spend hours on that, but I'm super happy for all the help @lean sail and @soft shard and @leaden ice - you tought me a lot today!

tranquil canopy
#

Hey, has someone ever used google firebase? i have 2 logs and i dont know how to solve them...

vapid bluff
#

Hello. I've noticed something weird while making my game. Everytime I press play, instead of showing the right tiles (image 1), the tiles are shown in random order (image 2). Is has something to do with the terrain sprites and the order that I put/copy-pasted them?

leaden ice
vapid bluff
leaden ice
hard viper
#

@heady iris I fixed my pausing bug from yesterday. My solution was to make better use of a class I made to allow me to run methods in EarlyFixedUpdate. It's just a singleton that invokes a delegate every fixed update, with super high execution order. Also LateFixedUpdate, to get things in immediately after collision callbacks are done.

leaden ice
#

That's the code responsible

vapid bluff
leaden ice
#

Well you can post it here. But I assume it's just because whatever is in the tilemap in the editor doesn't matter because you're streaming the data either from a noise function or some saved data

vapid bluff
leaden ice
#

!code

tawny elkBOT
vapid bluff
leaden ice
#

Whatever you have set up in the editor will be ignored/overwritten

vapid bluff
#

I see

#

I will try and fix it

rich leaf
#
            if (Quaternion.Angle(transform.rotation, _targetRotation) < rotationThreshold)
            {
                // Apply the movement only when the rotation is within the threshold
                transform.Translate(Vector3.forward * currentSpeed * Time.deltaTime);
            }```
 I have this code here and I am stumped as to why the player is moving at different speeds on my computer vs my partners
leaden ice
rich leaf
#
    private Vector3 CalculateMovementDirection()
    {
        // Calculate the movement direction based on arrow keys or WASD
        Vector3 moveDirection = Vector3.zero;

        if (Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.W))
            moveDirection += Vector3.forward;

        if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D))
            moveDirection += Vector3.right;

        if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.S))
            moveDirection += Vector3.back;

        if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A))
            moveDirection += Vector3.left;

        // Normalize the movement direction if it's not zero
        if (moveDirection != Vector3.zero)
        {
            moveDirection.Normalize();
        }

        return moveDirection;
    }
#

TThis calculates the movement direction

leaden ice
#

Can you show the full script

rich leaf
#
        if (_normalMovement)
        {
            // Set movement speed based on input
            if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
            {
                currentSpeed = sprintSpeed;
            }
            else if (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl))
            {
                currentSpeed = walkSpeed;
            }
            else
            {
                currentSpeed = jogSpeed;
            }

            // Move the player
            NormalMovement(CalculateMovementDirection());

        }
``` and this is what gets called in Update
#
    {

        // Translate the player's position based on the movement direction and amount
        //Vector3 newPosition = transform.position + movementDirection * currentSpeed * Time.deltaTime; //! Change to fixeddeltatime if using fixedupdate
        //transform.position = new Vector3(newPosition.x, transform.position.y, newPosition.z);


        // playerRb.MovePosition(newPosition);

        // Rotate the player to face the movement direction
        if (movementDirection != Vector3.zero)
        {

            // Calculate the rotation based on movement direction
            _targetRotation = Quaternion.LookRotation(movementDirection);

            // Check if the rotation is close enough to the target rotation
            if (Quaternion.Angle(transform.rotation, _targetRotation) < rotationThreshold)
            {
                // Apply the movement only when the rotation is within the threshold
                transform.Translate(Vector3.forward * currentSpeed * Time.deltaTime);
            }

            // Interpolate the rotation
            transform.rotation = Quaternion.Lerp(transform.rotation, _targetRotation, _rotationSpeed * Time.deltaTime);


            // Play correct animation
            if (currentSpeed == sprintSpeed)
            {
                this.GetComponent<PlayerAnimationHandler>().Player_Ani_Sprinting();

            }
            else if (currentSpeed == walkSpeed)
            {
                this.GetComponent<PlayerAnimationHandler>().Player_Ani_Walking();
            }
            else
            {
                this.GetComponent<PlayerAnimationHandler>().Player_Ani_Jogging();
            }
        }

        // if not moving, play idle animation
        else
        {
            this.GetComponent<PlayerAnimationHandler>().Player_Ani_Idle();
        }
        
    }```
And this is the NormalMovement() function
leaden ice
#

Just posting the full script in a paste site !code would be much more helpful

tawny elkBOT
rich leaf
#

Can't share the full script unfortunately

leaden ice
#

Well transform.Translate(Vector3.forward * currentSpeed * Time.deltaTime); on its own is fine assuming currentSpeed is the same

#

transform.rotation = Quaternion.Lerp(transform.rotation, _targetRotation, _rotationSpeed * Time.deltaTime); isn't quite a proper Lerp but it shouldn't matter all that much

leaden ice
#

So given what you've shared I can't say what the issue is

leaden ice
spring creek
# rich leaf whats wrong with this?

In short, the third variable is not a speed. It's not any kind of rate. It's a percent between the first two.
Multiplying it by deltaTime makes that value go up and down and look shaky. You never want to multiply it by deltaTime

heady iris
#

You know how interest is worth more if you compound it more frequently? It’s a similar situation

#

You wind up with behavior that varies with your framerate

polar marten
hard viper
#

is there a way to make a machine const editable in unity editor? like how Physics2D works?

polar marten
rich leaf
#

Lol no

polar marten
#

is it from a tutorial?

rich leaf
#

It’s to make the movement when changing directions feel more realistic and less flipping on a dime

#

And yes I did it myself

#

Causes a smoothing effect as you’re changing directions and moving

polar marten
#

what is it?

#

what is being moved? like what's going on?

rich leaf
#

The player

#

The player gets rotated at some speed and once it’s within the threshold to the desired rotation it allows the player to start moving

polar marten
#

think very deeply about my question

#

big picture, what is going on

rich leaf
#

The game is top down 3D

polar marten
#

tell me what i need to know

#

okay that's very good

hard viper
#

so, quaternions are weird

polar marten
#

is the idea that right arrow always moves the player in positive x in the xz ground plane?

#

or does it move the character "right" relative to where it is facing, like driving a car?

hard viper
#

the best way to deal with quaternions is to try to avoid any sort of addition/subtraction or direct modification of ijkl individually

#

you want to use methods to multiply them, or rotate by

#

going back to your problem, _rotation speed has units of degrees/sec, and deltaTime has units of seconds. So you are using Quaternion.Lerp with the last number having units of degrees

#

which is incorrect

#

the last argument of a lerp/slerp needs to be dimensionless

polar marten
#

it seems weird to me, but is your goal that if my character is facing positive z (aka "screen up"), and i hit Right Arrow, it remains stationary and rotates towards ALMOST positive x, and then when it's within a certain threshold, start moving, and continue to rotate towards positive x?

polar marten
hard viper
#

lerp/slerp's last argument brings you to a spot between the start and end (0-1) by the 3rd argument

polar marten
#

@rich leaf also, when sharing your project, are you using git?

#

i will tell you now, based on the code you shared, the simplest explanation for why the speeds are substantially different is that you guys do not comprehend what you are looking at. like probably you didn't save and commit your scene, which has a different sprint and walk speed than what is committed into git

#

because there is nothing wrong with transform.Translate(Vector3.forward * currentSpeed * Time.deltaTime); which is the only place where your character moves in this code snippet

#

so everything else is a red herring

#

@rich leaf does that make sense? ignore this quaternion story nonsense, it isn't causing the thing you are describing, although it is indeed glitchy

rich leaf
#

Game is top down, W corresponds to going up the screen (game is in xz plane), D corresponds to going to the right, etc...

#

The whole point of the rotation is that lets say I am going upwards (W) and want to change directions to the right by holding D, the players transform gets rotated and then the player is moved forward. However there is a threshold that has to be satisfied in the rotation (ie has to be 90% done the rotation) before it starts moving the player.

The idea for it (and works very well) is to smooth the rotation and prevent the players transform from just flip flopping to face the direction, which works for 2D but looks janky in 3D. You can balance the rotation thresholds to find a good middle ground between responsiveness and looking good

rich leaf
#

Also, the speeds are set in the script themselves and are not modified in the inspector

summer oar
#

I am confused

#

this code loads a texture from a byte[] array, and falls back on creating a solid color texture if the byte[] is invalid

#
private Texture2D GetTextureFromBitstream(byte[]? bitstream, UnityEngine.Color backgroundColorForInvalid, UnityEngine.Color key)
{
    if (bitstream == null || bitstream.Length == 0)
    {
        backgroundColorForInvalid = UnityEngine.Color.red;
        
        var solidTexture = new Texture2D(3, 3, TextureFormat.RGBA32, false);
        solidTexture.SetPixels(new[] { backgroundColorForInvalid, backgroundColorForInvalid, backgroundColorForInvalid, backgroundColorForInvalid, backgroundColorForInvalid, backgroundColorForInvalid, backgroundColorForInvalid, backgroundColorForInvalid, backgroundColorForInvalid });
        return solidTexture;
    }

    var imageTexture = new Texture2D(1, 1);
    imageTexture.LoadImage(bitstream);
    imageTexture.alphaIsTransparency = true;
        
    UnityEngine.Color[] colorData = imageTexture.GetPixels();
        
    for (var i = 0; i < colorData.Length; i++)
    {
        if (colorData[i] == key)
            colorData[i] = default;
    }
        
    imageTexture.SetPixelData(colorData, 0);
        
    return imageTexture;
}
#

In the case where the byte[] is valid and I get the image, everything's fine

spring creek
summer oar
#

but in the case where it falls back to the solid color, I get a translucent gray texture in my UI

#

And I'm unsure why

summer oar
#

Because look at the code, it should be solid red

#

And it is if I use EncodeToPNG on it and save it to disk

rich leaf
#

What effects do i expect to see "incorrectly" using lerp? Everything looks smooth on my end

cosmic rain
cosmic rain
summer oar
#

ABSOLUTELY sure

#

and I'm well aware of the debugger, thank you

#

I wouldn't really be asking for help if I hadn't exhausted all other options

cosmic rain
#

Okay, then what do you see in the debugger when the issue occurs?

#

Might also be a matter of applying the changes to the texture.

summer oar
#

Like I said. If I use the debugger to call EncodeToPNG on the texture in the if block, I get a 3x3 red texture like I should

#

proof incoming

#

that is the texture

#

But it shows as the gray texture even in the Unity inspector

cosmic rain
#

Not sure what you mean by "use the debugger to call EncodeToPNG", but okay. What about the applying changes part?

polar marten
#

so something else is wrong

hexed pecan
#

Looks like dlich pointed that out too

polar marten
#

comment out this rotation and don't worry about it since it's not essential

summer oar
#

there's an interactive console

summer oar
#

that might just kill two bugs

cosmic rain
#

Ah, you're using that? There's that feature in VS to, but I'm not sure how reliable it is.
Regardless, my question still stands.

mental rover
polar marten
#

i mean he won't share the whole code file

summer oar
#

OH MY GOD

#

IT WAS APPLY

mental rover
summer oar
#

calling Apply fixed solid textures

#

but now image textures are broken

#

the background where the two windows are, well

#

that should be Windows XP Bliss

#

now it's just a weird pattern

#
private Texture2D GetTextureFromBitstream(byte[]? bitstream, UnityEngine.Color backgroundColorForInvalid, UnityEngine.Color key)
{
    if (bitstream == null || bitstream.Length == 0)
    {
        var solidTexture = new Texture2D(1, 1, TextureFormat.RGBA32, false);
        solidTexture.SetPixels(new[] { backgroundColorForInvalid });
        solidTexture.Apply();
        return solidTexture;
    }

    var imageTexture = new Texture2D(1, 1);
    imageTexture.LoadImage(bitstream);
        
    UnityEngine.Color[] colorData = imageTexture.GetPixels();
        
    for (var i = 0; i < colorData.Length; i++)
    {
        if (colorData[i] == key)
            colorData[i] = default;
    }
        
    imageTexture.SetPixelData(colorData, 0);
    imageTexture.Apply();
        
    return imageTexture;
}
#

so, everything in the if statement is fine

#

everything after it isn't

#

Any idea what could be corrupting it?

#

Narrowed it down

#
UnityEngine.Color[] colorData = imageTexture.GetPixels();
            
for (var i = 0; i < colorData.Length; i++)
{
    if (colorData[i] == key)
        colorData[i] = default;
}
            
imageTexture.SetPixelData(colorData, 0);
imageTexture.Apply();
#

comment this code out and the texture loads fine, no corruption

#

but I need this code to do what it's written to do

#

SetPixels instead of SetPixelData

#

that fixed it

naive inlet
#

Hello, I need help with trying to add controller support for Prometeo Car Controller?

#

Working on a project with a group and we trying to do controller support for the car

rich leaf
#

Literally sent the whole code dude

naive inlet
#

Huh?

rich leaf
mental rover
spring creek
# naive inlet Huh?

I think they're talking to someone way above and just didn't do the reply button

naive inlet
#

Oh

modern creek
#

I'm getting DOTween errors when trying to delete a game object as part of the sequence on the tween. No worries, I can use OnComplete and it works fine. However, Demigiant's OnComplete replaces any other callback if one is set, and I need the OnComplete for other things (sequence queue).

Any ideas?

leaden ice
#

E.g. start a new sequence

modern creek
#

hm.. not sure I can easily. I have a sequence manager that's .. asking the components for a sequence, and then tacking it's own callback onto the sequence so it can fire the next.

Example, the "reward manager" can ask the "reward renderer" for a single sequence of grant 100 coins, and then stick them in a queue with a callback to fire the next one.. result:

#

but the .. i can only use oncomplete..

#

or maybe i could .. append a normal callback instead of using oncomplete

leaden ice
#

Can the sequence just do something silly like set a flag to destroy the object later or start a coroutine that does the same?

#

Also not sure I understand what the error is with putting Destroy in the sequence? What kind of error is it?

modern creek
#

I'm trying to get the error actually but DOTween seems to be soaking it somewhere.. I think it might be a problem with trying to destroy the object in the same frame as another part of the sequence is finishing? ie, if I tween scale from 0 to 0.5 sec and immediately append a callback to destroy, it .. just doesn't destroy the object. I'll show, one sec

#

OK, I've figured it out. And.. it's dumb. 🤦‍♂️

#

I overrode Destroy(UnityObject) to throw an exception when I tried to destroy a component on a gameobject (accidentally) instead of destroying the game object.

When I (finally) managed to get dotween's logging to show the underlying error, I found it.

The code I posted above even has it correct - it was only when I tried to Destroy(tile) instead of Destroy(tile.gameObject) did it fail.

leaden ice
#

ah

modern creek
#

(tile is some sort of object of mine)

cursive moth
#

Hi, I followed an advice I was given(because my terrain was disappearing), I rewrote the entire generation script so that it uses multiple connected closed sprite shapes instead of a single shape w many points because I was getting a warning message of max vertex limit being reached(which does appear to be solved now).
However, this new approach results in the terrain being very "unsmooth" and colliders are not nice because there are multiple instead of a single connected one.
I don't know what I am supposed to do in order to achieve a smooth appearance and nice feeling colliders(required for gameplay).
Here's the code
I'll provide an image showing what I mean by "unsmooth" terrain and colliders aswell.
This image shows a small gap between 2 sprite shapes even tho they are right next to each other, what am I supposed to do?

modern creek
leaden ice
modern creek
#

Yeah.. I think I'd make that part of the component that I'm asking for the sequence from.. like, "how long is your attention required".. and at the parent, instead of queue and dequeue only when the sequence is finished, I'd insert the next sequence after the first one has indicated "that's good enough".

ie: Sequence one takes 5 seconds but 3 seconds is good enough
Sequence two is 5 seconds but 3 seconds is also good enough

Orchestration: Start sequence 1 at 0.0 sec and 2 at 3.0 sec, and restore navigation after 6.0 sec

#

the animations themselves aren't great but I just needed something to ensure that I could.. queue up 6 animations at once and have them unspool nicely

rich leaf
#

Alright so going back to my p[roblem from earlier with the player speed being different on different hardware. When the players rigid body is removed, our movement speed is the same. However, the rigid body literally does not get called anywehre in the entire project solution (confirmed by searching through whole solution in VS). We've even commented out everything that had to do with playerRb in the code, but only when the component itself was removed did the movement match...

#

are there any settings in here that would be framerate dependend even if no scripts call the rigidbody?

cursive moth
#

try disabling that

rich leaf
#

It seems like isKinematic being disabled also fixed it?

#

why would that be the case?

cursive moth
#

I am honestly not sure

#

I just had several instances of rb interpolation messing up the movement

#

I mean I have an idea of why it's happening but not sure if it's accurate

rich leaf
#

turning on isKinematic and disabling Interpolate fixed it too

#

And the weird part is this only seems to change things on their end... mine is unaffected

cursive moth
#

afaik, interpolate mimics the smooth movement of an rb(movement between fixed updates) by interpolating between the position before previous and previous position

#

and therefore, when combined with a transform based movement, it completely messes up everything

#

I am not sure if what I just said makes sense or is true

leaden ice
#

But generally a kinematic body should be well behaved with direct transform motion

#

Although interpolation is completely unnecessary if you're moving it in Update via the transform

rich leaf
#

What constraints are weird?

cursive moth
spring creek
#

And the y position

rich leaf
#

it seems to be the interpolation. What is this used for?

cursive moth
rich leaf
#

and how can you make it consistent across devices if you do want to interpolate?

cursive moth
rich leaf
#

is interpolation used for physics based movement?

cursive moth
#

it is used to smooth out the movement done in FixedUpdate() which happens less often than Update()

rich leaf
#

ahh that makes sense

#

thanks

leaden ice
#

If you're already moving in Update it's already in sync with the display framerate

#

Oops sorry I'm slow

fickle lichen
#

Hey I'm unable to understand number of commands in SpherecastCommand.ScheduleBatch(), how should I decide what number to put for "minCommandsPerJob" argument? Does it have to be amount of CPU cores?

cosmic rain
fickle lichen
cosmic rain
#

Start from the total count and look at how long the job takes to perform. If it's too long, divide by 2.

fickle lichen
earnest karma
#

can someone help me with my code? i'm trying to make it so the gameobject can be rotated when swiping across screen (like previewing a 3d model) and it works but when moving too fast it starts jerking back and forth

public class DragRotator : MonoBehaviour
{
    public float sensitivity = 1;
    public float speed = 0.5f;

    private Quaternion targetQuat;

    private void Start()
    {
        targetQuat = transform.rotation;
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        if (Input.GetMouseButton(0))
        {
            float pitch = Input.GetAxis("Mouse Y") * sensitivity;
            float yaw = -Input.GetAxis("Mouse X") * sensitivity;
            
            Quaternion yawRotation = Quaternion.AngleAxis(yaw, Camera.main.transform.up);
            Quaternion pitchRotation = Quaternion.AngleAxis(pitch, Camera.main.transform.right);

            targetQuat = yawRotation * pitchRotation * targetQuat;
        }

        transform.rotation = Quaternion.Lerp(transform.rotation, targetQuat, speed * Time.deltaTime);
    }
}
fickle lichen
cosmic rain
earnest karma
fickle lichen
spring creek
cosmic rain
cursive moth
cosmic rain
earnest karma
cosmic rain
cursive moth
#

it completely fixed the collider it seems, the visuals are not there but I can live w that

polar marten
indigo plume
#

im trying to make a moving platform, but the player keeps changing its scale with the floor and bugs it out, is there a way to keep it from affecting the scale?

fervent furnace
#

Because you setparent so child global scale will be affected

#

I remember there is an overload of setparent persevere global transformation

indigo plume
#

so what would be a different way to set the parent without affecting the scale?

fervent furnace
#

See the overload version

indigo plume
fervent furnace
#

Keep the child position rotation and scale in world space while setparent

spring creek
# indigo plume whats the overload version 💀 im very new to this lol

An overload is the same method, but with a different signature (the parameters you pass in).

public void SetParent(Transform parent, bool worldPositionStays);
This is the other overload. Make worldPositionStays true I guess.

"If true, the parent-relative position, scale and rotation are modified such that the object keeps the same world space position, rotation and scale as before."

indigo plume
spring creek
#

public void should not be in there at all

fervent furnace
#

It is called method

flat abyss
#

Jesus guys, I'm sorry for the stupid question but I'm having a brain fart. How do we move an object backwards, regardless of rotation?

spring creek
#

collision.gameObject.transform.SetParent(transform, true);
It's EXACTLY what you had before, but with a comma true at the end

indigo plume
#

as i said

#

im very dumb and new to this

#

lmao

spring creek
spring creek
flat abyss
#

What it looks like. If the object is facing south, I want it to move north, if it's facing East, move west, etc

fervent furnace
#

Transform.forward

flat abyss
#

Exactly. The inverse of that

spring creek
#

-transform.forward

flat abyss
#

I'm having a bit of issues with localmoveZ -1

flat abyss
#

It's supposed to move one unity back regardless, but it keeps moving backwards. Perhaps it's because it has no parent

spring creek
spring creek
tawny elkBOT
spring creek
# indigo plume its still broken nvm

Actually, just to make sure, is this your current code?

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

public class StickyPlatforms : MonoBehaviour
{
    private void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.name == "Marble")
        {
            collision.gameObject.transform.SetParent(transform, true);
        }
    }

    private void OnCollisionExit(Collision collision)
    {
        if (collision.gameObject.name == "Marble")
        {
            collision.gameObject.transform.SetParent(null, true);
        }
    }
}
indigo plume
spring creek
indigo plume
#

oh lol

#

also ik how to fix error #2 but im having trouble with error #1 bc idk how to read errors and i cant figure out if its a problem in the code, or one of the things on the side

spring creek
indigo plume
#

and its just smth for the scoreText

#

is it bc the thingy is empty?

spring creek
#

Well, as you see from the previous screenshot, you don't have a reference to scoreText

spring creek
indigo plume
#

oh alr

somber nacelle
tawny elkBOT
somber nacelle
#

yep, looks configured now

indigo plume
#

this is the whole code for player movement in case u need it ig

cosmic rain
#

!code

tawny elkBOT
sleek chasm
#

hello i wanna know how to change the animations from the third person starter assest ?

cosmic rain
#

Is that code related?

graceful flume
#

I have a question: Is setting a float variable value = 0f the same as set in to float.MinValue

mellow sigil
#

Debug.Log(float.MinValue) and find out

fervent furnace
#

float can be negative

thin aurora
#

Google it

fervent furnace
#

you can see the value in your ide

latent latch
#

Better yet, just make a plain c# project to test this stuff on the side

thin aurora
#

That too, constants are shown when you hover over them

spark flower
#

GetComponentInChildren does this get the component from deactivated objects?

knotty sun
#

Actually GetComponent(s)InChildren has an option to include inactive objects as well

jovial spear
#
ArgumentException: Illegal characters in path.
System.IO.Path.GetExtension (System.String path) (at <1c8569827291471e9db0dcd976e97952>:0)
ReferenceChecker.Editor.LinkedAssedChecker.CheckPackedAssets (UnityEditor.Build.Reporting.PackedAssets[] packedAssets, System.String& message) (at Assets/_Scripts/ReferencesChecker/Editor/LinkedAssedChecker.cs:41)
ReferenceChecker.Editor.LinkedAssedChecker.OnPostprocessBuild (UnityEditor.Build.Reporting.BuildReport report) (at Assets/_Scripts/ReferencesChecker/Editor/LinkedAssedChecker.cs:21)
UnityEditor.Build.BuildPipelineInterfaces+<>c__DisplayClass18_0.<OnBuildPostProcess>b__1 (UnityEditor.Build.IPostprocessBuildWithReport bpp) (at <8117508d098d40e7b6cab2e14abb2fdc>:0)
UnityEditor.Build.BuildPipelineInterfaces.InvokeCallbackInterfacesPair[T1,T2] (System.Collections.Generic.List`1[T] oneInterfaces, System.Action`1[T] invocationOne, System.Collections.Generic.List`1[T] twoInterfaces, System.Action`1[T] invocationTwo, System.Boolean exitOnFailure) (at <8117508d098d40e7b6cab2e14abb2fdc>:0)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)

#

getting this error when building

#

where i could find the illegal character?

leaden ice
jovial spear
#

D:\Repo\folklore\Assets\

#

my path is clean

leaden ice
#

What about inside the project

jovial spear
#

inside the assets folder?

#

the space character is accepted?

warm kraken
#

this is my rotation function

#

but the issue is that sometimes it rotates endlessly

#

i heard its because i need to use quaternion rotation

mellow sigil
#

No, it's because you read Euler angles from transform

#

You need a separate variable to keep track of the current rotation

#
currentRotation = Vector3.Lerp(currentRotation, ...
transform.localEulerAngles = currentRotation;
#

also unrelated but incorrect use of Lerp

somber tapir
# warm kraken

you are comparing 2 vectors which is almost always not true because of rounding.

somber tapir
warm kraken
#

whats the right approach on lerp in this case?

somber tapir
#

Lerp(startPosition, endPosition, timer)

#

when timer is 0 the object will be at startPosition, when it is at 1 or higher it will be at endPosition. At 0.5 it will be in between both values.

swift falcon
#

Hey All!

#

I have an issue

#

Where I have a boomerang that constantly rotates, which causes my transform.position addition with transform.right to not go in a straight line.

#

I would like the sprite to go in a straight line, while rotating.

leaden ice
swift falcon
#

Thank you so much

dawn sundial
#

Hi all, would anyone be able to help with CharacterMovement vs deltaTime vs fixedDeltaTime + Update/FixedUpdate/LateUpdate --> in other words, **the issue is: ** My character jumps higher when game is maximized (with more FPS).
I have this script, that covers all the movement, mosue look and jump with gravity. https://pastebin.com/GWk7JDcG

I'm trying all the things like spliting logic into Update, performing Movement in FixedUpdate. Using fixedDeltaTime instead of deltaTime. But nothing seems to fix my issue.

somber tapir
leaden ice
#

And you added it here which doesn't make sense:
newMovementSpeed += m_jumpingForce * Time.deltaTime;

#

Also why are you adding jump force every frame?

#

That should only happen once, right when you jump

#

Also you should just save all the DeltaTime stuff till the end, right before the Move call. Right now you have it confusingly mixed in all over the place

dawn sundial
#

I was following some tutorial since I was unable to make Camera as child object of a Player in FPS. The objects in scene where always flickering, etc.. so trying to understand now how it all works. I have done tons of 2D movement/cameras, learning the 3D these days for the first time.

#

Thanks both for your advices, going to check on that and try it.

#

Also appreciate pointing out the best practices on where to use the deltaTimes. Thank you!

tidal shadow
#

has anyone ever seen this type of behaviour?
never seen meshes do this kind of blinking thing
all my code that affects the character is disabled
the only thing i do, is spawn the character in which worked with no problem before i imported this character
there cant be a script inside the fbx model already can there?

seems like it was due to an animation it was uploaded with
removed the animation it had and now it no longer flickers

dawn sundial
#

I applied the changes and I think I alrady had it this way. Unfortunatelly now the object edges are flickering :/

young moon
#

Hello, I'm making a puzzle game that has daily levels. I have daily levels made for around 2 years but how would I best cycle through them? I was thinking of using the date together with the daily levels being in resources (they're json files) and then either having them all on a list, using Resource.Load or learning about Addressable.
My question is what would be the most efficient solution as I'll have 8 daily levels per day so I have a lot of files to work with.

deft timber
#

asset bundles, addressables

#

for sure not Resource.Load

#

or json as you said

hard estuary
# tidal shadow has anyone ever seen this type of behaviour? never seen meshes do this kind of b...

In the past I've seen similar issues when someone added some sort of culling that was triggered by transparent objects.
In your case it's most likely badly implemented animation. Try putting the object on empty scene and see if it still flickers. If it's the case, I would suggest opening the animation in some sort of animation editing program and checking if everything is correct (e.g. scale is not set to 0 in some frames).

tidal shadow
hard estuary
gray mural
#

Hello, in my script I'm calculating the difference between start and current Rounded mouse position and assigning this Vector3 to my GameObject's Transform. Everything works fine when I assign Transform.position

item.transform.position = position;

But assigning Rigidbody2D.position makes my item go farther from the mouse every time if I move my mouse fast enough.
What's the reason?

item.rigidbody.position = position;
jovial spear
thin aurora
jovial spear
#

& is safe?

thin aurora
#

No

#

You can assume that any special character except for - and _ is illegal

young moon
leaden ice
jovial spear
#

thanks, i'm renaming everything

hard estuary
# young moon I love the idea of adressables based on what you said but don't think it sounds ...

I think databases are nice for projects that might want to update and/or download the data independently. E.g. you could update levels in external programs or let players upload their own levels. But if you don't need such features, I would probably abandon the idea of database. But if you're considering it, I would probably suggest using Firebase, because it has some support for Unity and there are some tutorials available.

When it comes to addressables, it's worth to mention you can include all of them in the initial build. I also think it would be easier to manage files compared to the Resources.Load.

leaden ice
young moon
jovial spear
#

I still have this problem!

#

no illegal character in the assets folder

hard viper
#

is there a way to disable a field in inspector if a given component is on the gameobject?

rigid island
#

custom inspector

hard viper
rigid island
#

they're not hard to make

#

just a pain in the butt

hard viper
#

i would honestly like an attribute to “disable if has component”

rigid island
#

I always do the question "Is this gonna benefit me in the long ? is it worth my time making it vs time saved using it?"

#

or if you're working with game designers I suppose

hard viper
#

the answer for me is very much no

rigid island
#

so don't do it lol

elfin quest
#

xd

swift falcon
#

Can anyone tell me how I can fix these errors?

polar marten
jovial spear
#

oh

#

old code

polar marten
#

you probably want to remove it if you don't use it

jovial spear
#

yeah

gray mural
quick elbow
#

Why is my trail renderer only showing a tiny bit? I have time set to 10 seconds, and it is not lasting 10 seconds. Any ideas?

#

Also please forgive the extremely blurry second photo 😄

latent latch
#

Have you played with the curve? Maybe related

leaden ice
quick elbow
#

My objects are very tiny

#

Is that a problem?

leaden ice
#

potentially

#

that's really small

#

floating point precision will be a huge problem

quick elbow
#

Yeah... I'm displaying objects on a map in Unity where the map is 1m, so the aircraft are very small

leaden ice
#

Sounds like you're trying to sneak your way around doing a real floating origin implementation?

#

try making your objects bigger temporarily and see if the trail renderer is fixed

#

just to see if that's the problem

quick elbow
#

Not really. It's for an AR app. So I have a 1 meter map. And I need to see the aircraft on the map. The aircraft models are tiny. Like .004 meters or possibly smaller

swift falcon
quick elbow
hard viper
#

remember floating point precision is about relative values

#

single precision floats have significand holding the equivalent of 7 decimal digits

#

but they get sparser/denser depending on the order of magnitude

#

if the numbers are 1 vs 0.0002, there should not be issues with floating point precision

quick elbow
#

I tried making the width .01 and the min vertext distance .01, which sould be fine I'd imagine. And I have the same result. Unless it's because the object is moving very small amounts?

#

I imagine that is likely the culprit

hard viper
#

how big is the world?

#

like, what would constitute a typical big number in the game world

#

are your transforms at positions with x like 1000?

quick elbow
#

No they are very tiny. They move like .0001 every second

hard viper
#

but what is the actual raw position of the transforms

quick elbow
#

Changing the trail renderer time to something absurdly large like 500 seems to work. I just don't understand why

thick socket
#

if I set prevousHeadRotation = headrotation and headrotation changes...will prevousHeadRotation change also?

Quaternion headrotation;
    Quaternion firepointRotation;
    Quaternion prevousHeadRotation;
    Quaternion prevousFirepointRotation;
quick elbow
#

something like 0.5321234

#

Is how many decimal places

leaden ice
quick elbow
#

That is the Y value of one of my obejcts for example

hard viper
#

ok, so if all the numbers are within a few orders of magnitude of each other, then floating point precision shouldn’t be an issue

thick socket
quick elbow
#

x is like -0.04383245

#

Anbd they move about .001 a second

hard viper
#

just for reference: subtraction is a shitty opperation, because it gets unstable if you have big numbers thag are very close together.

quick elbow
#

Let me check, I don't believe so

#

is there a way to view in editor? Or do I have to log it?

leaden ice
#

but if your code is setting it you won't see it there, not until runtime at least

hard viper
#

i think I understand now. And I agree with Praetor that your timescale is a likely issue

strange scarab
#

I have a 2D collider and when a player enters it I set the position of a particleSystem to that player. I'm not sure how to make it work for two players since it switches position between two players in collider.

leaden ice
strange scarab
#

Maybe I should store the particles in a dictionary and have the key be the players name and value be the newly created particlesystem so I can refer to the particleSystem for that player without interfearing with another players particles

#

Time to find out if c# has dictionarys

knotty sun
#

why not just put ther particle system on your players?

strange scarab
#

Because then the particles behave unnaturally when on player

#

and rotate with player

knotty sun
#

that is just a question of organising your hierarchy correctly

strange scarab
#

If I placed it directly on player it rotates with player so cant have that

latent latch
#

There's a few ways to forgo the rotational constraints

knotty sun
obtuse cape
#

When pressing player, my enemy navmesh agent's patrol point seems to moving extremely far away. how can i fix this?
here is the code

tawny elkBOT
strange scarab
#

If I could stop it from rotating somehow it would fix my problem

knotty sun
#

Parent
--- Player who rotates
--- Empty with Particle System

latent latch
#

Steve actually has the best solution if you can go about it, but make your character model and target particle object siblings at most

obtuse cape
leaden ice
dusk plume
#

why i can't add 2d character controller

leaden ice
#

Not built into Unity anyway

strange scarab
dusk plume
leaden ice
dusk plume
#

look

obtuse cape
#

Why is my navmesh agent moving very far away from the baked navmesh surface

dusk plume
#

that's a triangle

#

i want to do it collide with the 2d box

latent latch
dusk plume
#

i am beginner to 2d unity so idk how to do it

leaden ice
#

use a Rigidbody2D and a CapsuleCollider2D

#

CharacterController is only for 3D

gray mural
dusk plume
#

i am very dumb

#

thanks you for the informations anyway

#

have a nice day

#

🙂

strange scarab
#

If I want to destroy a particle stored as the value in a dictionary can I just get the key and destroy it?

#
 Destroy(particleDictionary[collision.gameObject.name]);
leaden ice
#

also you shouldn't use name as the key

#

just use the GameObject itself

simple egret
#

(Know this will throw an exception if the key is not present in the dictionary at the time this instruction is executed)

strange scarab
#

it's a string as key then particleSystem as value then I'm removing it from dictionary after destroying it

leaden ice
#

string key isn't good

#

names are not unique

#

and also .name produces garbage

#

the object itself is a fine key and more performant too

strange scarab
#

alright so if collision objects are unique ill use that thanks

leaden ice
#

ooh actually this is probably the cutest way:

if (particleDictionary.Remove(collision.gameObject, out GameObject particleSystem)) {
  Destroy(particleSystem);
}```
strange scarab
#

you don't have to loop through the dictionary to remove key values I thought

leaden ice
#

Where do you see a loop?

#

There's no loop here

#

loops are for while foreach and do : while

strange scarab
#

oh nvm awesome

#

you get a gold star

quick elbow
#

As I mentioned previously, changing the Time value in the TrailRenderer to something high like 50 seems to work, but it doesn't make sense to me since my timescale is 1

main coral
#

if (Time.time > ShootConfig.FireRate + LastShootTime Does this not work for networking ?

#
    private void FireNewBulletServerRpc()
    {
        if (NetworkManager.LocalTime.Tick > GunSelector.ActiveGun.ShootConfig.FireRate + LastShootTime)
        {
            LastShootTime = Time.time;
            GameObject go = Instantiate(TestPrefab, transform.position, Quaternion.identity);
            go.GetComponent<NetworkObject>().Spawn();
        }
    }```

I have the problem on the host the prefab is spawning 10 times ..
obtuse cape
#

I keep having an error saying ""SetDestination" can only be called on an active agent that has been placed on a NavMesh."
Even though I have assigned the robot onto the baked navmesh, How can I fix this error?

spring creek
obtuse cape
#

Code link ^

#

Navmesh bake

simple egret
#

Example NavMesh (source: Brackeys tutorial)

#

Successfully baked areas will be blue - you don't have any here

spring creek
magic wolf
#

What's wrong here

simple egret
#

Taking pictures of screens obviously :)

#

The exception happens on line 193, you're trying to access something on null

somber nacelle
magic wolf
#

Istg 😂

#

What's wrong with the code. Not my dirty screen lmao

#

Oh ok I see the second link

somber nacelle
#

for future reference, look below to see how to share !code 👇

tawny elkBOT
magic wolf
#

So is it my hit that is throwing error when there is not a hit?

misty ibex
#

Hey all, i seem to be having trouble with a BinarySpacePartitioning algorithm, in that i am trying to add a "room offset" parameter that gives some space between the rooms im splitting, but it seems that while it does give me more space between rooms, it's making all of the rooms smaller, which if you turn up the offset high enough, leaves empty/"zero" space rooms. I took the algorithm from a youtube tutorial, and one of the comments bought up this issue, saying that its due to how in the "makeSimpleRooms" function, the for statements are only executed (room.size.x - offset - offset) times. This means that when the offset is greater than 0, it reduces your available space by 2 * offset for both the width and height. The comment mentions that a simple fix could be to include the offset into the BinarySpacePartitioning() parameters, but I'm a bit lost on how exactly to do that. I've tired to add or multiply the dungeon size by the offset, but this still leads to microscopic rooms if the offset is high enough. Do you all have any suggestions? here are the scripts and some pics of the issue, thanks for your time.
https://gdl.space/vibibahiyo.cs , https://gdl.space/oqajizujol.cs

somber nacelle
magic wolf
#

The if is 193

#

I don't have another way to share it right now. No wifi.

#

I'm not going to rewrite all the code on my phone to make it more readable

#

Never mind ill ask somewhere else 😂

#

This is pointless

somber nacelle
#

okay that's fine. you have the link i provided to you that will help you figure out what is causing the NRE. i don't speak for everybody, but i'm sure most people don't want to try reading a blurry, dusty photo of a screen

magic wolf
#

Good luck with ur issue

#

Well u aren't most people. You are you. You gave your input now I am looking for helpful input. You've made it clear you don't want to help if it is inconvenient then asked for help on something else? Ok entitled much 😂

pearl otter
#

I think? I'm not fully understanding your code and why you're iterating the number of roomOffset

misty ibex
pearl otter
#

Yeah I see that.

spring creek
pearl otter
#

I'm currently just trying to understand the makeSimpleRooms function

misty ibex
#

ahh i see, lemme rewatch the tutorial i followed and see if that sheds some light on it, maybe i misunderstood something

magic wolf
somber nacelle
spring creek
#

Yeah, that was a super weird overreaction...
We can still help if you want
Either way, best of luck!

magic wolf
pearl otter
#

@misty ibex Can you try this code and see what happens?

private HashSet<Vector2Int> makeSimpleRooms(List<BoundsInt> roomsList)
{
    HashSet<Vector2Int> floor = new HashSet<Vector2Int>();
    foreach (BoundsInt room in roomsList)
    {
        for (int col = 0; col < room.size.x; col++)
        {
            for (int row = 0; row < room.size.y; row++)
            {
                Vector2Int pos = new Vector2Int(room.min.x + col + roomOffset, room.min.y + row + roomOffset);
                floor.Add(pos);
            }
        }
    }
    return floor;
}
magic wolf
#

But regardless that resource was not helpful 😂 I don't know if it's because I'm on phone or if somehow it's supposed to be helpful that it says the exact same thing that my error line says. All it does is explain what a null reference is. Which I know. But I don't know why I have a null ref

simple egret
#

What your raycast hit didn't have a rigidbody, it seems

misty ibex
simple egret
#

Attempt to get .gameObject on a null reference throws that exception

magic wolf
#

You did nothing Carby ❤️

somber nacelle
pearl otter
#

@misty ibex I am curious, what kind of game are you creating?

misty ibex
spring creek
pearl otter
magic wolf
#

Right

magic wolf
#

The second one down should do

spring creek
misty ibex
# pearl otter <@126850720233160704> I am curious, what kind of game are you creating?

im creating a top down shooter rougelite with procedurally generated levels. It was supposed to be for a game jam but i entered way too late and only started working on it at the last minute, but realized there wasn't enough time to finish the game i wanted to submit, so i simply has to withdraw, however, i am going to keep the project as this exact idea was gonna be my first "commercial" game anyways. So it all works out, heh

somber nacelle
# magic wolf I don't see those on my phone

if you truly do not see those links then you should report an issue on the page. i'm sure vertx would want to know that it's apparently not working on whatever device you are using. click the sidebar button at the top right and there will be a report an issue button

misty ibex
#

i don't just copy code and not learn from it, i like to learn what it's doing, ya know? but it seems that i coded this part of the generation on a late night and maybe didn't understand what exactly was going on

#

i am trying your code now

pearl otter
#

Ah thats cool. Let me know the result of using the code I sent,

pearl otter
misty ibex
#

i could maybe learn from reading a few papers but hey, if there's a tutorial on it might as well us that as a springboard

#

The tutorial is pretty good, just has this one little hiccup. at the very least it helps me understand the algos i need and how to put it all together

#

that's all development is after all, its all a big puzzle

#

its all problem solving

pearl otter
#

For sure

golden garnet
#

Hey! Right now I'm trying to program in something to stop my camera from clipping into walls in my 3D platformer. As of right now, however, I'm not using Cinemachine. This project is pretty far along so I'm trying not to switch since it would mean refactoring a bunch of code thats already written, so I was hoping I could find a fix that I can implement into my camera as-is?

somber nacelle
#

you would likely need to use physics queries like raycasts/boxcasts/whatevercasts to check when the camera would collide with something when you move it

#

it's basically the same concept as manually checking for collisions when moving an object without physics

#

but the better answer, while it may take a bit of refactoring, would be to just use cinemachine which already has some components for that

golden garnet
#

My camera is set up like this. The main cam is attached to a parent object that has a script that controls its offset from the player. The camera itself has a script on it that allows the player to move it using the mouse and scroll wheel.

misty ibex
golden garnet
#

zAdding a collider doesn't work since the movement of the camera is basically teleportation so collisions wont matter unfortunately

delicate flax
# golden garnet Hey! Right now I'm trying to program in something to stop my camera from clippin...

creating a camera is surprising, extremely complex.. that's why something like chinemachine exists 😅
not a code example, but this might help you out with creating a good custom camera, looking at what do to and not do, etc, etc

https://www.youtube.com/watch?v=C7307qRmlMI

GDC

In this GDC 2014 talk, John Nesky, the dynamic camera designer for thatgamecompany's award-winning PSN title Journey, takes attendees on a tour of all the poor camera choices that he and other game developers have made, and most importantly, how to fix them.
GDC talks cover a range of developmental topics including game design, programming, audi...

▶ Play video
golden garnet
somber nacelle
golden garnet
somber nacelle
#

i don't know of any specific resources that will teach you how to use raycasts and the like other than just looking at the docs 🤷‍♂️

misty ibex
# pearl otter Haha

i think you are on to something, the issue lies in the MakeSimpleRooms() function

#

in that i have to find a way to properly introduce the offset. All the offset should be doing is basically splitting the rooms apart from each other

golden garnet
pearl otter
#

What if you just do this?

Vector2Int pos = (Vector2Int)room.min + new Vector2Int(col + roomOffset, row + roomOffset);```
misty ibex
#

let me see if that helps

misty ibex
#

as in are my for loops starting at 0 or at the offset

pearl otter
#

Original code

pearl otter
#

You should only be using roomOffset in Vector2Int pos = (Vector2Int)room.min + new Vector2Int(col + roomOffset, row + roomOffset);

#

Although I believe that is doing what your code edited code would do, just in a different way 🤔

misty ibex
#

so i guess starting the for loop at the offset for some reason... works... ???

pearl otter
#

That is really strange

misty ibex
#

yeah

#

i think i know vaguely what;'s going

pearl otter
#

The only thing I can think of is it being something with room.min

pearl otter
misty ibex
#

essentially, the offset does separate the rooms from each other, but that comes at the cost of the blank space taking up the allocated "dungeon space"

#

in the comments of the video, someone pointed out this flaw, which is how i noticed, and they called it a "small flaw" that they think could be fixed by using the offset in the BSP() algo

#

though, im trying to figure out how that would work

pearl otter
misty ibex
#

here's exactly what the comment said:
1) In RoomFirstDungeonGenerator, the function CreateSimpleRooms does not create rooms of the minimum size. Indeed, it seems to me that the loop: for (int col = offset; col < room.size.x - offset; col++) is executed (room.size.x - offset - offset) times, which is fine when offset is zero, but reduces width (same for height) by 2 * offset. The most visible consequence is the reduction in the number of parts when the offset is increased, down to a zero number of parts. I would wait to see the end of the series to remove this small flaw, I think by adding the offset to BinarySpacePartitioning() to take it into account.

misty ibex
#

@pearl otter also interestingly enough, with the original code, the for loop runs for about 2200ish times with a offset of 2, but only about 240ish times with an offset of 5... while with edited code you suggested, it runs for 4900 times on the dot, no matter the offset

pearl otter
#

That is strange. I need to go for a bit but I asked chatgpt and it gave me this code. I don't think it will work but it would only take a second to test.

private HashSet<Vector2Int> makeSimpleRooms(List<BoundsInt> roomsList)
{
    HashSet<Vector2Int> floor = new HashSet<Vector2Int>();
    foreach (BoundsInt room in roomsList)
    {
        for (int col = room.min.x; col <= room.max.x; col++)
        {
            for (int row = room.min.y; row <= room.max.y; row++)
            {
                if (col < room.min.x + roomOffset || col > room.max.x - roomOffset ||
                    row < room.min.y + roomOffset || row > room.max.y - roomOffset)
                {
                    Vector2Int pos = new Vector2Int(col, row);
                    floor.Add(pos);
                }
            }
        }
    }
    return floor;
}
misty ibex
#

i appreciate your help but if you're just gonna run it past a damned AI i might as well just figure it out myself

foggy maple
#

especially to help others

misty ibex
#

also, i think it would be helpful if you could tell me your logic/reasoning for your suggested edits, instead of just providing me the code

#

i really do appreciate your help on this and it's a tough pickle to be in, but i rather stuff be explained to me so i learn rather than just being given the answer

#

ya know?

misty ibex
#

if it does im eating my hat

#

and i don't even wear a hat

misty ibex
#

yeeaaaa i don't think ChatGeePeeTee is gonna be of much use here

#

I appreciate it tho, i'll give it to ya that i don't pay for ChatGPT4 so thanks for asking that for me, at least

#

but no cigar

misty ibex
#

wait

#

actually i messed up the implementation lemme try again

#

okay fixed my error (forgot to comment out my original code lawl) and....

pearl otter
misty ibex
#

i mean, it's a result