#💻┃code-beginner

1 messages · Page 412 of 1

hasty sleet
#

Anchors and pivots need to be tweaked here, and the position of the object should not be set using an absolute Vector

safe radish
#

first screenshot is from Z- and X+, the second is from Z+ and X-, i cant figure out how to correct the offsets for the other side @hasty sleet

safe radish
#

im trying to map 1 voxel to .25 of the uv map ( 1 voxel has 4 colored squares on it with this texture )

full kite
#

i setted them to be on the top left

river quiver
#

So i added the code to this function which runs only when the object enters the other object and its still the same

{
    if (collision.gameObject.layer == 3)
    {
        gameManager.addScore(multiplier);
        if (gameManager.playerScore >= 10 && gameManager.playerScore % 10 == 0)
        {
            pipe.moveSpeed += 1;
        }
    }
}```
full kite
#

I swithced the Render Mode to World Space, its making a difference but not quite

inner quartz
#

Guys how do I can open the panel which name is = button name was clicked

full kite
#

Cause if anybody has a phone that has low length and more height then it wont be displayed on it

hasty sleet
umbral rock
#

i have done this but i dont have intellisense

inner quartz
#

    public void OpenClosePanel(string buttonName)
    {
        Panels[buttonName].SetActive(true);
    }```
Guys how do I can open the panel which name is = button name was clicked
umbral rock
#

still dont have intellisense

slender nymph
#

either you missed a step (like restarting your PC after the .net sdk was installed) or you need to regenerate project files and restart vs code

safe radish
#

!code

eternal falconBOT
umbral rock
#

do i NEED to install sdk?

hasty sleet
hasty sleet
safe radish
slender nymph
full kite
#

if I remove that line, the new gameobject wont be positioned

umbral rock
slender nymph
#

if only there were instructions for how to configure vs code for use with unity

inner quartz
slender nymph
#

if you cannot figure it out from those instructions, then consider switching to visual studio which is far easier to configure and keep configured

hasty sleet
# inner quartz And... how to implement this?
private GameObject _specificPanel
public SomeClass : MonoBehaviour
{
    public void OpenSpecificPanel()
    {
        _specificPanel.SetActive(true);
    }
}

// Set the button configuration in inspector to each panel
safe radish
#

@hasty sleet i think the issue is im not using the + tileSize at the correct positions. but i cant wrap my mind around where they should go

swift crag
#

It does recognize them -- it won't warn if they are unused

#

but it doesn't show up in the suggestion list

outer coral
#

Is there a way to trigger animations without using strings or is that not possible

umbral rock
#

same, like even the input....

hasty sleet
# inner quartz I don't want make new void for every button and panel ._.

UI can be tedious. You could generate a mapping, like you are doing in your code above, from the string button to a panel name, and use a dictionary to map button names to panel names. This would be more efficient, but your code would be a little more brittle since changing the button name by a single character would change the logic.

umbral rock
#

input.getaxis isnt recognized

swift crag
#

oh, well then it's just set up wrong

umbral rock
#

but how? i get the normal intellisenses... i followed tutorial on yt but it stays the same

summer stump
summer stump
full kite
#

@hasty sleet With that line, Im setting the position of the gameobject that was created during the script
if I remove that line, the new gameobject wont be positioned

umbral rock
swift crag
#

!ide

eternal falconBOT
swift crag
#

follow every single step in the VS Code link

#

do not skip any of them

#

do not re-interpret any of them

hasty sleet
summer stump
inner quartz
hasty sleet
#

If you set the absolute position of a UI element, it will not sync up with elements that scale with the canvas

full kite
#

its behind the background somehow

hasty sleet
#

@safe radish Upon reviewing your code, it does look like your +tileSize is at the wrong position.

Try moving the +tileSize to the other vector coordinate for the incorrect faces.

safe radish
umbral rock
#

intellisense works, thanks guys!

inner quartz
#

where I can ask about problem why if I want to open my project I need to wait like 30 minutes before open it

full kite
#

i dont get tho why is it behind?

#

and how can I put it in the front

hasty sleet
# full kite

The layering of GameObjects is due to their order of instantiation in the object hierarchy.

swift crag
#

yes: parents go behind children

#

and earlier children go behind later children

hasty sleet
#

transform.SetAsLastChild(); works

#

If there are different parents, then you need to reconcile that separately by reordering the parents or by changing the camel sprite's location in the object hierarchy.

inner quartz
#

where I can ask about problem why if I want to open my project I need to wait like 30 minutes before open it?

full kite
#

Ok so in the hierarchy they are good in order

#

LIke that thing is below it so basically in the layering he should be on top

#

but its not

#

even disabling the bg

hasty sleet
full kite
#

its not showing anything

#

with the bg

hasty sleet
full kite
#

without the bg

hasty sleet
#

oop

#

I think the camel has an additional Image element somewhere in it

full kite
hasty sleet
#

Because a white image is the default value of an image component

full kite
#

Indeed

#

It has Image but its still under it

hasty sleet
#

Delete or disable the extra image component and the camel will be displayed

full kite
#

so now by disabling it

#

its looking like this

hasty sleet
#

Voila!

full kite
#

still behind the bg

#

with the bg on its looking like this

hasty sleet
#

Hm, that's not expected. The background image is in BG, right?

full kite
#

indeed

#

these type of things are blowing my mind

hasty sleet
full kite
#

Exactly as it used to be

hasty sleet
#

Try manually recreating the camel sprite by hand, place it into the correct position, and check whether it's in front of the background (correct) or behind the background

#

This is trying to establish a passing case first, and then we can identify discrepancies

#

@full kite Change Render mode to Screen Space - Overlay

swift crag
#

Are any of these things even images?

#

or are they sprite renderers?

full kite
#

sprite renderers

swift crag
#

sprite renderers are not UI components

#

If you want to use sprite renderers, get rid of the canvas entirely.

#

just physically position the objects correctly in the world

full kite
#

yea its working

#

so it needs to be an image

#

so now we are above

swift crag
#

Trying to position the objects on a "Screen Space - Camera" canvas means that the canvas is sliding all over the place as the camera moves and the game changes resolutions

full kite
#

Now i need to know how to positionate the Image in the script

hasty sleet
#

What's the actual use case for screen space - camera?

full kite
inner quartz
swift crag
#

I mostly use Overlay mode, so that the canvas is drawn directly onto my screen on top of everything else

hasty sleet
full kite
#

How can I move my image inside of the script?

#

like to set it at a X and Y inside of the script

swift crag
swift crag
hasty sleet
swift crag
#

then you can just parent an image to one of those points and set its local position to [0,0,0]

hasty sleet
#

I think you might be able to get away with setting its local position to a slight offset above the carpet, or you can create another object child to the carpet where the camel should go.

full kite
#

yeah indeed

#

i need to set it a bit above the carpet

hasty sleet
#

position = [0, 5, 0] should work fine for canvas rescaling as long as the parent object is not set absolutely

full kite
#

so now, when spawning it

#

its spawning like this

#

(in the left side of the carpet, using pivot and anchor)

hasty sleet
#

Your anchor/pivot seems to be at (0, 0)

#

Try a pivot of (0.5, 1)

inner quartz
# hasty sleet 8-10 is frankly not that many scripts. I'm going to guess you have either a low-...

Let's take it in order... I recently bought a new disk with 1 terabyte of space. The project weighs less than 1 GIGABYTE of space. As for the performance of the computer, I can't say anything, I don't understand it. But I also noticed that when exporting a project, an error crashes after more than an hour of loading (in the screenshot). I do not know what kind of error it is, but it looks like unity is going to delete itself.

full kite
hasty sleet
hasty sleet
full kite
#

by default

inner quartz
full kite
#

i cant even modify it

#

if i press 0

#

then it goes back to 06

#

because of the anchor

hasty sleet
#

Try setting pivot y-value to 1

full kite
#

its -6

umbral rock
#

trying to use rb.position.y but he says i cant use it bcs it is not a variable?

hasty sleet
#

I'm not great at messing with anchors tbh

full kite
#

and now his legs are under the carpet

hasty sleet
summer stump
full kite
#

nevermind

#

resolved them

#

resolved the carpet

