#๐Ÿ’ปโ”ƒcode-beginner

1 messages ยท Page 567 of 1

rich adder
#

thats the million dollar question

#

there is no One or the Other

woeful bridge
fast monolith
#

is this where i ask for help?

rich adder
#

they both have their pros and cons

rich adder
eternal falconBOT
#

:thinking: Asking Questions

:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #๐Ÿ”Žโ”ƒfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696

woeful bridge
#

kk I'll stick with the character controller

rich adder
woeful bridge
#

Yeah i've done the move thing simple move was in desperation of trying to fix the isgrounded lol

rocky canyon
#

many ways to do a ground-check.. just in case u want to chose another..

#

better ways.. if its feeling "***cked"

rich adder
woeful bridge
#

well I can promise you the docs on it won't tell you shit lmao

fast monolith
#

I have a mechanic where the player can switch between two bodies, but when they switch bodies, the body not being used gets stuck in the animation they were in before switching. I want it so when they switch, the idle body goes into its idleanimation. what's the best way to tackle this problem?

woeful bridge
#

Its like one sentence

#

and the most overly complex code example i've ever seen for a doc page with one sentence

rocky canyon
#

u may even want to add a forgiveness timer.. like coyote time

rich adder
rocky canyon
#

but thats later on.. since ur only a few hours in

woeful bridge
#

ye

#

jumping isn't gonna be a huge part of the game anyways

#

I'm making a horror game to start off

#

cuz roblox wise its easier game wise so I'm gonna do that for unity

rocky canyon
#

textwalls ๐Ÿ‘€

rich adder
#

dont just mindlessly paste code, use links for code

fast monolith
#

ohhh how

#

sorry

eternal falconBOT
rocky canyon
#

copy n paste url's instead..

fast monolith
woeful bridge
#

I do got one question cuz docs don't really say I think

#

Do I still use a collider if I use a character controller

rocky canyon
#

no

#

the CC is the collider

woeful bridge
#

cuz the character controller seems to have a collider too but I saw a tutorial doing both

#

cool I figured

fast monolith
woeful bridge
#

do be the way of youtube tutorials is what i've discovered with roblox

rich adder
woeful bridge
#

anyways thanks for the help i'm gonna see what I can make

frail wind
#

god my variable code placement is disgusting

rich adder
#

wtf am i looking at my eyes hurt

slender nymph
#

fun fact, but it is 100% redundant to prefix variables with player on a class called PlayerCode. we know those variables are for the player

wintry quarry
rich adder
#

oh man.. you need a state machine

#

soo many bools you're gonna have many "in-between states" you're not going to want

frail wind
#

what worse is that my player script is make out of 90% if statement
even worst it working great ๐Ÿ’€ ๐Ÿ‘

wintry quarry
#

yep - you need an Enum not a bunch of bools

#

learn the state machine pattern

#

it will get rid of 80% of your if statements

frail wind
#

and i'm afraid to it to you all

timber tide
#

It's not that bad, but I'd probably split it up with groups a bit more and add some comments

rich adder
wintry quarry
woeful bridge
#

god dame unity makes me want to have 3 monitors

fast monolith
wintry quarry
woeful bridge
#

I live in a dorm desk isn't big enough :(

frail wind
rich adder
#

can you ever have enough monitors? I cant

woeful bridge
#

more than 3 is crazy

timber tide
#

statemachine would be preferred though if you do have a lot of bool checking going... but if it works for you, I'd just go with it until you realize the need to improve upon it

wintry quarry
#

My problem is no matter how many monitors I have I am incapable or organizing my windows in a productive way

rich adder
#

accidentally sprinting while sitting ๐Ÿ˜ฎ

timber tide
#

lel

#

full modular logic

rich adder
#

I split ma legs!

frail wind
#

just have to learn how to organize the script and it would be great for me

rich adder
#

organize maybe dont cram so much stuff in 1 monolith as mentioned lol

#

regions can help make it look neat but wont cure the problem

woeful bridge
#

is there a way to move your camera without holding right click

#

can I just make it where its wasd no matter what

#

its driving me insane

rich adder
#

all those speeds variables can easily be a struct for Movement stats or whatever

#

thats already less clutter in 1 script

rich adder
frail wind
woeful bridge
#

oh sorry

rich adder
#

and if you're not using VC, you should lol

woeful bridge
#

holy shit your right I can use git now that i'm off roblox

#

thats crazy

rich adder
#

ah yes version control is savior

rich adder
#

or maybe reset it after switch so you dont see any wonks

#

hard to say without seeing it

fast monolith
fast monolith
rich adder
woeful bridge
#

Is there a place to correct unity doc issues?

rich adder
woeful bridge
#

its not a major issue but one of the code samples is just really fucking dumb

#

oh that sucks

#

kk

woeful bridge
#
        playerVelocity.y += gravityValue * Time.deltaTime;
        controller.Move(playerVelocity * Time.deltaTime);```
rich adder
#

whats wrong with it ?

woeful bridge
#

multiplying deltatime then multiplying deltatime again

#

then 16 gravity just becomes a stupidly small number

wintry quarry
#

this is fine actually

rich adder
#

its correct

wintry quarry
#

you're not multiplying deltaTime twice into anything here

woeful bridge
#

so I'm suppose to set gravity to a stupidly high number?

rich adder
#

the only thing they should fix on that example code is the Move called twice instead they should've combined it into one call

wintry quarry
fast monolith
woeful bridge
#

a normal number with that code makes you fall at a insanely slow speed

#

removing the 2nd deltatime makes it normal

wintry quarry
rich adder
woeful bridge
#

player velocity is though

wintry quarry
#

it is not

#
playerVelocity.y += gravityValue * Time.deltaTime;```
#

gravityValue is being multiplied by deltaTime

woeful bridge
#

then the next line

#

its getting mutliplied again no?

wintry quarry
#

no

woeful bridge
#

wat

wintry quarry
#

that's the one time playerVelocity is being multiplied by deltaTime

#

the second line

#

a = a + (b * c) does not mean a = a * c

rich adder
#

gravityValue is being added to playerVelocity.y , and that(gravityValue) is being separately being calculated with T.dt

wintry quarry
#

note the + sign

woeful bridge
#

oh brotther

#

one sec

wintry quarry
#

mp4 if you want to embed a video in discord

woeful bridge
#

I know

#

why am I falling that slow then

wintry quarry
#

Due to some issue in your code that has nothing to do with what you posted above

#

Show it

woeful bridge
#
    {
        float horizontal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");
        
        if (playerVelocity.y < 0)
        {
            playerVelocity.y = 0f;
        }

        Vector3 move = new Vector3(horizontal, 0, vertical);
        characterController.Move(move * (speed * Time.deltaTime));
        

        playerVelocity.y += gravityValue * Time.deltaTime;
        characterController.Move(playerVelocity * Time.deltaTime);
    }```
#

its the same code in docs basically lol

wintry quarry
#

i mean

#

the docs don't have this

woeful bridge
#

it does

wintry quarry
#

which is pretty obbviously causing it

woeful bridge
#

I guess it also has grounded hto

wintry quarry
woeful bridge
#

but I had to remove that

#

but makes sense it checks for grounded

wintry quarry
#

Think about what that code is saying

woeful bridge
#

so yeah I can see that

wintry quarry
#

"if the object is falling faster than 0, make it fall at 0"

#

so that's clearly going to slow your fall

woeful bridge
#

yeah that do make sense

wintry quarry
#

The similar code in the docs indeed only happens when it's grounded, because they're just trying to make the velocity not build up like crazy when it's sitting on the ground.

woeful bridge
#

I'm still hella confused on the deltatime thing but

wintry quarry
#

deltaTime is very simple

woeful bridge
#

Its the time between frames

wintry quarry
#

it's literally just "the number of seconds that passed since last frame"

#

yes

woeful bridge
#

but its like

#
y = x * dt```
wintry quarry
#
playerVelocity.y += gravityValue * Time.deltaTime;

This one is the acceleration due to gravity. Increase velocity by n units per second per second.

characterController.Move(playerVelocity * Time.deltaTime);

This one is the actual movement.
Move the object by v units per second

#

think of them completely separaetely

#

because they are

woeful bridge
#

I guess that makes more sense I think

#

I've never really messed with gravity ig before

#

Cool thankies

wintry quarry
#

not x = 1 * dt

woeful bridge
#

Ik I just forgot the + lol

wintry quarry
#

important difference ๐Ÿ˜›

woeful bridge
#

but I guess if the number if increasing I can see why the dt works

wintry quarry
#