#

i got another carpet that was above that thing

umbral rock
rich adder
summer stump
inner quartz
#

new project was loaded in 10-15 seconds @hasty sleet

hasty sleet
#

❌ for accessing an object's y-coordinate by using transform.position.y or rb.velocity.y to get the values? These are valid

summer stump
#

You cannot write to .x .y. or .z

umbral rock
rich adder
full kite
#

damn

#

@hasty sleet all my respect ✌️

summer stump
hasty sleet
rich adder
#

make a copy, modify the prop u want and assign it back

#

literally

umbral rock
hasty sleet
rich adder
#

rigidbody.position is also a vector3

umbral rock
#

why cant i use rb.position then?

rich adder
summer stump
hasty sleet
#

rb.position returns a temporary value

inner quartz
hasty sleet
umbral rock
#

im trying to make an if function, so if the rb.position.y = 0 then im gonna set isGrounded = true

hasty sleet
#

I recommend making a new project and bringing your assets over and seeing what causes the performance bottleneck

summer stump
#

You can READ the components no problem

#

You cannot WRITE to them individually though, and that is what we thought you were trying to do

full kite
#

and now coming back Travis. Something is messed up with the drag of the gameobject part of script 🤣

umbral rock
hasty sleet
#

!code

eternal falconBOT
summer stump
#

= is not ==

#

And do not ever take a photo of your screen.

umbral rock
#

sorry lol

raw token
#

It steals your monitor's soul

full kite
#

@hasty sleet

#

it has to be a sprite renderer

hasty sleet
#

Why

full kite
#

can you detect collisions between Ui things?

swift crag
#

If they're supposed to be physical objects, and not a user interface, use sprite renderers.

hasty sleet
#

If you're making a 2d game, it's not UI

swift crag
#

But this means you need to get rid of the canvas.

full kite
#

So I need to get rid of the canvas, in order to use sprite renderers

#

and also to see them

#

in order to use trigger methods

#

in order to detect collisions

hasty sleet
#

You need to not use a canvas if you're going to use sprite renderers or aspire to have collisions on it

#

You can have a canvas and use it, but it can't be for sprite renderers or anything involving collision detection.

full kite
#

and how can I change that canvas

hasty sleet
#

Because UI is not for physics logic, but just for displaying information to the user and capturing user feedback

full kite
#

this is my main question

hasty sleet
#

Remove the canvas elements and they shall cease to exist

full kite
#

remove those things from the canvas?

#

or remove all of them?

hasty sleet
#

Remove background, remove camel, remove platform

#

Since I think you were treating UI as a 2d surface instead of as it was intended

full kite
#

and then have nothing?

#

to the screen?

swift crag
#

if you don't know what's going on here then i highly suggest stopping what you're doing and using !learn

eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

full kite
#

ummm, Im trying my best to understand @swift crag tbh. I used Canvas on all of my projects and this is the single one that I meet problems with

hasty sleet
umbral rock
#

to learn c# and unity, do u need to put in alot of time? or can u get good with a few times a week? or do u rly need dedication and time to put into it other wise u'll forget alot?

full kite
#

Ok, my main question is: How it worked before?

#

How could I use SpriteRenderer on Canvas and get Collisions

#

Why could I see the sprite of the Sprite Renderer if I used that code with Vector3 and offsets?

#

And now all of a sudden, nothing is working

swift crag
#

you shouldn't use sprite renderers on a canvas

#

It makes no sense

summer stump
swift crag
#

a Canvas's job is to draw UI graphics

#

SpriteRenderers are not UI

umbral rock
swift crag
#

SpriteRenderers are sorted based on distance to the camera, not their order in the hierarchy

twin bolt
#

How can i use Random.Range, to pick a number between 0,9 but exclude a certain number.

summer stump
swift crag
summer stump
swift crag
#

tbh i'd just do rejection sampling

#

yeah

twin bolt
swift crag
#

I guess you could do Random.Range(0, n-1) and then add 1 if the result is greater or equal to the excluded number

summer stump
swift crag
#

no, it's accurate

hasty sleet
safe radish
#

@hasty sleet i got them all in the correct scale and tiling. but i have them mirrored on the Z+ and X- now

summer stump
# swift crag no, it's accurate

Well wouldn't it be able to land on oke over naturally, then also a second chance in landing on the rejected number ALSO resulting in one over

So a slight increase in chance on that specific offset

hasty sleet
swift crag
#

if you exclude 5, then you're remapping like this:

0 1 2 3 4 5 6 7 8
0 1 2 3 4 6 7 8 9

summer stump
swift crag
#

right

summer stump
#

Got it. Even smarter

swift crag
#

anything 5 or greater

hasty sleet
#

Yes

swift crag
#

For anything more complex I'd just do rejection sampling

safe radish
#
                uvs.Add(new Vector2(uOffset, vOffset + tileSize));               //0,1   Bottom Right    2
                uvs.Add(new Vector2(uOffset, vOffset));                          //0,0   Bottom Left     1
                uvs.Add(new Vector2(uOffset + tileSize, vOffset));               //1,0   Top Left        3``` i still cant visualize it from this code, i should just swap 2 top ones and bottom ones from this?
#

as in swap top right with top left and bottom right with bottom left?

hasty sleet
rocky lava
#

Ok so i made a script that connects the position of an object to the ui, but the tutorial i followed with a drag and shoot mechanic wasnt working entirely so i had to improvise and now it only works on one side, meaning that my score goes into the -. is there any way to get rid of the - so it looks normal?

dry tendon
#

I know this is not the right channel... But the UI toolkit one is not red by anyone... So could anyone help me with this? #🧰┃ui-toolkit message

swift crag
#

For a moving object, I would store the player's last hand position in the local space of the object

#

That way, if the object moves, the player will naturally follow it

#

You can use transform.InverseTransformPoint to go from world to local, and transform.TransformPoint to go from local to world

#

So if you grab an object, and then the object suddenly moves 1 meter to the right, you'll correctly conclude that the player needs to move 1 meter

fervent abyss
swift crag
#

No, you need to get the transform of the thing you're grabbing

#
lastHandPos = grabbed.InverseTransformPoint(handPos);
#

Then, in the next physics update, convert that back to world space

fervent abyss
#

hm let me try

swift crag
#

This will correctly handle translating/rotating/scaling the cart

fervent abyss
swift crag
#

Transform.InverseTransformPoint takes a world-space position and returns a local-space position

umbral rock
#

i have an rb.addforce(new vector2 and then on the y axis i have jumpHeight but idk what to put on the x axis because its really glitchy, i want to put the current x axis speed but i dont know how, and if i jump and i go left or right i am floating lol

bitter root
#

im having a problem, i followed the brackeys tutorial using player controller for 3d player movement, https://gdl.space/vuborozike.cpp this is my code, but the problem is when i go backwards then its kindof funky, and when i jump backwards and move my mouse downwards then i go really high, and when i point my mouse down then i cant jump at all

swift crag
#

remember newton's first law: an object in motion stays in motion

#

if you don't want to change the horizontal speed, don't apply any force

fervent abyss
swift crag
#

again, it converts a world-space position into a local-space position

#

the result is a position in the local space of transform

#

You then convert it back when you need it

umbral rock
fervent abyss
#

its 3am im stupid rn

swift crag
#
transform.TransformPoint(transform.InverseTransformPoint(foo)) == foo
swift crag
umbral rock
vapid yew
#

I understand the difference between a double and a float with a few exceptions.

Does defining a variable like this have any impact? Do I need to always suffix these numbers with f?

float foo = 1;

In examples similar to the below mentioned, is the number 1 getting compiled differently? Is this format to my disadvantage?

float foo = .5f;
foo += 1;

float bar = .5f;
bar = foo + 1 + .5f;

Is there any reason as to why I should put the f after a "whole number" float?

fervent abyss
swift crag
fervent abyss
#

like i got 2 separate scripts, 1 is for the whole locomotion, and 2nd is for minecart controller (that im trying to grab and follow)

umbral rock
# swift crag show your entire script.

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

public class MyMovement : MonoBehaviour
{

public float speed = 10f;

public float JumpHeight = 10f;

private bool inAir = false;
[SerializeField] private Rigidbody2D rb;



// Start is called before the first frame update
void Start()
{
    Debug.Log("Game has started: ");
}

// Update is called once per frame
void FixedUpdate()
{
    if (Input.GetKey(KeyCode.D))
    {
        rb.velocity = new Vector2(speed, 0);
    }

    if (Input.GetKey(KeyCode.Q))
    {
        rb.velocity = new Vector2(-speed, 0);
    }
    if (Input.GetKeyDown(KeyCode.Space) && inAir == false)
    {
        rb.AddForce(new Vector2(0, JumpHeight));
    }
    

}
private void OnCollisionEnter2D(Collision2D other) {
    if(other.gameObject.name.Equals("Floor")){
        inAir = false;
    }
}
private void OnCollisionExit2D(Collision2D other) {
    if(other.gameObject.name.Equals("Floor")){
        inAir = true;
    }
}

}

swift crag
#

!code

eternal falconBOT
umbral rock
#

oh sorry

swift crag
#

Rider doesn't indicate a conversion is happening

#

But we should look at the compiled IL to be sure.

sand heath
#

Implicit vs explicit and such

umbral rock
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MyMovement : MonoBehaviour
{

    public float speed = 10f;

    public float JumpHeight = 10f;

    private bool inAir = false;
    [SerializeField] private Rigidbody2D rb;


    
    // Start is called before the first frame update
    void Start()
    {
        Debug.Log("Game has started: ");
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        if (Input.GetKey(KeyCode.D))
        {
            rb.velocity = new Vector2(speed, 0);
        }

        if (Input.GetKey(KeyCode.Q))
        {
            rb.velocity = new Vector2(-speed, 0);
        }
        if (Input.GetKeyDown(KeyCode.Space) && inAir == false)
        {
            rb.AddForce(new Vector2(0, JumpHeight));
        }
        

    }
    private void OnCollisionEnter2D(Collision2D other) {
        if(other.gameObject.name.Equals("Floor")){
            inAir = false;
        }
    }
    private void OnCollisionExit2D(Collision2D other) {
        if(other.gameObject.name.Equals("Floor")){
            inAir = true;
        }
    }
}



swift crag
#

That's a large amount of code

umbral rock
#

this is my code 🙂

swift crag
#

please use a paste site

sand heath
#

if you do

var foo = 1
var bar = 1f

it will know that bar is a float

umbral rock
safe radish
#

@hasty sleet uOffset = (adjPos.z % tilingFactor) * tileSize; vOffset = (adjPos.y % tilingFactor) * tileSize; uvs.Add(new Vector2(uOffset + tileSize, vOffset + tileSize)); //1,1 Top Right 4 uvs.Add(new Vector2(uOffset, vOffset + tileSize)); //0,1 Bottom Right 2 uvs.Add(new Vector2(uOffset, vOffset)); //0,0 Bottom Left 1 uvs.Add(new Vector2(uOffset + tileSize, vOffset)); //1,0 Top Left 3 im sorry but i still havent figured it out, if this order is 4213, what order would mirror it?

umbral rock
#

@swift crag its on the addforce function

vapid yew
sand heath
swift crag
#

sort of; it's part of a numeric literal

#

we're breaking out the C# specification for this one!

#

First: to answer your question

#

I see no difference in the IL

#

(intermediate language)

sand heath
#

There shouldn't be

#

If the "f" is redundant the compiler will see that

hasty sleet
swift crag
#

Both of these values are stored identically.

#

(i used godbolt for this)

hasty sleet
#

What do you mean 'identically'?

swift crag
vapid yew
#

What's godbolt ?

swift crag
#

It lets you write and compile code in a variety of languages.

vapid yew
swift crag
swift crag
vapid yew
#

It does actually

#

Let me find the source

hasty sleet
#

There was one instance where unity compiled my C# such that using a when clause was just ignored. Unsure why.

#

Null check had to be performed manually

swift crag
#

You were probably getting tripped up by how Unity objects pretend to be equal to null

hasty sleet
#

Aaahhh that was probably it

swift crag
#

When a unity object is destroyed, it compares equal to null

#

But your reference doesn't magically disappear

#

Things like the null coalescing operator and the null-conditional operators don't care about this

#

?? ?. ?[]

fervent abyss
# swift crag Yes. You want the player to follow the movingo bject.
void FixedUpdate(){
      LocalPlayer.GetGripHand(grabbingHand).handLastPosition = attachPoint.TransformPoint(attachPoint.position);
      
      //Lever Login
      
      if (!LocalPlayer.GetGripHand(grabbingHand).overrideLastHandPos) return;
      attachPoint = LocalPlayer.GetGripHand(grabbingHand).handTransform;
      LocalPlayer.GetGripHand(grabbingHand).handLastPosition = attachPoint.InverseTransformPoint(attachPoint.position);
}

erm i did this and.... it throws me everywhere

vapid yew
#

Someone is quoted:

 '1.0' is a double (64 bits)

'1.0f' is a float (32 bits) 



The code `float f = 1.0;` will not compile. It will fail with error CS0064, with the message:

Literal of type double cannot be implicitly converted to type 'float'; use an 'F' suffix to create a literal of this type
swift crag
safe radish
#
uOffset = (adjPos.z % tilingFactor) * tileSize;
                vOffset = (adjPos.y % tilingFactor) * tileSize;
                uvs.Add(new Vector2(uOffset + tileSize, vOffset));               //1,0   Top Left        3  
                uvs.Add(new Vector2(uOffset, vOffset));                          //0,0   Bottom Left     1 
                uvs.Add(new Vector2(uOffset + tileSize, vOffset + tileSize));    //1,1   Top Right       4
                uvs.Add(new Vector2(uOffset, vOffset + tileSize));               //0,1   Bottom Right    2```
swift crag
#

float x = 1;

vapid yew
#

Another person quotes:

 The compiler is pretty smart, and if you make it unambiguous that the number needs to be a float, you'll get a float. So like:

float f = 1.0;

The compiler will treat that like a float, no problem. Problems happen when you have something like:

var f = 1.0;

That will be a double, and the only way to make it a float is to use 1.0f or put float on the left-hand side. 
slender nymph
#

that first part is inaccurate

slender nymph
#

that's attempting to assign a double literal to a float which is not possible without casting

swift crag
#

1.0 is a double. There are no exceptions.

hasty sleet
vapid yew
swift crag
slender nymph
vapid yew
fervent abyss
slender nymph
safe radish
swift crag
#
  1. When you grab the object, convert the world-space hand position into a local-space position
  2. Each physics update, convert that back into a world-space position.
vapid yew
#

Is there any reason as to why I should put the f after a "whole number" float?

swift crag
dry tendon
#

I know this is not the right channel... But the UI toolkit one is not red by anyone... So could anyone help me with this? #🧰┃ui-toolkit message

sand heath
fervent abyss
slender nymph
vapid yew
slender nymph
#
float f = 1 / 2; // results in 0
float g = 1f / 2; // results in 0.5f
swift crag
#

Also, keep in mind that the compiler will optimize a sequence of constants down to a single constant.

#

float x = 1 + 0.5f;

#

This produces a constant whose value is 1.5f

hasty sleet
vapid yew
#

Okay!

hasty sleet
#

I don't quite understand that part

swift crag
hasty sleet
#

Ahh

lime pewter
slender nymph
vapid yew
#

@slender nymph What about the amount of bits required to store that variable?

slender nymph
#

and for the record, integer division is basically that grade school division you learned when you learned about remainders before learning about decimal numbers. so 1 / 2 == 0 with a remainder of 1

vapid yew
#

Yes

swift crag
slender nymph
# vapid yew Yes

if you knew that then i don't understand the question. the variable is a float which means it is 32 bits

swift crag
#

notice how this was optimized to a constant

vapid yew
#

But buy omitting the f will the variable be interpreted as a double (64 bits)?

zenith cypress
swift crag
#

because 1 is not a real literal

#

it is an integral literal

swift crag
vapid yew
#

float a = 1; typeof will be a float 32bit and not double 64bit

swift crag
slender nymph
vapid yew
#

Okay I understand!

zenith cypress
#

1.0 and 1d is a double

vapid yew
#

Thanks @swift crag @slender nymph @sand heath 👍

umbral rock
#

@swift crag i still dont understand why this line of code:
if (Input.GetKeyDown(KeyCode.Space) && inAir == false)
{
rb.AddForce(new Vector2(0, JumpHeight),ForceMode2D.Impulse);
}

is so weird, if i move left and right while in the air then im flying lol theres almost no gravity

swift crag
#

I see nothing wrong with that code.

dry tendon
#

Are there any kind of layers while creating a uxml so I can move to the front a letter?

vapid yew
umbral rock
slender nymph
swift crag
#

if you set the Y velocity to 0, you lose your Y velocity

dry tendon
umbral rock
#

aahh yes omg, now i can see, if i press q or d my Y velocity goes to 0, hmmm... how do i fix this

slender nymph
swift crag
umbral rock
swift crag
#

indeed

umbral rock
#

Thanks for the help mate! sorry, im very new to programming in unity 🙂

bitter root
#

i have a problem with my movement, i use brackeys method with a player controller, when i walk backwards toward a wall then i start climbing it for some reason

swift crag
#

show your !code

eternal falconBOT
bitter root
swift crag
#

You should consolidate everything into one Move call

#

Although, the main reason to do that is to make CharacterController.isGrounded work right

#

and you're doing your own ground check

slender nymph
# bitter root i have a problem with my movement, i use brackeys method with a player controlle...

unrelated to your issue, but if you are using brackey's FPS movement code then you're probably also using his flawed camera rotation code. Don't multiply mouse input by Time.deltaTime, it leads to stuttery controls. Mouse input is already framerate independent so that isn't necessary. And whenever you remove that multiplication make sure to reduce your sensitivity variable both in the code and the inspector (since it is about 100 times too high)

swift crag
#
        /*if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
        {
            controller.slopeLimit = 100.0f;
            velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
        }*/

this is very odd; did you just comment this out?

#

there's no reason to change the slope limit

bitter root
# swift crag ```cs /*if (Input.GetKeyDown(KeyCode.Space) && isGrounded) { ...

yeah i removed the jumping because it had too many problems, like when i looked down the jumping just didnt work, and when i jumped backwards and looked down it started flying for some reason, the slopelimit change suggestion was by some commenter on brackeys video, "1.) Trying to jump onto something can cause a stutter/jitter effect because the slope limit(it should be adjusted when you jump and then readjusted when you land)"

swift crag
#

Your camera rotation should have no bearing on how you move. Your move vector is just:

#

Vector3 move = Vector3.Normalize(transform.right * x + transform.forward * z);

#

Are you rotating the object that has the PlayerMovementController on it..?

swift crag
#

This will cause you to start moving up and down if you look up or down

bitter root
sand heath
#

Brackeys videos are debugging exercises disguised as tutorials

sand heath
bitter root
vapid yew
sand heath
# bitter root yes

are the character controller, movement controller, camera input scripts supposed to be on the root gameobject?

swift crag
#

it's fine to just directly set your velocity

sand heath
#

I guess if you want a feel for acceleration(?)

swift crag
sand heath
#

depending on the game though you might not want acceleration

swift crag
#

(notably, you can't accrue t across many frames if you're constantly changing the start point)

#

which is the case for movement

bitter root
#

i cant find any tutorial that does the movement right

vapid yew
#
while (t != 1) {

            elapsedAnimationTime += Time.deltaTime;
            if (elapsedAnimationTime > totalAnimationTime) elapsedAnimationTime = totalAnimationTime;

            // Ease in
            t = elapsedAnimationTime / totalAnimationTime;
            t = 1 - Mathf.Cos(t * Mathf.PI * Random.Range(.3f, .5f));

            controller.height = Mathf.Lerp(controller.height, targetHeight, t);
            controller.center = Vector3.down * (3 - controller.height) / 2;
            camera.localPosition = new(0, Mathf.Lerp(camera.localPosition.y, targetCameraPositionY, t), 0);

            movementSpeed = Mathf.Lerp(movementSpeed, targetMovementSpeed, t);

            yield return null;
        }

This is my procedural crouch and yes you can tell the difference (because of the interpolation).

summer stump
vapid yew
summer stump
rocky canyon
#

its neither here nor there.. this

#

i use MoveTowards() for my crouch

#

guess im weird ¯_(ツ)_/¯

sand heath
#

if you want a game to feel as responsive as possible, you probably don't want interpolation

vapid yew
#

i.e: Making it go from 0-100 over .25f is better than an instant burst in almost all movement scenarios.

sand heath
#

maybe more realistic but it's not an objective thing

vapid yew
#

🤷‍♂️

#

That's the beauty of art I suppose.

swift crag
#

It has absolutely nothing to do with movement.

vapid yew
#

You just don't have context

#

xD

swift crag
#

No, you're just posting a blob of irrelevant code to try to look clever.

#

It is obvious that you should interpolate between values if you want the change to take a non-zero amount of time

summer stump
#

While accomplishing the opposite

swift crag
#

This is a tautology.

vapid yew
#

The code block was posted to provide an example to @umbral rock how they may chose to add interpolation.

swift crag
#

interpolation to what? You just said "you should use interpolation!"

#

This is anti-useful information.

steep rose
#

what

rocky canyon
#
    private void CrouchCheck()
    {
        if (Input.GetKey(KeyCode.LeftControl))
        {
            isCrouching = true;
            // Height and Center deltaMaxs need to match
            characterController.height = Mathf.MoveTowards(characterController.height, 1f, (7f * Time.deltaTime));
            characterController.center = Vector3.MoveTowards(characterController.center, playerSettings.crouchingVector, (7f * Time.deltaTime));
        }
        else if (!obstacleOverhead)
        {
            isCrouching = false;
            // Height and Center deltaMaxs need to match
            characterController.height = Mathf.MoveTowards(characterController.height, 2f, (5f * Time.deltaTime));
            characterController.center = Vector3.MoveTowards(characterController.center, playerSettings.standingVector, (5f * Time.deltaTime));
        }
    }``` my implementation.. no lerp here
slender nymph
#

that MoveTowards is the interpolation there

swift crag
#

MoveTowards is equivalent to a Lerp with fixed start and end points, mind you.

#

Of course, if the start and end points change, it's no longer feasible to do that

vapid yew
swift crag
radiant frigate
#

!code

eternal falconBOT
steep rose
#

why are we arguing about interpolation?

swift crag
#

scroll up

steep rose
#

yup

rocky canyon
rocky canyon
radiant frigate
rocky canyon
#

must not be getting reached

#

debug outside it and see if the entire else statement ever runs

slender nymph
#

if the raycast doesn't hit anything then the log will never print

swift crag
vapid yew
#

@swift crag Perhaps not to you it wasn't

swift crag
#

Physics.Raycast defaults to a very long max range

slender nymph
#

also that raycast will never hit a 2d collider 😉

swift crag
steep rose
#

pipes, cool it

slender nymph
rocky canyon
#

b/c its a Physics 3d raycast

swift crag
vapid yew
#

Anyways man, I was just looking to give the guy some food for thought. It's not that deep

summer stump
swift crag
#

i glossed over that Rigidbody2D

swift crag
radiant frigate
vapid yew
#

Well I'm sure y'all ain't gonna lose any sleep over it. This is entirely futile.

steep rose
#

bro the one liners from fen, 10+ points

rocky canyon
#

nope.. why u still talkin about it?

slender nymph
rocky canyon
#

and make sure ur collider is 2d as well. just in case

rocky canyon
#
    void PrintFolderToFile(string folderPath, int indentLevel, StreamWriter writer)
    {
        string[] subFolders = Directory.GetDirectories(folderPath);

        foreach (string subFolder in subFolders)
        {
            string folderName = Path.GetFileName(subFolder);
            writer.WriteLine($"{new string('-', indentLevel * 2)} {folderName}");
            PrintFolderToFile(subFolder, indentLevel + 1, writer);
        }
    }``` 
anyone know how I could add filenames to this? (it prints the folder directory)
#

the recursive part kinda sketches me out not sure how to expand this..

#

nvm i think this is it..

sour spear
#

am i correct to assume the highlighted line calls OnJump() the first frame the button assigned to jump are pressed, and not the subsequent frames when they are held?

rocky canyon
#

ive never seen that syntax before tbh w/ you

steep rose
#

that style is neat looking

#

ngl

radiant frigate
#

how can i use the RaycastHit2D return? im looking at the docs and i cant see anything that explains it

steep rose
#

i just dont understand it 🥲

rocky canyon
#

/* are you sure about that? */

slender nymph
radiant frigate
rocky canyon
#

ohh. i just realized what the _ was

slender nymph
#

yeah that's just a discard to ignore the paramter passed by the event they are subscribing to

rocky canyon
#

neat.. i always pass ctx for everything

steep rose
#

i still dont understand it

slender nymph
#

what part do you not understand

rocky canyon
#
        inputActions.Player.Move.performed += ctx => OnMove(ctx);
        inputActions.Player.Move.canceled += ctx => OnMove(ctx);
        inputActions.Player.Jump.performed += ctx => OnJump();```
#

instead of ctx he throws his away

#

like my OnJump() it doesnt actually need it

steep rose
#

im just not sure what it does in general, i know its an input

rocky canyon
#

yea, thats all i know either..

#

its input system input 😄

slender nymph
#

they are subscribing to the started event on an input action using a lambda expression

rocky canyon
#

it can be done w/ stuff other than input as well

rocky canyon
steep rose
north kiln
rocky canyon
radiant frigate
#

how can i make the raycast ignore the first object/the object that casted it?

steep rose
#

sorry i havent used them before but thanks for informing me 😄

rocky canyon
#

use a counter..

slender nymph
# rocky canyon

note that this is different than a lambda expression. this is expression body syntax which just makes the body of the method one line. a lambda expression creates an instance of a delegate using an anonymous method

rocky canyon
#

if its the first hit ignore it.. if its the 2nd or more.. use it

radiant frigate
#

how do i make a counter for that?

rocky canyon
#

i dont have an example of that

sour spear
rocky canyon
#
        DrawButtonAligned("SPWN FUNC 2", MaxLogoWidth, () => {
            Debug.Log("Execute FUNC 2");
        });``` does this count?
north kiln
#

There's two different usages of it, if it's attached to a method or property then it's a "expression-bodied member", which is just a single-line method.
The second is a lambda expression () => term, (input, ...) => term, () => { multi; line; terms; } which takes many forms but is basically a way to write a method inline, which can also "capture" variables in the containing scope

steep rose
#

yeah personally ive only seen => use as a {}

slender nymph
north kiln
#

If you're passing a function to a method by declaring it inline then you're writing a lambda expression

rocky canyon
steep rose
#

yeah

north kiln
#

Oh and I forgot the 3rd usage of it as an expression beyond methods and properties, which is in the switch expression, where you say:

result = input switch
{
  query => resultA,
  queryB => resultB,
  _ => default
};```
That's also not a lambda.
steep rose
slender nymph
#

i consider that basically the same as expression body syntax since that's pretty much what it is, but for switch statements

north kiln
#

sure, but it is a completely different form of switch statement really, with different requirements and flexibilties

rocky canyon
#

i ended up just using GetFile.. but i'll look into EnumerateFile.

#

hmm now how to remove the meta's 🤔

#

ohh lol imma just shutup. i found it in the same Class

swift crag
#

e.g.

#
QualitySettings.SetQualityLevel(setting.Choice switch {
  choiceOne => 1,
  choiceTwo => 2,
  choiceThree => 3
}, true);
north kiln
#

you can use when, but I don't remember how flexible that is. I try to reseve it for simple cases

swift crag
#

where choiceOne/Two/Three are variables

#

ooh, maybe you can

#
int what = qualitySetting.Choice switch
{
    var x when x == qualityLow => 1,
    var x when x == qualityMedium => 2,
    var x when x == qualityHigh => 3
};
rocky canyon
#

thats very clean

swift crag
#

not a huge fan of the extra var x in the front

#

previously:

#
            if (qualitySetting.Choice == qualityLow)
                target = 0;
            else if (qualitySetting.Choice == qualityMedium)
                target = 1;
            else if (qualitySetting.Choice == qualityHigh)
                target = 2;
#

oops, off-by-one error

sour spear
#

under the new input system, is there something i can use to check if an input is being held via the update method? where i define jumpAction = playerInput.actions["Jump"];

rocky canyon
#

if (obj is string s) does this mean i can use is to do string comparisons in my Input Fields?

swift crag
#

in that case, it's being used to test if obj can be assigned to a string variable

#

if so, it assigns it to s

swift crag
sand heath
#

whats that got to do with unity though

swift crag
#

well, you tend to use C# when making a game in Unity 😛

swift crag
sand heath
#

only oldheads remember javascript

#

or bolt

swift crag
#

you mean Boo

#

that's true oldhead territory

sand heath
#

cuz it sucks?

sand heath
#

what im talking about doesn't even have a wikipedia page

swift crag
#

I just figured you meant Boo, given that it and JavaScript were both removed a long time ago

sand heath
#

i never know 'er

swift crag
#

Bolt (now Visual Scripting) is at least extant!

sand heath
#

all i know is that javascript is the reason i append "c#" to every unity related google search

rocky canyon
#

lol. where u looking history books? 🤪

steep rose
#

This jump code makes the character controller jump to a certain height and take the original velocity of the character and applies it to move in that direction so you cant just move in all directions in the air, but I would like some air control via A and D keys an i tried to +=, -=, add, subtract, mutiply with another float and or velocity but it just doesnt work, does anyone have a right direction to lead me in or help me to get some air control in this code?

    void Jump()
    {
        if (isGrounded && Input.GetKeyDown(jumpKey))
        {
            velocity.y = Mathf.Sqrt(jumpheight * -2f * gravity);
            if (Airstuff == false)
            {
                JumpVel = moveDirection;
                Airstuff = true;
            }

            print("ISDOING");
            //this is to keep velocity
            NewJumppvel = new Vector3(JumpVel.x, 0f, JumpVel.z);
        }
    }
rocky canyon
#

ur setting ur velocity directly? u should factor in ur air stuff in a calculation and construct a vector to use at the end of ur move functions

sour spear
#

is there a way to freeze controls? like not register any inputs for 0.2s

rich adder
sour spear
#

wdym

true heart
#

i have a dictionary called damage which holds a vector 2 key and a int value and i have a function that takes a vector 2 and checks to see if its in the dictionary has an int for it, it then either returns 0 if there isnt or the value at the vector 2 in the dictionary.
the problem is im not sure how to find the int that is related to the vector 2 key
public int GetDamageAtTile(Vector2 pos)
{
if(damage.TryGetValue(pos,out var howmuchdamage))
{
Debug.Log("hit");
return //not sure what to write here;
}
else
{
Debug.Log("nohit");
return 0;
}
}

rich adder
#

activate it with a timer or whatever

sour spear
#

gotcha

#

is Time.deltaTime a consistent timer? like is it 1/60 s

rich adder
rich adder
#

Time.time can also be an option

#

or coroutine

true heart
rich adder
#

also wat is the point of this thing

sour spear
#

ok gotcha, last question is there a player form which allows me to edit the velocity directly? as opposed to character control's kinda limited physics interactions with Move()

rich adder
#

there is SimpleMove too but that has its own gravity situation going

#

anything you would pass to a .velocty you would use Move()

sour spear
#

i see

rich adder
#

yes it would be similar if rigidbody you only assign velocity, all forces are overridden

true heart
# rich adder also wat is the point of this thing

its for a tile based game the vector 2 is a tile position and the int is the damage at that tile and the code is just checking to see if the tile you are on is getting attacked and how much damage the atatck is doing

true heart
#

na

#

its my own tile system

#

with prefab tiles

rich adder
#

where do you assign a value to a new entry to dictionary

#

also I would suggest you at least use the Vector2Int version rather than the float

true heart
# rich adder where do you assign a value to a new entry to dictionary

public void damagesquare(Vector2 tile, int howmuchdamage)
{
if (damage.TryGetValue(tile, out howmuchdamage))
{
int Damagenow = damage.GetValueOrDefault(tile);
damage.Remove(tile);
damage.Add(tile, Damagenow + howmuchdamage);
}
else if (damage.TryGetValue(tile, out howmuchdamage) == false)
{
damage.Add(tile, howmuchdamage);
}
}

#

this si the code for that

rich adder
true heart
#

oh ya i ran into problems with flaot before

#

im using all int i think

#

wheres the float exactly

rich adder
#

Vector2 is literally a struct of 2 floats

true heart
#

oh

#

wait

rich adder
#

thats why I said Vector2Int has the integer version

true heart
#

ohhhh

#

ive been using mathf.roudntoint all this time

rich adder
#

not saying thats not correct because it should still have decent approximation for ==

true heart
#

didnt know you could do that

rich adder
true heart
#

i use it for the actual grid system not in thsi code

rich adder
#

did you try printing all your keys/values in the dictionary to make sure everything is correct?

true heart
#

ya i was tryign to figure out hwo to see dictionarys in the unity editor but im not sure how to

rich adder
#

you cannot unfortunately

true heart
#

oh

#

well hwo do i know

#

whats on it

rich adder
#

unity doesn't serialize dictionaries

rich adder
true heart
#

so like for loop and stuff

#

liek manually check

rich adder
#

foreach

true heart
#

oh i see

#

alright ill try that out ty

#

hopefully it allows me to see where i went wrong

rich adder
#

yeah it should, you will be able to see what is exactly there and why its not pulling the value

#
   foreach(var kvp in myDiction)
  {
      Debug.Log($"key {kvp.Key} : value {kvp.Value}");
  }```
true heart
#

oh isee ill put that in teh code

#

oh it seems like the tiles that are getting damaged all have a int value of 0

#

it probably a problem in another part of my code ill go figure that out

rich adder
#

suggest you learn the debugger though

true heart
#

whats that?

#

oh

#

ill try it out

rich adder
#

whichever works, the point is debugging though basically lol

#

always triple check which values are what , never make assumptions

true heart
#

public void damagesquare(Vector2 tile, int howmuchdamage)
{
Debug.Log(howmuchdamage);
if (damage.TryGetValue(tile, out howmuchdamage))
{
Debug.Log(howmuchdamage);
int Damagenow = damage.GetValueOrDefault(tile);
damage.Remove(tile);
damage.Add(tile, Damagenow + howmuchdamage);
}
else if (damage.TryGetValue(tile, out howmuchdamage) == false)
{
Debug.Log(howmuchdamage);
damage.Add(tile, howmuchdamage);
}
}
the first debug.log give me the right value which is 1 damage but the 2 other debug.logs seem to be giving me 0 damage which im not sure why

eternal falconBOT
true heart
#

oh

rocky canyon
#

you should put some more details in ur debugs.. if they're all the same it'd be hard to know which one did which.. esp if one doesnt work for example

rich adder
#

btw the out overwrites whatever value you had before if statement

#

just so you know

true heart
#

well i individually changed 2 into comments the nran it and saw what the otehr one gave

#

oh

#

but if i remove out the code jsut gives me errors

rich adder
#

you're not meant to remove it then just use the temporary variable it gives you

true heart
#

oh

rich adder
#

or just contains key...

#

either way works

true heart
#

wait so coudl i make a variable and make it equal to howmuchdamage before and use that one in the dictionary instead of howmuchdamage?

rich adder
#

what is even the pointof this

            int Damagenow = damage.GetValueOrDefault(tile);```
#

if you already getting the value in the out

true heart
#

oh thats how much damage was on the tile before

rich adder
#

thats wat the out is for

true heart
#

teh first if is adding damage to the tile if it already has damage on it

#

oh...

rich adder
#

can just be

if (damage.TryGetValue(tile, out var oldDamage))
{
    damage[tile] = oldDamage + howmuchdamage;
}
else
{
    damage.Add(tile, howmuchdamage);
}

@true heart

true heart
#

this was my first time usign a dictionary so im a little lost

#

k let me try that out rn

#

oh ya the codes workign now

#

thank you

verbal reef
#

I am currently learning game development and discovered that when using Unity's latest Input System, specifically when getting gamepad.Move.readValue<Vector2>(), the direction vector consistently reads as -0.7,0.7 even when there is no input. This causes the character in my game to constantly drift to the left. I'm very frustrated and unsure how to fix this. Can anyone help me resolve this issue?"

summer stump
#

Or a second keyboard
And are either connected?

verbal reef
slender nymph
#

where ever you set up your input action. but you want to add a deadzone processor as most likely there is at least a small amount of "drift" on your joystick

verbal reef
verbal reef
slender nymph
#

that's because it is normalized

verbal reef
slender nymph
slender nymph
verbal reef
slender nymph
#

that is not the reason you are experiencing stick drift. but the input being normalized is why the values are both 0.707 since that is what you should expect when the values on each axis are the same and the vector is normalized

#

they could both be incredibly small values, but since you have no deadzone those incredibly small values are not being ignored. it could literally be (-0.000001,0.000001) and the resulting normalized vector2 is going to be (-0.707107, 0.707107)

verbal reef
#

Got it Thanks a lot bro

summer stump
verbal reef
sand heath
#

What is the preferred way to add gravity to an object not using a rigidbody?

slender nymph
#

well if you're not using a rigidbody then you just add a downward motion however you normally move the object

sand heath
#

And if I wanted acceleration and terminal velocity and such I would need to make that myself wouldnt I

slender nymph
#

yes

sand heath
#

😔

cosmic dagger
sand heath
#

Some magic thing included in Unity I don't know about so I don't have to spend the next few days learning physics

cosmic dagger
#

set a global gravity vector and apply that to all affected objects . . .

cosmic dagger
sand heath
#

I wanted to try to make my own character controller and I've always read the rigidbody-based controllers are inferior to custom made controllers or ones that use character controller

#

I'm not sure what the general standard for character controller is and what you're 'supposed' to use

cosmic dagger
#

inferior? 🤔 depends on who makes it . . .

rocky canyon
#

if u want a decent physics type controller id use a Kinematic custom character controller

slender nymph
#

use whatever tf you want. if you like rigidbodies then use a rigidbody, if you prefer the CharacterController component then use that, if you prefer a custom solution then make one.

sand heath
#

The only reason I like rigidbodies is because they require no effort from me

cosmic dagger
#

some are easier than others, but that depends on the person making it . . .

sand heath
#

but if I could sacrifice some of my laziness for something I have more control over..

slender nymph
sand heath
#

(specifically i want more control over jumping and movements like dashing)

sand heath
#

if it has enough already done for me I should be able to just make my own version of it if i need something more specific

#

(but I also don't want to re-invent the wheel)

keen bloom
#

Hi all!
I'm trying to make a camera controller that has a sideways "roll" option
but
the X and Y axes stay global when I use the roll function, meaning moving the mouse up and down actually moves the camera sideways from the player's perspective - up and down in world space.

The code is attached to the player gameobject with a rigidbody, collider and camera.

Here's the code I use (the "Roll" axis is set to Q and E in the input manager):

    inputX = Input.GetAxis("Mouse X") * mousesensitivity;
    inputY = Input.GetAxis("Mouse Y") * mousesensitivity;

    inputRoll = Input.GetAxis("Roll");

    yaw += inputX;
    pitch -= inputY;
    roll += inputRoll;


    transform.rotation = Quaternion.Euler(pitch, yaw, roll);
slender nymph
#

change its localRotation not its rotation (assuming you "roll" a parent)

#

otherwise you'll need to look at the transform class and its various TransformXXX methods to find out which one is right for what you need

keen bloom
#

I've tried transform.Localrotation and it has the same effect, the script is parented to the main gameObject, but if I specify playerRigidbody.transform.localRotation I still get the same results

slender nymph
#

are you rotating the parent object for the roll?

keen bloom
#

Yes

slender nymph
#

and the transform.rotation = line is affecting the child object or the parent object?

keen bloom
#

Here's the hierarchy, the script is attached to the "Player" object, with a rigidbody specified as a public variable, I then dragged the player object's rigidbody into it. The camera and spawner are children of "Player" and move together with it.

slender nymph
#

so then when i asked if you were rolling the parent of the object with this script on it, the answer should have been "no". and now you can go re-read what i said before

keen bloom
#

I am rotating the parent object, the player is the parent object, I now specified exactly how I rotate it

slender nymph
#

but you aren't rotating the parent of the object with this script. you are rotating the object with this script

keen bloom
#

The player is the parent of all the other objects, are you saying that there should be an additional object above the player in the hierarchy with the script attached to it instead?

slender nymph
#

no i am not saying that. i told you what you can do if you are rolling the same object that you are rotating the view for

keen bloom
#

your only suggestion so far has been changing rotation to localRotation

slender nymph
#

it definitely wasn't the only suggestion. but since you refuse to read the other suggestion, which i conveniently linked you to again, i won't be helping you further

keen bloom
#

getting snappy in the beginnner coding section because you refuse to elaborate... why are you even writing then?

#

"Duh, re-read what I said"

slender nymph
#

mate i'm not getting "snappy". i just refuse to help people who refuse to help themselves. i told you what to look at to find what you need

#

put some fucking effort into getting your issue resolved

devout flower
dark sluice
#

unity is freezing my game whenever i reload my scene or use the on click event i have set to reload my scene, anyone else ever have this issue? only the music/sound effects are still going, everything else is frozen. 😦

keen bloom
# devout flower I think he’s talking about this

the transform class (to my understanding) is just whatever you put behind transform (the documentation also links there) - I've tried rotation, localRotation, transformDirection, I've tried using both X and Y inputs for both, offsetting their incluence based on rotation of the object and nothing worked

slender nymph
#

have you actually looked at the documentation like i suggested?

keen bloom
slender nymph
#

great! did you bother looking at the methods i suggested you look at?

keen bloom
#

"the various TransformXXX" ? like I said I already tried?

slender nymph
#

show what you actually tried

#

although i will say that all of this would be easier if you did just have another parent that you used for the roll

#

however that isn't necessary as you have these convenient methods to transform a Vector3 from local space to world space

keen bloom
# slender nymph show what you actually tried

"I've tried rotation, localRotation, transformDirection, I've tried using both X and Y inputs for both, offsetting their incluence based on rotation of the object and nothing worked"

#

I could also say "re-read what I said"

#

also tried quaternion, eulerAngles, localEulerAngles...

slender nymph
#

and i said show what you tried. obviously implying i wanted to see your actual attempt in code. but if you want to be a baby about this i'm just going to block you

keen bloom
#

my code is way too long to post here

slender nymph
#

you can post your !code so that someone who is willing to help you further can see it

eternal falconBOT
elder raptor
#

In a ragdoll object, how can I identify what part my bullet shot? Do I need to make colliders for each part or?

keen bloom
slender nymph
elder raptor
slender nymph
#

i'd also give each part of the ragdoll a component that can take damage and relay that to whatever the "main" health object is. that way you can just TryGetComponent on the hit part to get that specific component and then that component can take the damage and pass that damage along to the main part. Doing this would also allow you to optionally have individual health values for each part in case you wanted to be able to break specific parts off or something when they've taken enough damage

elder raptor
#

Ahh yes, I remember doing something like that before. Thank you!

summer stump
tawdry quest
#

I would have long called you hopeless and blocked you lol, hes way more patient then many of us.

#

Don't bite the hand that feeds you!

#

@slender nymph regarding your bio.
if you dont want random dms from people asking for unity help you can do this btw:

slender nymph
#

i am aware. but that still doesn't stop it if someone shares a completely different server with me. which still happens quite frequently

tawdry quest
#

understood, unfortunatly you need to do that will all gamedev servers notlikethis

static cedar
#

I made a SinCos struct with trig identities for 45 and 90 deg turns. But on second though, I could have just added extension methods on Vector2 for that. UnityChanThink

idle ginkgo
#

can i set 2 coordinates as a public variable which i can change using some marker ?
for example i want an saw to move from point a to point b
so can i make the points an variable and then set those points as position of the markers ?

rich adder
idle ginkgo
#

but then i would have to manually enter the coordinates every time /

rich adder
idle ginkgo
#

wait i can set those as position of a child game object and i will just move around the game abject

rich adder
#

I mean thats what i was trying to tell you

idle ginkgo
#

oh ok

#

thanks

atomic holly
#

Hello,
What is the best method to save data for a videogame ? I see some tutorial use text file , JSON or with PlayerPref

waxen adder
#

Looking for advice. I got a Player object that is a child of the Unit object. I was wondering, where would I be putting the code for player movement? In the player object or as a seperate class altogether?

half egret
teal viper
#

Or a gameObject?

storm dove
#

with my player im applying rb.velocity to it so that the movement is instant and doesnt accelerate or deaccelerate, but for some reason after ive let go of either the left or right key to move it continues to move for about half a second, is this normal velocity behavior or is something going wrong?

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

public class PlayerController : MonoBehaviour
{
    [SerializeField] float speed = 5;
    private Rigidbody2D rb;
    private float horizontal;
    [SerializeField] private float jump = 5f;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        horizontal = Input.GetAxisRaw("Horizontal");
    }

    void FixedUpdate()
    {
        // horizontal movement

        // horizontal movement
        if (horizontal != 0)
        {
            rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);
        }

        // jump
        if (Input.GetKey(KeyCode.UpArrow))
        { 
            rb.velocity = new Vector2(rb.velocity.x, jump);
        }
    }
}```
teal viper
#

In your case it stops because of dumping and friction. Which are external forces.

storm dove
#

right ok, thank you 🙂

teal viper
#

If you want it to stop immediately, remove that if statement that checks if horizontal is 0 or not

teal viper
waxen adder
#

Handling data specific to the player. Stuff that other units wouldn't care for. I know I'm being vague at the moment on this front. Currently just thinking about the movement part atm

teal viper
storm dove
#

ah right

teal viper
waxen adder
#

Gotcha, that's where my mind was at initially, just wanted to make sure

umbral rock
#

i dont understand something about the camera rotation calculations, every video i watch on how to move the camera like in an fps game they do this,

yRotation += mouseX
xRotation -= mouseY

what is this calculation? i know its if u move your mouse but it doesnt make sense to me

teal viper
#

I'd assume that it's Euler angles

idle ginkgo
#

`public float moveSpeed = 0.3f ;

public Transform startPosMarker;
public bool movingToEnd = true;
public Transform endPosMarker;

private void Start()
{
transform.position = startPosMarker.position;
}

private void Update()
{

Vector3 targetPos = movingToEnd ? endPosMarker.position : startPosMarker.position;

transform.position = Vector3.MoveTowards(transform.position, targetPos, moveSpeed * Time.deltaTime);


if (transform.position == targetPos)
    movingToEnd = !movingToEnd; 

}`

#

why doesnt this wor

#

the if statement doesnt work

#

its not switching target pos on reaching that position

languid spire
upper tide
#

For the following, I was wondering if the Update function will run directly after the #1 mark? Or wil it wait for the function to finish execution before running the Update ufnction

public static SmallMissileScript Attach(GameObject go, float speed, Vector3 faceDirection)
    {
        SmallMissileScript missile = go.AddComponent<SmallMissileScript>();
        // #1
        return missile;
    }

  private void Update()
  {
      
  }
#

Function is called in the FixedUpdate function of another monobehaviour

languid spire
#

standard functions are never interrupted by Unity messages

keen dew
#

The Update method runs the first time during the update phase next frame

upper tide
languid spire
#

no, only the Awake will run at that point

upper tide
#

Gotcha thanks

languid spire
upper tide
#

To make it immediately start running if Im getting this correctly

languid spire
#

yes

upper tide
#

Where would this be a use case

#

I can imagine some very frame important stuff?

languid spire
#

for positioning and movement

#

could also be ray casting, anything really that you do in Update but you also want to do as initialization

upper tide
#

Im curious if that one frame really matters

languid spire
#

that would depend on your use case, it could also be purely used so as not to duplicate code

upper tide
#

Makes sense

#

Thanks

umbral rock
teal viper
idle ginkgo
#

btw it still doesnt change when reaches the end pos

#

this should work

#

but it doesnt

idle ginkgo
#

it isnt becuase of the if statement

bright oxide
#

does anyone know why TMP text is so blurry?

#

(this is the view from game mode)

#

and these are the settings

#

And if it affects anything, this is a BRP project

keen dew
#

Is the game view zoomed in?

bright oxide
#

nope, the scale is normal

bright oxide
#

actually even the text in TMP example scenes is blurry

#

its fine in editor mode though

frank zodiac
#

strange

#

oh nvm i had to add using System.Collections.Generic;

umbral rock
#

hello, im watching a tutorial on how to make an endless runner because i wanna make flappybird, and i came across the instantiate function but i dont understand why he sets the position of the instantiated object to transform.position? he has 2 objects that he wants to spawn, an object thats flying and an object thats on the ground, but somehow even tho he sets the position to transform.position the objects are at different heights?

#

he doesnt say to the instantiate function where he wants to spawn the object, he just says he wants to spawn them at the transform.position, but why are the 2 objects at different positions?

willow scroll
fading sluice
#

i have a script that references a gameobject, but from donotdestroy, the original is destroyed and the new instance is kept instead, and so if i switch scenes and come back the script does not get referenced anymore.

does anyone have code that preserves the original gameObject and destroys all other clones?

willow scroll
willow scroll
umbral rock
willow scroll
umbral rock
# willow scroll Perhaps, I would be able to answer your question if you share the code

private void Spawn(){
Vector2 randomPosition = new Vector2(
Random.Range(minPosition.x, maxPosition.x),
Random.Range(minPosition.y, maxPosition.y)
);

    GameObject obstacleToSpawn = obstaclePrefabs[Random.Range(0, obstaclePrefabs.Length)];
    GameObject spawnedObstacle = Instantiate(obstacleToSpawn, transform.position, Quaternion.identity);

    Rigidbody2D obstacleRB = spawnedObstacle.GetComponent<Rigidbody2D>();
    obstacleRB.velocity = Vector2.left * speed;
}

}