it changes things a lot from making x be really small, to making x actually grow

woeful bridge
#

yeah if it grows that makes more sense

wintry quarry
#

It might make things more clear to just like Debug.Log the values each frame

rich adder
woeful bridge
#

no no I understand now

wintry quarry
#

It's really this

woeful bridge
#

Its late i'm sorry coding brain rot is hitting hard Waaahh

rich adder
#

flashed banged ๐Ÿ˜ตโ€๐Ÿ’ซ .
also not a code question

woeful bridge
#

I assume logically I should cap how much gravity can increase so it doesn't just like eventually zoom you to mak 5 if you fall far enough

wintry quarry
#

acceleration is gravityValue which stays constant
playerVelocity is velocity
and the position is the position

frail wind
#

just do little bit of reorganizing. Now it look better

nova ivy
#

i'm trying to make a draft idle game, how do I properly display the acquired resources / second?

#

i got this solution off an old video but it doesn't properly reflect the actual gain/second

wintry quarry
#

the code you shared doesn't seem to have anything to do with displaying anything though.

nova ivy
#

mult1 is static as 1 so it doesn't do anything

wintry quarry
nova ivy
#

i would have figured since update runs every frame, that just by multiplying by 60 that would be an accurate representation but it's off as well

wintry quarry
#

But you asked about:

how do I properly display the acquired resources / second

#

i don't see anywhere you are trying to do that

#

I see totalPoints text

nova ivy
#

mult1Text is resources/second

wintry quarry
wintry quarry
#

You said it's static as 1

#

doesn't that mean you only ever get 1 point per second

#

I'm confused about your code and also don't feel like I have enough context.

nova ivy
#

for whatever reason it doesn't

wintry quarry
#

there's absolutely not enough context here to help you

nova ivy
#

okay okay

wintry quarry
#

Feel free to share full scripts in paste site(s)

#

!code

eternal falconBOT
nova ivy
#

sure thing

unreal snow
#

Anybody?

nova ivy
#

is there a specific reason pastebin isn't listed despite being the most popular one?

slender nymph
#

because it sucks. it's riddle with ads and crypto scams

nova ivy
#

okay then

wintry quarry
#

Why is it a fixed value

nova ivy
#

so as you can see counter stores the points, totalPoints is the text object to display them, mult1 would be an added increasing points per second that is currently fixed at 1, updateTime is the "refresh rate"

wintry quarry
#

Why aren't you using Time.deltaTime

#

You need to use Time.deltaTime or your point counter is going to be framerate dependent

#

Basically mult1 does NOT mean points per second because you are not using Time.deltaTime

#

it means points per frame * whatever updateTime is

nova ivy
#

i mean am I not using Time.deltaTime? or rather how else would I use it

wintry quarry
#

counter += mult1 * updateTime;

#

that is not Time.deltaTime

#

that is updateTime which is some unchanging thing you set in the inspector

#

Ok wait I see what you're trying to do

nova ivy
#

you can set it to 0.01 for it to be real time

wintry quarry
#

Nah you have a bug here

#

A couple actually

nova ivy
#

๐Ÿ…๐Ÿ…

wintry quarry
#
  1. it's not points per second right now. It's points per updateTime right now.
  2. setting the ticker to 0 is incorrect
#

because setting it to 0 means you lost fractional seconds

#

which will build up

nova ivy
#

so I should be subtracting something instead? not sure what

wintry quarry
#

You also shouildn't be skipping the frames when the points are updated for the ticker

#

so at least 3 things are incorrect here

#

Oh also your comparison is backwards too ๐Ÿ˜ฌ

nova ivy
#

wait are you sure?

#

because ticker is supposed to grow with time until it reaches the refresh rate

#

at which point it's reset back to 0 and the points are updated

wintry quarry
#

You want something like this:

void Update() {
    ticker += Time.deltaTime;

    if (ticker > updateTime) {
        ticker -= updateTime;

        // mult1 points per second for updateTime seconds
        counter += mult1 * updateTime;
        totalPoints.text = counter.ToString("F1") + " points";
    }
}```
wintry quarry
#

subtracting updateTime is correct

nova ivy
#

no yeah i understand that much

#

but in regards to the comparison being backwards

wintry quarry
#

if (ticker < updateTime) doesn't make sense

#

well wait

#

ok I see what oyu're saying

#

sorry it's fine it's just

#

doing if/else was wrong

#

you should be increasing the ticker always

#

not skipping the update frames

nova ivy
#

i see that alright

#

let me test that out

wintry quarry
#
    public void Add()
    {
        totalPoints.enabled = true;
        counter++;
    }```
#

this throws a wrench in the works though

#

what's going on with this?

nova ivy
#

so that first line is jank. it's so the points only start displaying whenever you click the button for the first time

#

wasn't sure how else to implement it

#

and then counter++ is so even if you are gaining points per second, you can still manually click points in

wintry quarry
#

ok as long as it's fine that those extra points aren't reflected in the points per second thing

nova ivy
#

no absolutely

#

those just go to the total

nova ivy
#

another minor thing, that TextFadeOut function at the bottom sort of overlaps with itself when clicked very rapidly

woeful bridge
#

Ok is this sortaish look like how a character controller is suppose to work

    void Update()
    {
        float horizontal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");
        bool isGrounded = Physics.CheckCapsule(
            characterController.bounds.center ,
            new Vector3(characterController.bounds.center.x , characterController.bounds.min.y+.1f , characterController.bounds.center.z ) ,
            0.18f,
            3
        );
        
        if (isGrounded && playerVelocity.y < 0)
        {
            playerVelocity.y = 0f;
        }

        Vector3 move = new(horizontal, 0, vertical);
        playerVelocity.y += gravityValue * Time.deltaTime;
        characterController.Move(((move * speed) + playerVelocity) * Time.deltaTime);
        

        if (isGrounded && Input.GetKeyDown(KeyCode.Space)) {
            playerVelocity.y += Mathf.Sqrt(jumpHeight * -2.0f * gravityValue);
        }

    }
}
nova ivy
#

i can record what I mean if you need some visual

wintry quarry
#

Not from this script certainly

nova ivy
#

oh did I not include it

wintry quarry
#

oh maybe it's commented out

nova ivy
#

yeah it's in AddMult1, commented out

#

it resets the alpha of a text to 1 and fades it back down to 0

#

but the thing is if I click it midway the fading out animation it won't restart the timer, it'll just play out the remaining fadeout

woeful bridge
#

Aka the shape cast touches before my collider

#

but my attempts to fix that just- make it where I can't jump off of slopes

#

I guess I could set the gravity to 1 instead of 0

#

to a player I doubt they'd ever notice

slender nymph
#

do note that you are specifically not doing a cast, you are checking within a specific area

woeful bridge
#

Oh

#

wouldn't a shape cast still have the same issue though

#

oh right its a query

#

but either way

slender nymph
#

use a sphere cast (because there's really no need to cast an entire capsule to check for ground)

#

and also make sure you use the physics debugger so you can actually see where your queries are

woeful bridge
#

wheres that? lol I've been using unity for 3 hours

#

probably 4 now

#

tru

nova ivy
#
{
    return Physics2D.OverlapCircle(groundCheck.position, 0.5f, Ground);
}```
is what I use
#

wait

#

you're probably in 3d

#

no?

slender nymph
#

a cast is more useful than an overlap circle, especially when handling slopes because you can get more info from it like the normal of the surface the character is on

woeful bridge
#

I won't really need info in the long run for the type of game i'm making

#

But I do agree I need to shrink the area

slender nymph
#

i mean, unless you want the character controller to move inconsistently along slopes then you do need the normal. you would ideally be projecting your input or velocity on the normal to get the proper movement direction

woeful bridge
#

I'm just making press space bar to jump rn lmao I'll figure out shape casting later on

lilac plinth
woeful bridge
#

Honestly for now I might just raycast down

slender nymph
eternal falconBOT
slender nymph
#

damn i guess it will only respond to one command at a time. here's the !IDE configuration ๐Ÿ‘‡

eternal falconBOT
lilac plinth
slender nymph
#

yeah so get your IDE configured and check your spelling

woeful bridge
#
Physics.SphereCast(characterController.bounds.center, .18f )```
Regretably trying to do a sphere cast

The error is 
Argument 1: cannot convert from 'UnityEngine.Vector3' to 'UnityEngine.Ray'CS1503
but its... a vector3? the params want a vector 3????????
lilac plinth
#

ide configurated

slender nymph
#

screenshot the entire IDE window

lilac plinth
#

what is an ide window?

ivory bobcat
#

Check the docs for the available overloads.

slender nymph
woeful bridge
#

Nvm I figured it out thats the dumbest thing ever

slender nymph
#

did you realize you didn't have the correct parameters? or all of the required ones for the overload you wanted to use?

ivory bobcat
woeful bridge
#

yeah

slender nymph
# lilac plinth alright

yeah the left screen wasn't necessary. but the spelling error is underlined, pay attention to it.

lilac plinth
ivory bobcat
slender nymph
woeful bridge
#

I figured it out

#

I just wish it didn't hit me with the redline while typing it

woeful bridge
#

Make me think I did something wrong

lilac plinth
#

or gameObject?

slender nymph
ivory bobcat
#

public static bool SphereCast(Vector3 origin, float radius, Vector3 direction, out RaycastHit hitInfo, float maxDistance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal);
where the first four arguments are required.

lilac plinth
slender nymph
#

no. if you think that is correct, then please complete the beginner c# courses pinned in this channel

lilac plinth
#

i see, can I at least know what the code needed btw? is it like a variable or object define?

#

maybe I declared the public wrong right?

#

the guide told me to do this

slender nymph
#

it needs you to spell the property you are trying to access correctly. look at the relevant documentation and all of the other locations you access the desired property at

lilac plinth
slender nymph
lilac plinth
#

alright

#

I'll paste it in

slender nymph
#

you should also maybe bother reading it too, and compare what you have with what is there

#

your code actually has two things wrong with it now that i take another look

lilac plinth
#

it've red it and it's the same gameObject

slender nymph
#

it's literally not

lilac plinth
#

there's another error now when i paste it in : <

slender nymph
#

there are beginner c# courses pinned in this channel that will cover the absolute basics, such as the fact that c# is case sensitive so gameObject != GameObject

lilac plinth
#

} expected [Ln82, Col 2]

#

should I add another }?

slender nymph
#

considering the code you posted as a text file is missing the closing brace for the method, you probably do need another one. of course that entirely depends on what you copy/pasted and where

lilac plinth
#

all problems are fixed now

#

ty

lilac plinth
#

I will look into the C# doc you recommend ty

slender nymph
#

start with beginner c# courses, then when you understand the absolute basics of the language the junior programmer pathway on the unity !learn site is a good next step

eternal falconBOT
#

:teacher: Unity Learn โ†—

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

woeful bridge
#

the only other real idea I have is just checking when the y stops decreasing at this point lol

quick epoch
#

Hello guys i would like to ask you something... so i got a top down 2d rpg game snap grip walk style and i got an enemy roaming int the map... but as he roams and im coming with my player next to him when roaming he does not collide with player but enter same grid cell, both players and challenger have box collider and rigid body.. could anyone give me some assistance?

woeful bridge
#

Like there has to be like a real way to solve this rather then hovering above the ground lol

wintry quarry
woeful bridge
#

I think its like snapping rotation and snap walking

quick epoch
#

ive just ticked the snap tp grip option at the scene, and its 16x16 gridcell , there is no way to move diffently.. like tibia

quick epoch
#

yes grid

wintry quarry
#

ok if you're using a grid-based movement system why would you have colliders and Rigidbodies?

#

That sounds completely contradictory.

quick epoch
#

i got a solidObjects layer right for tiles

#

but for other objects the tutorial i was following showed me that way of collision

wintry quarry
#

Pick one. Use the physics engine or use a grid-based system

#

don't try to do both

quick epoch
#

its easy to say when you understand and i dont mate

#

probably would be the grid-based

wintry quarry
#

If you're using a grid based system:

  • Use your grid data structure to determine if a square is occupied already or not to disallow moving into it
    If you're using the physics engine:
  • Fully embrace that and move your objects using it and they will naturally not be able to overlap
quick epoch
#

ok sure

#

i understand you concept for sure

wintry quarry
#

There should be no "probably"s, you pick one or the other

quick epoch
#

grid for sure

#

i came form gamemaker so you would have mp_grid there

#

add the instances that are forbidden to walk in

wintry quarry
#

In C# you could use a multidoimensional array (i.e. YourClass[,] or you could use e.g. a Dictionary<Vector2Int, YourClass> to track what's in each space

quick epoch
#

but still flunky u have to make checks to see if cell was completely empty and stuff

wintry quarry
#

you'd do something similar

#

basically keep track of which objects are in which grid spaces

#

and then you just check if the space is empty or not

quick epoch
#

multidimentional array right?

#

that what i should study then mate?

wintry quarry
#

That is one of the options I mentioned, yes

quick epoch
#

i will give it a look thank you very much

timber tide
#

if you want to serialize it though multi-dimentionals don't work

#

so something like a List of lists would work, otherwise if you only need to build it then constructing it in Start() is fine

gloomy cosmos
#

Umm, running into an error I can't make sense off. I have 2 classes:

{
    protected IStateMachine DefaultState;
    ...
}```
Child class:
```public class SimpleBullet : BulletScript
{
    DefaultState = null;
    ...
}```

I get an error that 'DefaultState' does not exist, but why? I thought protected meant that child classes could access the variable?

Exact error:
```The name 'DefaultState' does not exist in the current context.```
north kiln
#

Are you accessing it in a function?

gloomy cosmos
#

Oh it works if I do it in a function

#

I guess that makes a lot of sense, just threw me off

floral trout
#

Hey I had set up the new input system and created a input actions asset. How do I reference the Input Actions asset with the actions I made in it?

rich ice
hexed terrace
cold pier
#

Hi, i'm beginner and when i put the line for the horizontalMovement the velocity is crosses out and i dont know why ? ( You can tell me in french )

swift crag
#

Your code editor will show something crossed out when it is obsolete

hexed terrace
#

put your cursor over the red line and read the error

swift crag
#

yes, it'll explain

#

(you should always start by reading the error message)

hexed terrace
#

also !screenshot

#

bleh, is that not a cmd? :E

rich ice
cold pier
#

@rich ice thank you ๐Ÿ˜Š, @hexed terrace i try to put cmd for moove my character in game. I Read the red line but i learn by an video to have 6 years ago

#

Thank you all

rich ice
#

can you click this button here and send us the error message?
pouvez-vous cliquer sur ce bouton ici et nous envoyer le message d'erreur ?

hexed terrace
#

as a screenshot, not a photo

rich ice
#

a window like this should appear
une fenรชtre comme celle-ci devrait apparaรฎtre

cold pier
#

Yes, i'm sorry i do some research for understand my eroor and i understand a little beat

#

I try to do in screen shot i dont really know the method ahah.

exotic prism
#

Hi everyone,
I have a problem. My character starts jittering while rotating. The strange part is that this jitter only happens in the Game window, not in the Scene window. Any help would be nice.

cold pier
#

@rich ice

The cosole tell me : CS1061 'Rigidbody has not definition for 'linearvelocity' and no access method 'linearvelocity.

CS1003 error syntax ','

I understand velocity is obsolete but i must pit Rigidbody2D for the script PlayerMovement

swift crag
#

Show us the actual code.

rich ice
#

The cosole tell me : CS1061 'Rigidbody has not definition for 'linearvelocity' and no access method 'linearvelocity.
i think that's just a unity 6 thing. i think you just have to change it to linearVelocity.y (i may be incorrect, i rarely use unity 6)
je pense que c'est juste une question d'Unity 6. Je pense que vous devez juste le changer en linearVelocity.y (je me trompe peut-รชtre, j'utilise rarement Unity 6)

swift crag
#

yes, you have to use linearVelocity instead of velocity now

#

this is true for both Rigidbody and Rigidbody2D

eternal falconBOT
rich ice
swift crag
#

Please use a paste site for large blocks of code.

#

They do not send correctly on Discord when you just send the code directly, especially for mobile users

rich ice
#

please, use one of the paste sites above. while i can read that code, i can also read house of leaves

swift crag
#

lmao

cold pier
#

""" public class PlayerMovement : MonoBehaviour
{
public float moveSpeed;

public Rigidbody2D rb;
private Vector3 velocity = Vector3.zero;





void FixedUpdate()
{
    float horizontalMovement = Input.GetAxis("Horizontal") * moveSpeed * Time.deltaTime;



    MovePlayer(horizontalMovement);
}

void MovePlayer(float _horizontalMovement)
{
    Vector3 targetVelocity = new Vector2(_horizontalMovement, rb.velocity.y);
    rb.linearVelocity = Vector3.SmoothDamp(rb.linearVelocity, targetVelocity, ref velocity .05f);
}

}
"""

#

I'm sorry i'm not know discord ^^'

exotic prism
hexed terrace
#

the ` is usually next to 1