this is the spawncode

#

look at the instantiate, he gives it a position transform.position

#

wich is logical if u want to spawn 1 object at the same place, but he spawns 2 objects at 2 different places, wich isnt logical to me anymore

fading sluice
#

note that ChooseSong(false); still chooses the song

languid spire
#

yes, code is executed from top to bottom, you do not stop this

magic panther
#

I am trying to modify the color of my particle system, but every time I change something a new error pops up. What's the right way to go about this?

willow scroll
fading sluice
#

sorry, I am still slightly confused about the implementation of singletons

languid spire
fading sluice
languid spire
fading sluice
languid spire
#

yes, and the code continues to execute

fading sluice
#

thus the script would stop running and thus everything else after would run only if the script wasnt destroyed (thus was the original)

fading sluice
languid spire
#

why would you assume that?

willow scroll
#

This code is the same

if (instance == null)
{
    instance = this;
    DontDestroyOnLoad(gameObjet);
    ChooseSong(false);
}  
else
    Destroy(gameObject);
#

Are you saying the object is destroyed when starting the game?

fading sluice
#

essentially in pseudocode i want

IF no other instances
{
  ChooseSong
}
ELSE
{
  some magicky way to detect if the script is the original one or a cloned instance
  destroy the cloned instance
}
willow scroll
magic panther
willow scroll
languid spire
#