cold pier
#

J'ai rรฉussi hourra

#

it is difficult for me to see immediately where I have to change and the consequences that this implies

rich ice
#

the error list helps a lot. you should see what error you get (assuming you make one)

cold pier
#

if I use LinearVelocity the consol tel me is not correct with the domain Rigidbody. I see my error

swift crag
#

LinearVelocity is not correct.

#

linearVelocity is correct.

cold pier
#

Oh, yes, the convention ^^'

frail hawk
#

why not let intellisense do the job

rich ice
#

capital letters are important

cold pier
cold pier
rich ice
eternal falconBOT
rich ice
exotic prism
rancid tinsel
#

hey guys i followed advice from this video, but im a bit confused on how to implement ability cooldowns? how do i set a cooldown to an instance of a scriptable object, if thats even possible? https://youtu.be/0HCOZo5N-t4

cold pier
#

lol, all timelap lost ! omg

#

I dont know how but all my project is empty now

swift crag
#

you may have the wrong scene open

cold pier
#

i try to open by ctrl+o ^^'

#

i try to open "recent scene " same, i do a research ^^

swift crag
#

you can search your project folder for scenes with:

t:scene

rich ice
#

^ (same thing, but this also works)

cold pier
#

Yes is the good option thank you, i try to reload all. i have all my Grid and tilemap thank you

visual linden
rancid tinsel
#

since theyre meant to be readonly

cold pier
#

@swift crag @rich ice all is right thank you โค๏ธ

silk meteor
#

so ive put all my player data inside of a different scripts, each aspect being a property, however its not showing up in the inspector, are properties not serializable?

cosmic dagger
rancid tinsel
#

and then how does it tell the ability its off cooldown

cosmic dagger
silk meteor
#

alr thanks

rancid tinsel
#

maybe scriptable objects are not the play here, ill experiment with some other methods

rich adder
polar acorn
# silk meteor

Properties can't be serialized, but you can access the invisible backing field with an attribute by using the prefix field:. So, you'd use [field:SerializeField] to apply the SerializeField attribute to it. Note, that this is directly changing the backing field, not the actual property, so if you were to do something like put an event in the set accessor, that event would not be called

silk meteor
#

i see

#

well thanks

rancid tinsel
#

so far the plan is for them to be one-shot abilities so I was hoping I wouldn't need that

rich adder
rich ice
#

what usage does { get; set; } have on its own?

#

i know you can put some extra functionality inside it but i have no idea what it does on its own

rich adder
#

if you open the brackets then you can add items inside

#

get and set are like functions (called accessor actually)

polar acorn
#

Practically: It allows the property to be chosen as a target or source of a unity event.

#

You can't have a UI Input dynamically set a string variable, but you can for a string property

rich ice
#

o, that actually sounds really useful

rich ice
rich adder
rich ice
#

properties, i cant imagine living without the documentation lmao

#

i've been programming for a while now but there's still tons of basic stuff i find that i've missed

woeful bridge
#

So I'm having a issue where my shape cast is detecting I'm grounded before my like collision box itself is grounded
But moving it up prevents me from detecting slopped objects
My solution was instead of setting gravity while I'm on the floor to 0 I set it to -1 but I feel like this is a poor choice
Any advice? Heres the code

    void Update()
    {
        float horizontal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");

        RaycastHit hit;

        bool isGrounded = Physics.SphereCast(characterController.bounds.center, .18f, new Vector3(0, -1, 0), out hit, characterController.bounds.size.y/2, 3);
        
        if (isGrounded && playerVelocity.y < 0)
        {
            playerVelocity.y = -1f;
        }

        Vector3 move = new(horizontal, 0, vertical);
        playerVelocity.y += gravityValue * Time.deltaTime;
        characterController.Move(((move * speed) + playerVelocity) * Time.deltaTime);
        

        if (isGrounded && Input.GetKeyDown(KeyCode.Space)) {
            playerVelocity.y += Mathf.Sqrt(jumpHeight * -2.0f * gravityValue);
        }

    }
}```
#

When it was set to 0 I would just very SLOWLLYY fall the rest of the .4 y idk what unit unity uses roblox used studs lol

rich adder
woeful bridge
#

its casting from my player

rich adder
#

I think thats why I used overlaps

polar acorn
rich adder
#

isGrounded is trash

woeful bridge
#

IT JUST RETURNS FALSEEEEE

swift crag
polar acorn
#

It works fine as long as you include some downward gravity in the one time per update you call it

woeful bridge
#

NO MATTER WHAT >:(

#

I DID :(

swift crag
#

You must actively move the controller into the ground for isGrounded to become true

#

Gliding along the ground doesn't count

woeful bridge
#

I did tho

#

I had gravity pushing down

high surge
#

Hi
does anyone know the version controll well, i have a problem where i got one version with one player, and my friend a verison with two players, when i watn to merge from his version it tellls me files need to be resolved or so, i do the conflict resolve and then i still cant merge without checking in again but then it beginns from the beginning again.

woeful bridge
#
        characterController.Move(((move * speed) + playerVelocity) * Time.deltaTime);```
rich adder
#

tbh thats going backwards, I would figure out whats wrong with the spherecast. Also give overlap a try, never have issues with it

woeful bridge
#

I did use overlap but someone said its bad and told me not too but I realize every programmer disagrees with every programmer so lmfao

rich adder
#

the only "bad" about it is, it doesnt give you the hitInfo like Casts do. So you need manually check slope angles with another ray

woeful bridge
#

I mean I did fix the issue though with the gravity sorta by setting gravities default state to -1 while grounded

#

which honestly I feel like isn't the worse thing ever

#

I was just curious if there was a better solution

visual linden
#

But your gravity is -9.81 normally?

woeful bridge
#

yes

swift crag
woeful bridge
#

well

swift crag
#

You don't need to manually set the velocity to anything

woeful bridge
#

Let me rephrase that

woeful bridge
swift crag
#

ah, I see the issue

woeful bridge
#

I have to manually code in gravity so I have to apply it to the force

swift crag
#

you're building up velocity forever in playerVelocity

woeful bridge
#

yeah thats why I have the if statment

swift crag
#

If you do want to keep track of that separately, then you need to clear it when grounded, yeah

polar acorn
#

You need to set the vertical speed to 0 if you're grounded, then apply one frame of gravity

woeful bridge
#

I'm using a character controller so I have to apply my own gravity

rich adder
#

yes thats exactly what the original Move. example code had

polar acorn
#

So if you're grounded your speed is basically constantly at "one frame of gravity" to move you into the ground

woeful bridge
polar acorn
woeful bridge
#

yeah but if I move the cast up I can't detect slopes

polar acorn
#

Again, don't use a cast at all

rich adder
#

im willing to bet the issue is your Spherecast is already inside the ground when its trying to go (0,-1,0)

polar acorn
#

use isGrounded and properly apply gravity every frame

woeful bridge
#