then why not just put the DDOL and ChooseSong inside the if statement you have where it belongs

willow scroll
magic panther
#

I did. As I said, new error whenever I change something

willow scroll
magic panther
#

daaamn MainModule

#

thanks mate

fading sluice
umbral rock
languid spire
willow scroll
umbral rock
willow scroll
fading sluice
# languid spire wrong ```cs if (no instance) set instance = this set DDOL ChooseSong() ...

then it might be another error - ill give you some context

essentially i have a script that gets the length of the current song being played to know when to play the next song. This script is attached to my musicplayer, which is carried via DDOL to other scenes.

However, if switching scenes concluded with deleting the original, then this would result in detaching the musicplayer, and thus the script would reference a missing object.

#

so now we have htis

willow scroll
#

If you want to make sure, print the GameObjects' positions before instantiating them

fading sluice
#

right now the code results in the original gameobject being lost

languid spire
#

how? you must be destroying it explicitly

#

are you perhaps calliing CreateSingleton somewhere else?

fading sluice
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine;
using TMPro;

public class musicplayerscript : MonoBehaviour
{
    

    public AudioSource source;
    public AudioClip clip1;
    public AudioClip clip2;
    public AudioClip clip3;
    public AudioClip clip4;
    public AudioClip clip5;
    public AudioClip clip6;
    public AudioClip clip7;
    public AudioClip clip8;
    public AudioClip clip9;
    public AudioClip clip10;
    public AudioClip clip11;
    public TextMeshProUGUI songname;
    public TextMeshProUGUI timeleft;
    public TextMeshProUGUI songid;
    float playingtime;
    string clipname;
    int clipID;
    int random;
    public static musicplayerscript instance;
    [HideInInspector]
    public int score;