I did do that :( But sure I'll try it again lol

rich adder
#

isGrounded is flimsy af especially fast on sloped surface

woeful bridge
#

OH

#

WHEN I USE ISGROUNDED IT DOESN'T WORK

#

BUT WHEN SOMEONE ELSE TELLS ME TOO

#

IT WORKS

polar acorn
#

Then you did something wrong the first time

woeful bridge
#

I copy and pasted my code from yesterday :(

#

I changed one thing

#

I move is grounded below the move code

#

when before it was above it

#

does that really matter?

polar acorn
#

Yes

swift crag
#

Yes, because moving the character controller changes its state

woeful bridge
#

the docs showed it being called before the move code :(

polar acorn
#

Is grounded returns true if the previous move call hits the ground

woeful bridge
#

ok well thanks lol last time i'm trusting doc code

polar acorn
#

You should be calling Move exactly one time, in update, as the last thing you do

woeful bridge
#

wait so grounded should be called before or after move

polar acorn
#

If you call it in more than one place, you're going to run in to issues

rich adder
#

to be fair the idiots who put the example code made 2 Move calls

polar acorn
#

Grounded should be checked before the move, some downward force should be applied if it is grounded, and then move should be called. once

#

If you have .Move in more than one place, where you put the code determines whether it works or not

rich adder
woeful bridge
#

so like this?

    void Update()
    {
        float horizontal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");

        Vector3 move = new(horizontal, 0, vertical);
        playerVelocity.y += gravityValue * Time.deltaTime;

        bool isGrounded = characterController.isGrounded;

        if (isGrounded && playerVelocity.y < -1)
        {
            playerVelocity.y = -1f;
        }

        characterController.Move(((move * speed) + playerVelocity) * Time.deltaTime);

        if (isGrounded && Input.GetKeyDown(KeyCode.Space)) {
            playerVelocity.y += Mathf.Sqrt(jumpHeight * -2.0f * gravityValue);
        }

    }```
#

nvm

#

docs had it being set to 0 if you are grounded but if its 0 then grounded doesn't work it seems

woeful bridge
#

well when its 0 grounded doesn't find ground

polar acorn
#

Here's how it should go:

  1. Calculate your horizontal movement however necessary
  2. Check if you are grounded. If so, set your y velocity to 0. Otherwise, leave it u changed.
  3. Add your gravity value to the y velocity.
  4. Apply changes to your vertical velocity from jumping
  5. Move the character
woeful bridge
#

when I set it to like idk -.5 it does

rich adder
polar acorn
#

In that very specific order

rich adder
#

did you also change the value the right of <

woeful bridge
#

Oh I see the issue

#

I get it now

#

its because I did gravity calculation THEN set it to 0 so probably something something computers like decimals so I was technically like barely hovering over the ground?

#

or I'm shitzo and just the like deltatime of gravity fixed it

#

idk

#

It works now tho

#
    {
        float horizontal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");

        Vector3 move = new(horizontal, 0, vertical);

        bool isGrounded = characterController.isGrounded;

        if (isGrounded && playerVelocity.y < 0)
        {
            playerVelocity.y = 0f;
        }

        playerVelocity.y += gravityValue * Time.deltaTime;

        characterController.Move(((move * speed) + playerVelocity) * Time.deltaTime);

        if (isGrounded && Input.GetKeyDown(KeyCode.Space)) {
            playerVelocity.y += Mathf.Sqrt(jumpHeight * -2.0f * gravityValue);
        }

    }```
rich adder
woeful bridge
#

I should do the jump before move

#

oops

#

honestly for one day of unity i'm happy with this progress

swift crag
#

Also, one thing you may want to tweak

#

the default minimum move distance is 0.001

#

I don't actually understand why you shouldn't just set that to zero

#

It often causes problems at high framerates

#

at 100 fps, that means you can't move below 0.1 meters per second!

woeful bridge
#

I did see someone saying that and I already tweaked it

#

If I rotate the parent of the camera would the camera rotate with it?

#

Aka I'm asking cuz its not lol

#
        float mouseX = Input.GetAxisRaw("Mouse X");

        transform.Rotate(0, mouseX, 0);```
woeful bridge
#

weird wonder why it isn't

#

maybe I locked it rotation somehow

rich adder
#

are you forcing Y rotation through script

#

for cam

woeful bridge
#

no cuz I just wanted to get x working

#

its not rotating at all when my character is rotating

rich adder
#

so You don't have any camera rotation scripts ?

woeful bridge
#

nope

rich adder
#

and which object its on

woeful bridge
#

a new one and its on my capsule

rich adder
#

hnn and camera is child of this?

woeful bridge
#
using UnityEngine;

public class CameraScript : MonoBehaviour
{

    public float xSensitivity = 150f;
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    // Update is called once per frame
    void Update()
    {
        float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * xSensitivity;

        transform.Rotate(0, mouseX, 0);
    }
}
rich adder
woeful bridge
#

oh ok

rich adder
#

mouse inputs already frame-rate independent

woeful bridge
#

I'll fix it after my other issues

rich adder
#

thats why you cranked rotation to 150 lol

#

but yeah something weird goin on

woeful bridge
#

My only idea if that my movment isn't moving based on the local vector

rich adder
woeful bridge
#

wait

#

I might be shitzo

#

Hoild on

#

wait I think I decribed my problem wrong

rich adder
#

if cam is child of capsule it should rotate with it unles you have a mouse look script preventing rotation on Y axis

woeful bridge
#

I'm so confused hold on Waaahh

#

Ok I described that in the complete wrong way idk why I said this

#

My issue is that my character isn't moving based on the local vectors

#

But I think I can fix that

#

I don't know how I confused myself this badly

#

just ignore me lol

woeful bridge
#

Yeah I'm moving in the global plane

#

not the local plane

rich adder
#

you aren't using the forward anywhere

woeful bridge
#

yeah ik

rich adder
#

.Move is relative to CC no ?

woeful bridge
#

yeah I think so idk

swift crag
#

Move works in world-space, so you'd need to use transform.forward to make the character move forwards, not Vector3.forward

rich adder
#

ahh right. You also can use InverseTransformDirection iirc

woeful bridge
#

ye I fixed it

#

I'm realizing unity wise I gotta do a lot more vector math than roblox made me lol

swift crag
woeful bridge
#

I just relooked at my roblox code to remember how to get to the local vectors

rich adder
swift crag
#

That would be backwards.

#

move is not a world-space direction right now

#

well, I mean

#

you can interpret it as one

rich adder
#

inside .Move though

#

i forgot tbh
I just do the
move.y * forward + move.x + right
lol

#

someone once told me about the other method tho

swift crag
#

you mean move.y * transform.forward ?

#

because then that would be correct

rich adder
#

yea

swift crag
#

transform.forward is the world-space direction your transform is facing forwards in

#

These are equivalent:

#
transform.TransformDirection(Vector3.forward);
transform.forward;
#

I generally just construct a local-space move vector and then transform it into world-space

#

These are also equivalent:

#
transform.InverseTransformDirection(transform.forward);
Vector3.forward;
rich adder
swift crag
#

Correct. That will give you world-space directions.

rich adder
#

this gets rid of that sus
transform.forward + transform.right bs

swift crag
#

Both are fine.

rich adder
#

less clutter ๐Ÿ˜›

swift crag
#

I prefer the former because it's a little more obvious what's happening, though

crimson pike
#

is there any concern about increasing rotation value beyond a certain limit? e.g. i have an animation that rotates the game object 720 degrees (barrel roll), if i keep doing that would it possibly hit a ceiling and crash?

#

or do i have to reset its rotation value at some point?

keen dew
#

It's a float so the maximum value is 340282346638528859811704183484516925440. So you're probably safe.

bright arch
#

is there anything inherently wrong with doing this? i originally wrote code in the update function but seeing as i want to do multiple unrelated things in update and want to keep it more organized, i want to put several functions in there

keen dew
#

That's fine

bright arch
#

thx

polar acorn
rich ice
#

if its only like 1-10 lines then i'll just use a comment

#

if its anything more then i'll typically do that

bright arch
#

i didnt know that! i thought it would be creating garbage somehow (i dont know what constitutes that but it just feels dirty to call functions all the time)

polar acorn
#

You would need to call four billion extra functions in order to produce one second of slowdown

bright arch
#

thank you very much. in all tutorials ive seen they just write the code straight into the update function, had no idea this was what you should be doing

cosmic dagger
cosmic dagger
bright arch
#

that makes sense, thank you

crimson pike
rich ice
#

damn, now i feel like i need to start breaking my code up into more methods guh

rich ice
#

if it involves a .cs file then it probably goes in this channel

rich tusk
#

i see

#

where should i put it instead?

rich ice
rich tusk
#

i see thank you

heady mesa
#

how do i fix?

burnt vapor
queen vigil
rich ice
#

#๐Ÿ’ปโ”ƒunity-talk is pretty universal, the specific channels are for more common issues (or so i assume, idk i didn't make the server daihakkenshrug)

rocky canyon
#

im a member of 3 Unity discord servers.. none of which have dedicated Linux channels

bright arch
#

idk how i screwed this up lol isnt a vector3 just 3 floats?

rocky canyon
#

yes. but theres specific ways to do that

bright arch
#

oh wait i think just putting "new Vector3" fixed it

rocky canyon
#

new Vector3(floatX, floatY, floatZ);

verbal dome
bright arch
#

thank you!

crimson pike
#

hm, this isn't working anything like i thought it would. is there a better way to do this? trying to have a barrel roll/evasion animation move the player child object (the sphere is at the same level in the heirarchy and is just there to show where the parent object position is (the center is offset from teh actual parent but just for visibility))

#

thats the event triggering at the end of the animation

#

also its only working sometimes, randomly the parent position doesn't update

bold plover
#

So for GitHub do changes suggested on the site adjust the code on my machine directly? Noob question just want to make sure I don't accidentally obliterate my files.

rich ice
#

pretty sure changes only get made on your device if you git pull

slender nymph
#

you will also be required to pull changes if any exist on the remote before you can push any

bright arch
#

is it fine to have something moving in one direction basically indefinitely? an instance probably wont move for enough time that it matters probably, right? currently i have the x position of a gameobject gradually going down

#

after like 10 seconds it goes from ~2 to ~(-10)

#

(this is meant to be a loading screen of sorts though so it wont be up for very long anyway)

slender nymph
#

issues only arise once objects get to about 10k units from the origin

bold plover
#

So only if I pull them. Got it.

#

ty

slender nymph
#

again, you have to pull changes before you can push new ones

crimson pike
crimson pike
#

Is using animations for movement too janky or bad practice? As a rule of thumb?

steep rose
#

If your player or object is going to be solely root motion or an active ragdoll of sorts, then no it shouldn't be janky. I definitely would not mix animation based movement with normal scripted movement though.

crimson pike
#

Trying to fix the position post animation has some janky results and I canโ€™t figure out what it is

steep rose
#

I would not mix animation based movement with scripted movement, why not just make it solely scripted movement for something that simple?

crimson pike
whole cliff
#

how do i fix my camera being on the left?

#

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

public class FollowPlayer : MonoBehaviour
{
public GameObject player;
private Vector3 offset = new Vector3(-8, 5, -7);
// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void LateUpdate()
{ //offset the camera behind the player by adding to the player's position
    transform.position = player.transform.position + offset;
}

}

slender nymph
#
  1. !code
  2. what direction do you think offsetting the position by -8 units on the X axis will be?
  3. obligatory: use cinemachine
eternal falconBOT
crimson pike
whole cliff
#

why can i go trough the ramps

#

isnt the collider on?

slender nymph
#

show the car object and how you are moving it

whole cliff
#

the code?

slender nymph
#

yes, and the inspector for the car

whole cliff
#

added rigidbody and now i also fall trough the ground

slender nymph
#

probably because it has no collider

whole cliff
#

the car?

slender nymph
#

yes

inland cobalt
#

Hey all, I have the position and rotation of VR controllers that i want to display as an object within unity, the thing is. I want these controllers ingame to have collision, but trying to update their position with MovePosition() and MoveRotation() looks very jittery when updating at the freqency of the physics system, rather than at 120FPS, even with my rigidbody set to interpolate. Is there anyway i can get my controllers position to update based on framerate, while still maintaining physics?

grand snow
inland cobalt
grand snow
inland cobalt
#

i feel like im approaching this in a bad way

#

but not sure how else to

grand snow
#

they are kinematic right?

inland cobalt
grand snow
#

I wonder though due to the interpolation being to the old world pos, as you move the character it is now going to be incorrect ๐Ÿค”

#

im not fully sure how it interpolates

inland cobalt
#

ill try with kinematic one sec

grand snow
#

you can make it teleport too with .position

inland cobalt
grand snow
inland cobalt
#

this is what my hierarchy looks like

verbal dome
#

but whenever i move the parent it is attached to, it starts to jitter
Yes, moving a rigidbody's parent transform will mess with the physics and interpolation

#

Just like you would move the rigidbody's transform directly

inland cobalt
#

fyi i am moving the parent with AddForce, not .position

verbal dome
#

Try having them as "siblings" instead?

#

And make the hands follow the player manually with forces or something

inland cobalt
#

So i just reference the player in my hands script and work out the position relative to that?

verbal dome
#

Yeah

inland cobalt
#

alright i'll give it a go, thanks

verbal dome
#

You could also use some type of Joint but I think you get better control here if you do it manually

inland cobalt
#

tried with both Update and FixedUpdate

verbal dome
#

What is your setup currently? The hands don't have a moving parent now, right?

#

You can show your code and I can take a look if I see anything problematic

inland cobalt
#

nope, its top level of the heirarchy

inland cobalt
# verbal dome You can show your code and I can take a look if I see anything problematic
public class ControllerTracking : MonoBehaviour
{
    public enum Hand
    {
        Left,
        Right
    }

    [SerializeField] private Hand hand;
    [SerializeField] private Transform offset;

    private Rigidbody rb;

    private Dictionary<string, InputAction> actions;

    private Vector3 position;
    private Quaternion rotation;

    private void Awake()
    {
        rb = GetComponent<Rigidbody>();
    }

    private void Start()
    {
        actions = InputManager.Instance.GetActionMapFromDefault((hand == Hand.Left ? "Left" : "Right") + " Tracking");
    }

    private void FixedUpdate()
    {
        position = actions["Position"].ReadValue<Vector3>();
        rotation = actions["Rotation"].ReadValue<Quaternion>();

        rb.MovePosition(offset.TransformPoint(position));
    }


}```
verbal dome
#

Also make sure that it's not actually the camera jittering

inland cobalt
#

camera was fine before so i dont think thats it

verbal dome
#

I don't really know how well MovePosition works with non-kinematic bodies, I really only use it with kinematic ones.
Even the docs say

Moves the kinematic Rigidbody towards position.

inland cobalt
#

yeah, im just completely stuck with how else to implement it though, if i use .position its gonna phase through objects

verbal dome
#

Calculate velocity from the difference

wintry quarry
inland cobalt
wintry quarry
#

How does it rotate

verbal dome
#
var diff = targetPosition - rb.position;
var vel = Vector3.ClampMagnitude(diff, limit) * speedMult;
rb.velocity = vel;```
This would make it move towards the target position by velocity rather smoothly
inland cobalt
inland cobalt
#

i'll give it a go, but i'm guessing that'll be the case

verbal dome
#

It can be made snappier, but if you want it to be absolutely responsive then I'd probably separate the hand's visuals from the physics. Update the visuals to the target position while the rb is catching up

#

You can also use kinematic hands and MovePosition() but then I think you'd need to implement collision checks with something like SphereCast

inland cobalt
verbal dome
#

You could snap the visual to the physical hand when colliding, but yeah that would probably look bad now that i think about it

inland cobalt
#

Yeah it seems like quite a hacked solution

verbal dome
#

I'm not a VR dev but I'm sure this problem has been solved, have you looked online for resources on VR hand collisions?

inland cobalt
# verbal dome I'm not a VR dev but I'm sure this problem has been solved, have you looked onli...

Yeah, i've found it really annoying to be honest. Unity provides a default XR toolkit with some built in stuff, but a lot of that is very generic with basic movement for example which don't really work for my project. That and all the tutorials on youtube i seem to find are outdated even a couple months after release, and a lot of the scripts used seem to get frequently deprecated and replaced. That's why i figured id just do it myself, and make picking up objects and such by myself, but i keep seeming to get stuck at simple hurdles like this where it feels like the solution should be easy, but it ends up being a lot more convoluted.

#

and the demo scene they provide doesn't have physics collisions on hands, so i cant really see how you would go about doing it now either

inland cobalt
#

not that noticeable

grim leaf
#

Does anyone know if it's possible to make a local multiplayer in unity 3d with split screen with a rigidbody instead od character controller?

#

with the new input system

#

i saw every tutorial using that

slender nymph
#

of course it's possible

grim leaf
slender nymph
#

i mean, moving a rigidbody is going to be different than moving a character controller, but not by much

grim leaf
#

alrrr

#

tysm

dusky sphinx
#

Anyone have any idea how to make an edge detection for 3rd person? tried couple methods like shooting 2 raycasts and try to compare their normals but i don't think that worked well

teal viper
rocky canyon
#

wouldnt u compare distance? like if 1 hit at zero and 1 hit (1 meter down)

teal viper
#

Ah, like ground edge?

rocky canyon
#

thats what im assuming.

dusky sphinx
swift crag
#

so that you can stop the player from walking off the edge?

teal viper
#

Maybe a combo of normals and distance.

#

Or bake a navmesh and sample it when moving.

dusky sphinx
#

nah so the player can jump between them

rocky canyon
#

but it could be..

swift crag
#

can't the player just...jump?

#

or will this be a little animation

#

where the player isn't directly controlling the movement

teal viper
#

Is it like to make them jump automatically?

rocky canyon
#

2d prince of persia style.. lol

#

delayed movements.. /tableflip

teal viper
#

Couldn't you jump even if there's no edge nearby in prince of Persia?

rocky canyon
dusky sphinx
#

Oh nah it's like high building that you can teleport to it's edge

#

tried to use overlapsphere too but didn't work either idk

teal viper
#

If there are predefined places where you can do that, maybe just place some empty gameObjects that you can use as points to teleport to.

dusky sphinx
#

well i thought of that, but for long term i'll get kinda lazy xD

#

So making it by script should be easier anyways

rocky canyon
#

You could raycast down from the player to see if heโ€™s on a platform.
You could also raycast down from a point X distance in front of the player and see if it hits the same platform at the same altitude.

If the altitude is more than a certain amount lower (or you hit nothing) then it might be a ledge.

Of course it also might be you are standing at the base of a mountain, and when you raycast from within the mountain you wonโ€™t find the mountain.

Therefore you might want to also raycast forward to see if you are hitting the base of a cliff that towers upwards in front of you.

Writing computer code to figure out your environment can be tricky, but it certainly is possible if you break it down into logical raycasts as you โ€œFeel outโ€ your world around the character.
https://discussions.unity.com/t/2d-platformer-need-advice-on-how-to-detect-if-player-near-edge-of-platform/839792

teal viper
#

You could still make it by script. An editor script.

Honestly, I think we're missing some context here.

steep rose
#

If all you want is to find if your player is near an edge and want it dynamically, just get the all of the vertices on the object you are currently standing on and calculate the edge normals for all of the vertices, then just find the closest edge that is near the player. Unless I am missing something that should work and as an added benefit it does not rely on the direction the player is currently facing.

#

Of course you may need an offset to back your character up a bit so you don't fall off of the edge

dusky sphinx
#

Ok sorry for the missing context, it's about teleporting to the edge of a building from down or far from it, i used raycast to try and get the edge with it but didn't quite get it that's it

teal viper
tender breach
#

Would it be possible to make a compilation game similar to Megaman Legacy Collection in unity?

dusky sphinx
# teal viper Well, maybe share the code that you have now.
    private void Update()
    {
        Vector3 onerayOffset = mainCamera.transform.position * camHeightOffset;
        Ray ray = new Ray(onerayOffset, mainCamera.transform.forward);
        if (Physics.Raycast(ray, out firstHit, raycastDistance, buildingLayer))
        {
            Vector3 secondRayStart = firstHit.point * rayOffset;
            Ray secondRay = new Ray(secondRayStart, mainCamera.transform.forward);
            if (Physics.Raycast(secondRay, out secondHit, raycastDistance, buildingLayer))
            {

                Vector3 firstNormal = firstHit.normal;
                Vector3 secondNormal = secondHit.normal;
                float normalDot = Vector3.Dot(firstNormal, secondNormal);

                if (normalDot < normalDifference)
                {
                    detectedPoint = secondHit.point + Vector3.up * camHeightOffset;
                }
            }
        }
    }
dusky sphinx
frosty hound
tender breach
#

I also don't know how to do button mapping for the roms.

teal viper
#

You'll need to calculate the offset from the original ray direction and the hit normal

#

Or, maybe no need for a hit normal.

steep rose
# dusky sphinx yup

ah the if that is the case then just do this #๐Ÿ’ปโ”ƒcode-beginner message but instead of the object you are currently standing on, shoot a raycast from camera to the camera's forward direction then use that object for the calculations and find the closest edge to the hit.point of the raycast. It'll look something like this

Blue is the distance between normal's
Orange is the normal's
Magenta is the closest distance

That's how I would probably do this

tender breach
slender nymph
tender breach
slender nymph
#

so you want to use existing games? because you won't be doing emulation in unity

frosty hound
#

You want to make your own games? Or existing?

tender breach
slender nymph
#

repeating the same useless phrase isn't really all that informative

tender breach
# slender nymph repeating the same useless phrase isn't really all that informative

Gonna take you for a ride back to the arcades with MARVEL vs. CAPCOM Fighting Collection: Arcade Classics! 7 legendary games, all in one Super Heroic collection, available NOW on Nintendo Switch, PlayStation 4 and Steam! Xbox One version is also coming in 2025.

  • X-MEN CHILDREN OF THE ATOM
  • MARVEL SUPER HEROES
  • X-MEN VS. STREET FIGHTER
  • ...
โ–ถ Play video
steep rose
slender nymph
teal viper
tender breach
teal viper
#

If you just want to include several games that you developed in unity into one application, that's certainly possible.

slender nymph
slender nymph
#

are they your games

teal viper
#

Do you have the rights to publish these games and are they built for the platform you want to run them on? Or are these actually rom files as you mentioned earlier?

tender breach
slender nymph
#

lol good luck with that

tender breach
teal viper
#

In technical context, you can certainly do it.

teal viper
slender nymph
teal viper
#

Unless you port/develop an emulator that runs in unity.

tender breach
teal viper
teal viper
#

Then yes. You'll need to remake or port them.

tender breach
teal viper
teal viper
# tender breach How do I port them?

You'll need to have access to the source code/the original project and build it for the desired platform(additional project/code modifications might be required). If you want to specifically use unity, you'll probably need to rewrite the project in C# and recreate the assets/levels in unity as well.

tender breach
teal viper
#

And rewrite the code in C#.

dusky sphinx
teal viper
steep rose
#

I used a slightly tweaked method to make AI pathfind to a hiding spot dynamically and the performance seemed fine (keep in mind it was in 2D but I would guess it would be roughly the same in 3D)

teal viper
#

Disregarding performance. Just effort wise

stable narwhal
#

Is this an ok way to change sorting layer of my 2d sword when switching to the left or right?

    private void MouseFollowWithOffset() {
        Vector3 mousePos = Input.mousePosition;
        Vector3 playerScreenPoint = Camera.main.WorldToScreenPoint(playerCore.transform.position);

        float angle = Mathf.Atan2(mousePos.y, mousePos.x) * Mathf.Rad2Deg;

        if (mousePos.x < playerScreenPoint.x){
            activeWeapon.transform.rotation = Quaternion.Euler(0, -180, angle);
            sprite.sortingOrder = 4;
        } else {
            activeWeapon.transform.rotation = Quaternion.Euler(0, 0, angle);
            sprite.sortingOrder = 3;
        }
    }
void thicket
#

I mean does it work for you?

#

Other than it being a magic number there

ornate aurora
#

What alternatives are there to tilemaps? SetTilesBlock is just not fast enough for me. My use case doesn't require colliders or that sort of stuff, only a grid and ways to click and change tiles (in runtime). I've seen an asset to make shader based tilemaps that span thousands of tiles with no performance drop but I can't afford that. My chunk system is not enough to reduce the amount of tile changes. I've also heard about coroutines. My use case has a single plain layer so I'm not sure how would I do that. Any help is appreciated.

eager spindle
#

I only render the tiles within the camera view

ornate aurora
#

Wait what is that? Does it have anything to do with tiles?

eager spindle
#

one quad = one tile

ornate aurora
#

Oh so I don't display anything from the tilemap and use quads instead

eager spindle
#

Yep

ornate aurora
#

Is zooming out too much an issue for that?

oblique chasm
#

I'm having a rough time trying to understand pulling a variable from another gameobject.
Essentially, I have a "weapon controller" which holds on to the attributes of a weapon and an object that follows my mouse and instantiates a bullet on click. What I'm trying to do is give that bullet a damage value when it instantiates.
Thoughts I've tried

  • Instantiate as a child and get parent damage value. (Not instantiating as a child, instantiates at the bottom of the whole scenes hierarchy. Can't seem to figure out getting it to instantiate as a child. Is this because of the "parent transform" situation? Transform itself being part of parenting is incredibly foreignt to me, I read the doc a few times and still don't feel like I understand whats going on there.)
  • Call to the weapon controller object and get the damage value. Can't seem to get the instantiated bullet to find the weapon controller on spawn. Gotta be missing something here.
  • I also read that you can't pass a method when you instantiate?
    I'm suuuuper new and coming from godot, so I'm still in the process of learning. I know I want to have a lot of these items separate so they can be modular in the end. If someone can point me in the direction of what I need to be looking at, I'll gladly dig through the documentation to try and help understand.
slender nymph
oblique chasm
#

I must be missing something. Going to do more digging but I'm getting the error "type' does not contain a definition for 'name' and no accessible extension method 'name' accepting a first argument of type 'type' could be found (are you missing a using directive or an assembly reference?)." error when writing out the code on that site. Compiler error site says it occurs when you try to call a mehtod or access a class member that doesn't exist. Which I'm assuming is because the bullet doesn't exist yet?

#

Thank you though! Nothing a few videos won't teach me XD

slender nymph
#

Which I'm assuming is because the bullet doesn't exist yet?
no, it means you are trying to use a property that does not exist in the code.
also share your actual error instead of an approximation

untold shore
#

Alright, having some issues with a part of my code. Currently, I'm trying to delete all the children of an object, but whenever I call for it to delete, it won't "delete" them? (It's weird. It doesn't show the children under the object, but it still counts them in my code.) Any ideas of how to fix this?

  public void ResetPlayerHand()
    {
      for (int i = hand.transform.childCount - 1; i > 0; i--)
      {
        Destroy(hand.transform.GetChild(i).gameObject);
      }
      handManager.cardsInHand.Clear();
      Debug.Log("Cleared cardsInHandPlayer");
      hand.GetComponent<CardValuesScript>().handValue = 0;
      
      Debug.Log("Number of children in handtransform " + hand.transform.childCount);
    }
}```
slender nymph
#

Destroy queues the objects up for destruction at the end of the frame, they aren't destroyed immediately

oblique chasm
#

"Actual error"
CS1061 'GameObject' does not contain a definition for 'Initialize' and no accessible extension method 'Initialize' accepting a first argument of type 'GameObject' could be found (are you missing a using directive or an assembly reference?)

This error is given when I hover over the "Initialize" section of my code (and in the error list)

#

I can grab the code, but it's from 2 different scripts

slender nymph
#

you need to use the actual type of component you care about for your prefab variable instead of just GameObject

#

or you need to call GetComponent on the gameobject after it has been instantiated

oblique chasm
#

okay, maybe I should post the code....
var instance = Instantiate(bullet, bulletTransform.position, Quaternion.identity); instance.Initialize(damage);

slender nymph
#

yes now re-read both of my messages because they are two options for fixing your issue

hallow bough
#

Does anyone have an idea why changing scenes doesn't work in unity 6000.0.32f1 compared to code in unity 2022.3.50f1? I just switched my project over from the latter, and the script is broken. the code is public void start() { ClosePhidgets(); SceneManager.LoadScene("Scene1"); SceneManager.SetActiveScene(SceneManager.GetSceneByName("Scene1")); }

slender nymph
#

define "doesn't work"

hallow bough
#

i get a long error

#

and the scene does not change

slender nymph
#

well naturally an error would prevent the code from running, so maybe share the error

hallow bough
#

NullReferenceException: Object reference not set to an instance of an object
ButtonScript.ClosePhidgets () (at Assets/Scripts/ButtonScript.cs:64)
ButtonScript.start () (at Assets/Scripts/ButtonScript.cs:20)
UnityEngine.Events.InvokableCall.Invoke () (at <44f3679c53d1477a9c6e72f269e3a3a9>:0)
UnityEngine.Events.UnityEvent.Invoke () (at <44f3679c53d1477a9c6e72f269e3a3a9>:0)
UnityEngine.UI.Button.Press () (at ./Library/PackageCache/com.unity.ugui/Runtime/UGUI/UI/Core/Button.cs:70)
UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at ./Library/PackageCache/com.unity.ugui/Runtime/UGUI/UI/Core/Button.cs:114)
UnityEngine.EventSystems.ExecuteEvents.Execute (UnityEngine.EventSystems.IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at ./Library/PackageCache/com.unity.ugui/Runtime/UGUI/EventSystem/ExecuteEvents.cs:57)
UnityEngine.EventSystems.ExecuteEvents.Execute[T] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.ExecuteEvents+EventFunction`1[T1] functor) (at ./Library/PackageCache/com.unity.ugui/Runtime/UGUI/EventSystem/ExecuteEvents.cs:272)
UnityEngine.EventSystems.EventSystem:Update() (at ./Library/PackageCache/com.unity.ugui/Runtime/UGUI/EventSystem/EventSystem.cs:530)

hallow bough
#

can you please explain the error for me? I dont understand it

slender nymph
#

if only there were a convenient link that provided a brief explanation of the error as well as extensive troubleshooting steps for resolving it

hallow bough
#

sorry, the page was mostly empty, so I automatically assumed it was taken down.

oblique chasm
#

Right. GetComponent would cause errors unless it's serialized according to the site you sent.
When I read through the serialization section, the first 5 steps are present in the DI page and I'm not seeing the difference. I may be missing a reference somewhere. It also mentions that cloning a component with instantiate has all attached objects and components with it. In this case, the script which has the Initialize function. Which is set to public as well. Maybe this is where I'm not understanding something?

slender nymph
#

you're trying to call the Initialize method on a GameObject variable when that is not where you've declared that Initialize method. you need to refer to that component to call Initialize

hallow bough
slender nymph
slender nymph
#

so therefore the scene change doesn't happen. you need to resolve the error first, before worrying about the scene change

#

figure out what is null on line 64 of ButtonScript.cs

teal viper
hallow bough
#

Thank you for helping, it is working now

ornate aurora
hallow bough
#

Another question involving scenes (not that related though). I am publishing a game through WebGL, and the scenes are in the wrong order. How can I control the first scene?

slender nymph
hallow bough
#

I did that, yet nothing changes

nimble apex
#

unityAction cannot exist in interface right?

nova ivy
#

hi. i'm having this bug where randomly after falling or moving sideways, my character can't jump.
https://scriptbin.xyz/owepagihis.cpp this is everything jump related I have in my movement script
i've tried debugging (see fixedupdate) and the conditions required to be able to jump are met. still doesn't

Use Scriptbin to share your code with others quickly and easily.

teal viper
teal viper
nova ivy
#

the issue is it's not letting me jump after reaching grounded state, logging while the character is in the air is not what i'm looking for

slender nymph
#

where are you even calling Jump

nova ivy
#

right i always forget to add something

#
{
    horizontal = Input.GetAxisRaw("Horizontal");

    if (Input.GetButtonDown("Jump"))
    {
        Jump();
    }
}```
slender nymph
#

you call Jump once per "Jump" button press, however you only update the grounded state in FixedUpdate so your object may appear grounded visually, but if you press that Jump button between when it appears grounded and when you actually update the grounded state then it just won't jump

nova ivy
#

i am checking the isGrounded parameter, made it public so i could see it reflected

slender nymph
#

also consider logging the relevant values when you get your Jump button input

slender nymph
covert obsidian
#

Hey, I have a click sound object with a click sound but it's in dontdestroy on load and not in this scene. is there any simple and efficient way to play it that's not just finding it and playing it within the script?

-# โœ… Solution I went with: GameObject.Find("ClickSound").GetComponent<AudioSource>().Play();

slender nymph
#

if it doesn't exist in the scene you can't just drag it in, so you'll need some other way to get a reference to it

nova ivy
#

all the conditions are met

#

it's really weird

slender nymph
#

then there is something you've left out that is affecting it

covert obsidian
nova ivy
# teal viper Do what I mentioned.

canJump being disabled when it shouldn't be is the reason I can't jump, I can log it if you insist but it's going to be false when it shouldn't be

slender nymph
#

then you need to find out why it is not being set to the value you expect

teal viper
nova ivy
#

i don't really have an answer for that, canJump relies on three variables, those being logged above

#

the conditions are met

teal viper
slender nymph
nova ivy
#

it has not

#

if I can't jump, then it's false

hallow bough
nova ivy
#

canJump relies on linearVelocityY, isGrounded, and jumpAmountRemaining

slender nymph
nova ivy
#

those are the three variables being debugged in the screenshot above

teal viper
#

Are they being false when you're supposed to jump?

slender nymph
#

why even have this canJump bool anyway, it seems superfluous when you could just check if you have jumps remaining

nova ivy
#

okay hold up i'm getting dizzy

tame oriole
#

just wondering how i can make my camera shoot a raycast and detect wether it hits an object or not

nova ivy
slender nymph
# nova ivy okay hold up i'm getting dizzy
if (isGrounded && rb.linearVelocityY < 0.001f)
{
    jumpAmountRemaining = jumpAmount;
}

else if (jumpAmountRemaining <= 0)
{
    canJump = false;
}

else 
{
    canJump = true;
}

with this information, what has canJump been assigned to this frame?

hallow bough
teal viper
#

Programming basics: only one of the if/else if/else blocks can be executed at the same time.

teal viper
nova ivy
#

right

#

well that was pretty silly wasn't it

slender nymph
#

and now, this is the part where you realize the canJump variable is useless. just check if you have jumps remaining in your Jump method instead

nova ivy
#

gotcha. i see it

#

thank you both very much

hallow bough
teal viper
hallow bough
#

how can I see if the build is failing

slender nymph
#

when you build it look at the console

hallow bough
#

what do you mean by that?

slender nymph
#

i mean, when you build the project for web look at the console in the unity editor. if the build fails it will tell you there

hallow bough
#

It does not

#

so how is it an older version? I go to the opened page, press update, then press play

slender nymph
#

you did build the project again, right?

hallow bough
#

yes

#

and restarted unity

teal viper
#

Are you doing build & run or something else?

hallow bough
#

in this window, I am pressing publish

slender nymph
#

when was the last time you actually built it, because it seems like it was not within (at least) the last 57 minutes