    private void Awake()
    {
        CreateSingleton();
    }

    void CreateSingleton()
    {
        if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad(this);
            ChooseSong(false);
        }
        else
        {
        Destroy(gameObject);
        }
    }

    void Update()
    {
        playingtime -= Time.deltaTime;
        if (playingtime <= 0)
        {
            ChooseSong(false);
        }
        float Playingtime = Mathf.Floor(playingtime);
        if ((playingtime % 60) < 10) 
        {
            timeleft.text = (Mathf.Floor(Playingtime / 60)).ToString() + ":0" + (Playingtime % 60).ToString();
        }
        else
        {
            timeleft.text = (Mathf.Floor(Playingtime / 60)).ToString() + ":" + (Playingtime % 60).ToString();
        }
        songid.text = "ID: " + clipID.ToString();
#

singleton has been called nowhere else

languid spire
#

Then there is no way this gameobject will be destroyed

#

DontDestroyOnLoad(gameObject); btw

umbral rock
# willow scroll Not sure what exactly you don't understand

well, now i understand it, but i got a weird thing where im instantiating pillars from flappybird, but theyr spawning in the middle too, i just want to spawn them at the edges of the view, i dont know what im doing wrong atm, could i send u my spawning script?

fading sluice
#

we can try another route

#

in this case, when switching through scenes, these things get disconnected right?

willow scroll
fading sluice
#

lets say if the object referencing musicplayer was scene-specific

umbral rock
willow scroll
eternal falconBOT
umbral rock
#

oops

#

uuhm, and what do i do? paste the code into the website and then?

willow scroll
normal mortar
#

anybody know how i can fix this, so that i can make y random?

umbral rock
#

is it that?

#

or this

languid spire
willow scroll
#

The code spawns a random object between the minimum and maximum spawn positions. I see no issue here.

fading sluice
#

ok so i have decided to simplify the issue by tackling a simpler problem:

referencing textmeshproUGUI elements with gameobject.find doesnt work

am i forced to use <GetComponent>?

umbral rock
normal mortar
lone sable
#

Lets say I want a Navmesh agent to dash forward.
What would be the best way to go about doing this? I could stop it, then use Warp I suppose, just wondering if theres another way to handle it or not.

willow scroll
dreamy dune
#

maybe dumb question but why are abstarct classes used

umbral rock
willow scroll
# dreamy dune maybe dumb question but why are abstarct classes used

In Unity, you cannot add an abstract class to the GameObject. This is useful when creating a script, which should not be attached to the GameObject, and requires additional classes to derive from it, which are then attached to it.
This includes classes, which don't have a specific functionality by themselves, and do require other classes to implement it.

languid spire
willow scroll
languid spire
umbral rock
rocky canyon
#

instantiate uses a position.. just define 2 vectors with ur Y position at those heights

#

and alternate

umbral rock
willow scroll
rocky canyon
#

or throw in a variable u can change w/e
Vector2(0, Random.Range(0, RandomY);

#

RandomY = Random.Range...

willow scroll
rocky canyon
#

nope he just needs flappy bird pipes

umbral rock
#

i want them to only able to spawn at the top of the view i send u and the bottom of the view

umbral rock
rocky canyon
#

it should be.. show what code u have

umbral rock
#

because i use a minPosition and maxPosition

willow scroll