#💻┃code-beginner

1 messages · Page 256 of 1

wintry quarry
#

so there's a good possibility we need some conversion

slender nymph
#

ah yeah good point

hexed fractal
#

the script is within the player

#

so they arent the same

#

lol

#

cant i just use

#

camera.main

#

than have a variable for that

wintry quarry
#

sure but it will be less efficient

#

don't get distracted by other issues lol

hexed fractal
#

i made it Vector3

#

and it moves

#

more weirdly

#

lol

worthy merlin
#

Yeahhh still nothing. I got all the extensions installed to my VSC so idk why its acting like it doesn't exist

hexed fractal
#

btw a guy thats making a huge planet vr game

#

gave me that

#

way

#

to get input

slender nymph
# worthy merlin Yeahhh still nothing. I got all the extensions installed to my VSC so idk why it...

https://docs.unity3d.com/ScriptReference/Random.html

Name resolution ambiguity
Because the classes share the name Random, it can be easy to get a CS0104 "ambiguous reference" compiler error if the System and UnityEngine namespaces are both brought in via using. To disambiguate, either use an alias using Random = UnityEngine.Random;, fully-qualify the typename e.g. UnityEngine.Random.InitState(123);, or eliminate the using System and fully-qualify or alias types from that namespace instead.

polar acorn
#

You have to pick one

slender nymph
hexed fractal
#

im confused the hell u mean

slender nymph
#

do what praetor told you

hexed fractal
#

where

hexed fractal
polar acorn
#

Show the updated code

hexed fractal
#

so where do i "use AddRelativeForce"

#

theres many places u are talking about

slender nymph
#

just do what praetor said.

hexed fractal
#

WHAT ELSE

slender nymph
#

then what is the fucking problem now?

#

does it not work?

hexed fractal
#

you are literally telling me that i can remove multiplications and MAGICALLY use something else

#

so i DONT need to do that?

slender nymph
#

since you clearly don't understand it, then don't fucking do it

hexed fractal
polar acorn
slender nymph
#

you don't need to do anything.

#

it's like you didn't even read all of the context

hexed fractal
static bay
#

What's going on in here?

summer stump
polar acorn
final kestrel
#

Hey all! I have this first person game and I am trying to do the door mechanic. What method or ways should I look into to be able to interact with the door only when I'm looking at it?

polar acorn
hexed fractal
#

I thought you were talking to another person

slender nymph
hexed fractal
summer stump
hexed fractal
polar acorn
hexed fractal
#

thats literally all it told me

summer stump
obtuse axle
#

Hello, I have a question about camera movement, is there a general way to avoid moving the whole body towards where the camera is looking at?

hexed fractal
#

it was useless to look at it

#

because i already seen it

obtuse axle
#

I have a character that faceplants on the ground when i look at the ground

hexed fractal
#

what conversion

slender nymph
polar acorn
hexed fractal
#

how many times i read that i dont see anything saying i shouldnt do that

obtuse axle
#

uh it's more like the character moves along with the camera

hexed fractal
#

😭

obtuse axle
#

and i want it to not move when im looking up or down, but it can rotate its body if i move left and right with the cam

polar acorn
obtuse axle
#

or maybe its not related to code but to cam hierarchy idk

hexed fractal
#

now i gotta rotate the player smoothly towards the direction im moving

polar acorn
hexed fractal
#

i dont see any difference to transform.forward and Vector3 forward

#

to the movement

#

i guess its just "correct"

polar acorn
#

if the object rotates at all, they become different values

hexed fractal
#

when i walked in a diagonal with transform.forward it was jittery. the player

polar acorn
#

In this case, you don't want the rotation of this object to affect your movement, just the rotation of the camera, so you'd use Vector3.forward and then transform it in the camera's direction

wintry quarry
hexed fractal
#

Vector3.forward made it smooth and move straight

wintry quarry
#

Also note that cam.TransformDirection(Vector3.forward) is the same as cam.forward

polar acorn
hexed fractal
#

Y i p p e e

tall delta
# hexed fractal btw a guy thats making a huge planet vr game

if it makes you feel better I don't really understand why people seems to be so upset with you...
anyways, reading this makes a lot of sense. there isn't anything inherently more correct about using transform.forward vs Vector3.forward but they don't work the same, and that's important to be aware of. for a VR game transform might make more sense honestly, but for a 'normal' third person game, Vector3 is more inline with 'standard' movement.

hexed fractal
#

Im assuming SmoothDamp for the player rotating to its moving direction?

#

lol

visual hedge
#

I give up... I tried fixing and it still adds to that list.
Logic is next:
My basic attack has

    [SerializeField]
    protected List<StatusEffectList> applyStatusEffects = new();
    public List<StatusEffectList> ApplyStatusEffects { get => applyStatusEffects; protected set => applyStatusEffects = value; }

Basic attack itself does not apply any, but when we have certain passive skills, they work only if the hero is using basic attack.
So for that I take that list from the struct, and add needed status effect in there. It was supposed to add status effect to some instance, and not to the source. This is how it appears there.
And now I have no idea how to prevent it modifying the source.

slender nymph
visual hedge
#

yeah, that's what gets that trouble. How do I work around that?

slender nymph
#

create a new list

#

and if that list contains reference types then you'd want to create new instances of those too

polar acorn
visual hedge
#

dammit... will try, while I was trying to fix that issue I guess I broke good working code now 😄

hexed fractal
#

After i actually get good at programming

#

in c#

#

id want to make classes for enemies i guess

uncut light
#

ok thank you

crisp moon
#

I have some questions.
what are some must have free resources or plugins to use with unity that could help?
do i start with 2d or 3d which is more for beginners?
How do i get an idea if im struggle with ideas or overthinking ideas?

that is it for now, i know there silly but im debating if gamedev is even for me or not.

visual hedge
# slender nymph again, List is a reference type. when you make a copy of a struct that has a ref...
                var PassiveSkills = GetComponent<Abilities>().PassiveSkills;
                List<StatusEffectList> NewList = new (actionSettings.applyStatusEffects);
                for (int i = 0; i < PassiveSkills.Count; i++)
                {
                    if (PassiveSkills[i].trigger == Trigger.DEAL_MELEE_DAMAGE)
                    {
                       NewList = PassiveSkills[i].ApplyEffect(NewList);
                    }
                }

and ApplyEffect(NewList); =

    public virtual List<StatusEffectList> ApplyEffect(List<StatusEffectList> effects)
    {
        List<StatusEffectList> NewEffects = new(effects);
        if (ApplyStatusEffects.Count > 0)
        {
            foreach (StatusEffectList status in ApplyStatusEffects)
            {
                NewEffects.Add(status);
            }
        }
        Debug.Log("ActionSettings updated with new information");
        return NewEffects;
    }

dammn... going to test that now...

#

LESSSSGGGOOO! that works, thank you!

shell matrix
#

Hello guys. I'm having a problem with drawing a line in Unity's OnDrawGizmos() function. The line, intended for ground checking from the player's position down, is misaligned and appears next to the player instead of through it. Any advice on troubleshooting and resolving this would be helpful, thanks a lot!

spark otter
#

Any recommendation on how to "split" big character controller to multiple sub-system scripts?

I want to know what is the correct/popular way to do this, thanks in advance to all the helpers! 🙂

summer stump
summer stump
#

Do you have animation included? Things like that?

wintry quarry
spark otter
summer stump
#

Enemy AI would probably have a brain

#

That controls various components

spark otter
summer stump
spark otter
#

sorry for the basic question, new to unity lol

summer stump
#

It's all good!

ivory bobcat
spark ravine
#

Woudl smth. like this work?

private IEnumerator ResetBool(bool boolToReset, float cd)
{
    yield return new WaitForSeconds(cd);
    boolToReset = true;
}

I am trying to make a function that can reset any bool that is passed in

queen adder
#
[SerializeField] private GameObject pawn;

void Start()
{
    StartCoroutine(SpawnPawnRepeatedly());
}

IEnumerator SpawnPawnRepeatedly()
{
    // Loop indefinitely
    while (true)
    {
        // Wait for 3 seconds
        yield return new WaitForSeconds(3);

        // Instantiate the pawn at the same position as the current GameObject
        Instantiate(pawn, transform.position, Quaternion.identity);
    }
}

Why the pawn spawns in the center instead of where my empty object is?
the script is attached to the empty game object
there is an animation on the pawn but only changes rotation of it

ivory bobcat
spark ravine
brave compass
#

👆, but you can't use it with an iterator method (yield).

ivory bobcat
polar acorn
#

Yeah, that's what I was considering. I've never used ref with a coroutine

#

wasn't sure if it would work and it looks like it can't

visual hedge
spark ravine
#

yep ok

#

gonna make diffrent functions then I guess

slender nymph
#

alternatively you could make your coroutine accept an Action parameter then just invoke that action after the delay

#

that would allow you to use it for more than just resetting bools

#

and you would just pass in a delegate that changes the value of the bool whenever you call it

quick summit
#

Hi I am trying to make a 2d game where i can launch stuff and the further you go the more money you get and the player is a water melon. does anyone know what to do?

slender nymph
#

don't crosspost. but what specifically are you having trouble with?

#

if the answer is "all of it" then you should start with some beginner courses like the ones on the unity !learn site

eternal falconBOT
#

:teacher: Unity Learn ↗

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

polar acorn
quick summit
#

yeah

#

and it like breaks

#

and you gotta buy armor

quick summit
night mural
#

i would eat a watermelon

teal viper
shell matrix
#

public Animator amim;
public Rigidbody2D rb;
public float speed = 9;
public float jumpForce;

private float xInput;
private float yInput;
private int facingDir;
private bool facingRight;
private bool isGrounded;

[Header("Collison info")]


[SerializeField] private float groundCheckDistance;
[SerializeField] private LayerMask ground;

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

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

    xInput = Input.GetAxisRaw("Horizontal");
    yInput = Input.GetAxisRaw("Vertical");
    Move();

    if (Input.GetKeyDown(KeyCode.Space))
    {
        if (VerifyCollision())
        {
            Jump();
        }

    }

    AnimatorControllers();
    AutomaticFlip();
    //CollisionCheck();

}

public void Move()
{

    rb.velocity = new Vector2(xInput * speed, rb.velocity.y);
}


public void Jump()
{
    rb.velocity = new Vector2(rb.velocity.x, yInput * jumpForce);
}



public void AnimatorControllers()
{
    bool move = rb.velocity.x != 0;

    amim.SetBool("move", move);
}
public void Flip()
{
    facingDir = facingDir * -1;
    facingRight = !facingRight;
    transform.Rotate(0, 180, 0);
}
public void AutomaticFlip()
{
    if (rb.velocity.x > 0 && facingRight)
    {
        Flip();
    }
    else if (rb.velocity.x < 0 && !facingRight)
    {
        Flip();
    }
}
#

private void OnDrawGizmos()
{
Gizmos.DrawLine(transform.position, new Vector3(transform.position.x, transform.position.y - groundCheckDistance));
}

public bool CollisionCheck()
{
  
    isGrounded = Physics.Raycast(transform.position, Vector2.down, groundCheckDistance, ground);

    return isGrounded;
}

public bool VerifyCollision()
{
    if (CollisionCheck())
    {
        return true;
    }
    else
    {
        return false;
    }
}

}

eternal falconBOT
earnest basalt
polar acorn
earnest basalt
#

i really dont

slender nymph
#

show the Player class

austere hedge
#

press0, press1, and press2 are ints. I'm looking for a more optimized way to do this, since this would require 10 if's for every digit pressed:

        if (press0.IsPressed())
        {
            NumPadController.Attack(0);
        }
        else if (press1.IsPressed())
        {
            NumPadController.Attack(1);
        }
        else if (press2.IsPressed())
        {
            NumPadController.Attack(2);
        }

I'm assuming I need to do a for loop, but I haven't figured out how to get the proper syntax. How to I increment the number on the int's name and the number in the NumPadController.Attack() input parameter?

wintry quarry
earnest basalt
wintry quarry
#

so it's unclear what you mean by them being ints

slender nymph
polar acorn
# earnest basalt

The very first thing you do is create a new Athletics object which completely overwrites anything you had there before

#

So yes, you do have code setting it to 0

earnest basalt
#

i see !

austere hedge
wintry quarry
austere hedge
shell matrix
#

Hello guys. I'm having a problem with drawing a line in Unity's OnDrawGizmos() function. The line, intended for ground checking from the player's position down, is misaligned and appears next to the player instead of through it. Any advice on troubleshooting and resolving this would be helpful, thanks a lot! https://paste.ofcode.org/XkpWZFPZCec3yfhi9mRqNV

polar acorn
trail chasm
#

Hello i have an object transform rotation (0,90,-90) in my code i need to extract it in this form so i did transform.rotation.euleurangle but i return me (0, 90 ,270) i cant find a function who works properly help

trail chasm
#

yea

slender nymph
#

what is the actual purpose of getting the rotation as signed angles

polar acorn
# trail chasm yea

So, whatever you're doing shouldn't care what form the rotation is in, those are the exact same rotation so it should work

trail chasm
#

thanks next question im working on UV mapping an object in unity to access it in game like im flattening a cube when i click on a face of his patron it access the cube is there any way to do it easly or i need to sort every face manually?

visual hedge
austere hedge
#
public InputAction[] press = new InputAction[9];

    // Start is called before the first frame update
    void Start()
    {
        for (int i = 0; i < press.Length; i++)
        {
            press[i].Enable();
            Debug.Log(press[i] + "has been enabled.");
        }
    }

I'm not sure press 0-9 is being enabled since the log is showing press[i] as blank in the Debug.Log section. I've also tried press[i].ToString().

wintry quarry
#

based on this code it's just going to give you blank serialized input actions that you'd have to set up in the inspector

#

especially since you made it public it's being serialized

polar acorn
#

make sure the object is selected so it also draws the transform gizmo

quick summit
#

unity isn't working fro me

thorn holly
austere hedge
wintry quarry
quick summit
#

it says something about unity version control

wintry quarry
austere hedge
wintry quarry
#

yeah definitely use an array instead of this

polar acorn
slender nymph
polar acorn
summer stump
quick summit
#

I can't create a projekt

summer stump
#

Deselect the cloud option or select an organization

summer stump
quick summit
#

oh

#

thank you

austere hedge
#

Not sure what the syntax is for adding those InputActions to the array.

I tried these:

public InputAction[] press = new InputAction[press0, press1, press2, ...];
public InputAction[] press = new InputAction[InputAction press0, InputAction press1, InputAction press2, ...];
wintry quarry
#

Just public InputAction[] pressActions; and set them up in the inspector @austere hedge

polar acorn
#

Just declare the array and then define them in the inspector

shell matrix
polar acorn
#

They only appear in the game window if you specifically enable them

#

they're always present in scene view

shell matrix
stoic glen
#

How can I prevent the player from, falling over edges?
Like having an invisible wall

austere hedge
#

As I add or remove elements from the InputAction array, it is changing the name from element to Input Action. Does it matter that it changes?

summer stump
stoic glen
summer stump
polar acorn
austere hedge
#

Thank you PraetorBlue and digiholic, I have the InputAction array working properly. UnityChanCelebrate

winged meadow
#

i can't find the device simulator link to instal it in package manager

worthy merlin
#

I have this code which generates 5k particles as objects into my game, it gets the object viewer very cluttered. Is there a way I can make these and nest them under another object to keep the menu readable?

floral pewter
#

ayo! am i right in assuming ahead-of-time dictionaries are like ahead-of-time lists except they have attached values?
if so, i'm thinking of using a dictionary instead of a list to have a chance value (right column floats/integers) dictate object occurance (left column, with strings/objects)
is that what this sort of thing is used for?

worthy merlin
polar acorn
#

and I've been using Unity for like ten years

#

Is this a plugin or package?

slender nymph
floral pewter
slender nymph
#

no

floral pewter
#

damn

polar acorn
slender nymph
#

Dictionaries are a collection of Key Value pairs. where a key (the first item) is used instead of an index to get the value (the second item)

#

keys are unique in a dictionary and you also cannot have a null key

floral pewter
#

wait so like, where a list is
thing1 = 0
thing2 = 1
thing3 = 2
a dictionary is
thing1 = (what ever number i pick)
thing2 = (what ever number i pick)
thing3 = (what ever number i pick)
?

polar acorn
frosty hound
#

Which, to be clear, isn't your example above digi's. You just made three similarily named variables, which is not a list.

winged meadow
#

i can't find the device simulator link to instal it in package manager

slender nymph
#

this is a code channel

frosty hound
#

It's also still a experimental package (I believe), so you'll probably have to enable experimental packages in your manager.

floral pewter
#

it has dawned on my that i don't know how to start code blocks in discord

polar acorn
#

Sure, you can look up a value by name. Think about an actual dictionary. You look up a word (key) and get a definition (value)

floral pewter
#

ahhhhhhhhhhhhh

#

it has clicked

#

my good sir, thank you very much

pallid verge
#

Is "starts pressing" different than "pressed down"?

slender nymph
#

no, those methods do the same thing. but one is used to query a specific key (Input.GetKeyDown) the other queries a button set up in your input manager settings (Input.GetButtonDown)

#

also for future reference, don't crop the method name out. i had to actually open the docs manually to see what that second one was

pallid verge
#

oh my bad

#

well if they are the same then why are their desciptions different

#

bc when i try to use the first method, i have to press the key multiple times for it to work

#

let me show u the full code

#

one sec

floral pewter
slender nymph
pallid verge
slender nymph
#

lol yup there it is.

pallid verge
slender nymph
#

don't poll input in physics updates. input should be checked in Update

#

there's also a good chance that this could just a be a physics query instead of relying on trigger messages

pallid verge
#

well i want to return true only when the player is colliding with that object AND pressing the button

#

should i make a bool for the collision check and use it in update?

slender nymph
#

you could, or (again) this could just be a physics query like an OverlapBox or whatever. so you check for input, if the input is true then you perform the overlapbox, if that is true then you call the method

pallid verge
#

what is an overlapbox

slender nymph
#

then you won't be relying on trigger messages and can even get rid of the trigger collider

pallid verge
#

is my method valid

polar acorn
# shell matrix this?

Sure but show the transform gizmo, the thing that shows up when you select an object. The arrows that let you move something around

shell matrix
#

a ok work

polar acorn
#

Send a picture of this object with the transform gizmos visible and set to "pivot"

polar acorn
# shell matrix

So it looks like the line is doing exactly what it should be doing

neon ivy
#

is it me or does setting transform.up reset the entire rotation, I'm trying to set transform.up to the inverse of my gravity direction and rotate the player based on the movement direction and camera rotation. each seperately works but the moment I put them together it just dies

shell matrix
#

I made the line so that when it touches the ground it jumps and it doesn't jump

final kestrel
#

Hey. I wrote a script that teleports the player when the conditions are met. The teleportation works just fine, but I also want to reset player's camera position to the destination position which is the other side of the door. I tried to do the thing on the second script but the camera just flickers till I move my mouse.
https://hatebin.com/slucqzpmgk, https://hatebin.com/sbdquuyqsl.

polar acorn
final kestrel
#

destination is just a simple empty with a trigger box collider.

shell matrix
#

just run or stay but doesn t jumb and before to do the line

polar acorn
#

Show the code

shell matrix
polar acorn
#

Just call CollisionCheck()

#

All this function does is call CollisionCheck. You should just do that

#

Second, what is ground and what layer is your actual ground object on

#

Also groundCheckDistance

neon ivy
shell matrix
shell matrix
winged meadow
#

device simulator doesn't work cause of this
Compiler error CS0121

polar acorn
#

This isn't even complicated

#

I just want to know what those are set to

wintry quarry
winged meadow
wintry quarry
#

To download what

#

open your package manager

winged meadow
#

device simulator

wintry quarry
#

It's a package, you manage it from the package manager

winged meadow
#

where

long matrix
#

float targetVelocityX = moveX * moveSpeed;
rb.AddForce(Vector2.right * targetVelocityX * acceleration, ForceMode2D.Force);
// Limit velocity
rb.velocity = new Vector2(
Mathf.Clamp(rb.velocity.x, -maxSpeed, maxSpeed),
rb.velocity.y
);
// Decelerate if no input
if (moveX == 0f)
{
float decelerationAmount = deceleration * Time.fixedDeltaTime;
rb.velocity = new Vector2(
Mathf.MoveTowards(rb.velocity.x, 0f, decelerationAmount),
rb.velocity.y
);
} guys is it a good way to move 2d character horizontaly? how can i make it smoother

winged meadow
#

i need the link

wintry quarry
#

The link to what?

winged meadow
#

.git

#

device simulator dowload

wintry quarry
#

You download it from the package manager

#

because it's a package

winged meadow
#

where in the package manager

shell matrix
polar acorn
#

Now, what layer is the ground on

carmine turret
#

Im currently refactoring my code to not be a complete mess, Im trying to understand enumerator and how its used as I felt this would be a better solution than having a million bools for each state since none of them can be true at the same time.

#

How do I check if the enumerator is currently set to a specfiic one?

#

ie


    public enum movementState{
        Grappling,
        Hookshoot,
        Grounded,
        Airborne
    }
#

The obvious thought if(movementState == "Grappling") doesnt work so I clearly dont understnad enums

polar acorn
carmine turret
#

(Ill probably use a switch instead of if statements though)

#

Oh, do I need to have a second movement state variable to store it?

polar acorn
#

Do you have a first movementState variable?

carmine turret
#

the enumerator

polar acorn
#

That's the type

#

do you have a variable of that type

carmine turret
#

no

#

I thought an enumerator was simply a type of variable 😄

polar acorn
#

Then what are you trying to check the value of

winged meadow
#

where is device simulator

polar acorn
carmine turret
#

you need to change packages to all and then search for it

polar acorn
#

It's a variable that can only hold those specific values

carmine turret
polar acorn
carmine turret
#

like how bool holds true or false

#

gotcha

#

thank you

shell matrix
polar acorn
polar acorn
#

the one you're trying to check if you hit

#

show it

summer stump
#

Look there for the ground object

shell matrix
#

well i wanna hit the Border

polar acorn
#

Actually, now that I look at the code a bit closer, is the issue even that you're not getting the raycast to connect? Have you tried logging isGrounded after your raycast?

long matrix
#
            {
                Debug.Log(rb.velocity.magnitude);

                // Gradually reduce velocity to zero
                float decelerationAmount = deceleration * Time.fixedDeltaTime;
                rb.velocity = new Vector2(Mathf.MoveTowards(rb.velocity.x, 0f, decelerationAmount),rb.velocity.y);
            }``` guys i think something is not right in my decelration skript the magnitude isnt go down to 0 it stay on like '1.322223E-08'
languid spire
hexed fractal
#

Why do people barely use c# syntax highlighting

#

in discord

long matrix
#

Steven wdym?

languid spire
long matrix
#

whats wrong i check if he stop move i want deaceleration that it wont immediatly stop

hexed fractal
#

just do if its >= 0

long matrix
#

moveX is the input.getaxisraw("horizontal")

hexed fractal
#

skill

languid spire
#

floats don't work like that, you can never guarantee an EXACT number

polar acorn
short hazel
#

1.322e-08 is very close to zero, but not zero. Your condition will fail

hexed fractal
long matrix
#

but >= 0 if its >0 he is moving

hexed fractal
long matrix
#

oh

hexed fractal
#

geez

long matrix
#

you sure its the problem cuz the debug.log() works

hexed fractal
#

== is equality. expecting an exact value equal

long matrix
#

float targetVelocityX = moveX * moveSpeed;
rb.AddForce(Vector2.right * targetVelocityX * acceleration, ForceMode2D.Force);
// Limit velocity
rb.velocity = new Vector2(Mathf.Clamp(rb.velocity.x, -maxSpeed, maxSpeed),rb.velocity.y);
// Decelerate if no input
if (moveX <= 0f)
{
Debug.Log(rb.velocity.magnitude);

            // Gradually reduce velocity to zero
            float decelerationAmount = deceleration * Time.fixedDeltaTime;
            rb.velocity = new Vector2(Mathf.MoveTowards(rb.velocity.x, 0f, decelerationAmount),rb.velocity.y);
        }
#

didnt fix ti

hexed fractal
#

so just use greater and less thans

long matrix
#

it still stay on wird numbers

eternal falconBOT
short hazel
#

<= 0 won't do anything as their value is still greater than 0. Something like < 0.001f should do the trick.
Or use Mathf.Approximately(num, 0)

hexed fractal
#

o k a y?

polar acorn
long matrix
#

9.998757E-10

hexed fractal
#

lol

long matrix
#

xd

short hazel
#

That is scientific notation

hexed fractal
#

why do you name ur script Player

slender nymph
hexed fractal
#

that doesnt say what the script does

#

💀

slender nymph
#

it's just not equal to 0

long matrix
#

i dont see the deceleration

#

i should have see it?

short hazel
long matrix
#

And if im not moving it always call it btw i should also check if the magnitude isnt 0?

polar acorn
hexed fractal
#

machines have issues with stuff like that

long matrix
#

or like <0.1

#

0.1*

hexed fractal
#

12+1? you mean 13.00000000001?

#

lmao

shell matrix
#

set distance with 2.1 and it s the same

polar acorn
#

log isGrounded, see if it's ever true

long matrix
#

`` if (moveX <= 0f)
{
Debug.Log(rb.velocity.magnitude);

            // Gradually reduce velocity to zero
            float decelerationAmount = deceleration * Time.fixedDeltaTime;
            rb.velocity = new Vector2(Mathf.MoveTowards(rb.velocity.x, 0f, decelerationAmount),rb.velocity.y);
        }`` guys shouldnt it like start from 5 and go down to 0? it just start fro mthe small number
eternal falconBOT
hexed fractal
short hazel
#

0.00001 is not less or equal to zero.

long matrix
#

i didnt 111

polar acorn
long matrix
hexed fractal
long matrix
#
        {
            float targetVelocityX = moveX * moveSpeed;
            rb.AddForce(Vector2.right * targetVelocityX * acceleration, ForceMode2D.Force);
            // Limit velocity
            rb.velocity = new Vector2(Mathf.Clamp(rb.velocity.x, -maxSpeed, maxSpeed),rb.velocity.y);
            // Decelerate if no input
            if (moveX <= 0f)
            {
                Debug.Log(rb.velocity.magnitude);

                // Gradually reduce velocity to zero
                float decelerationAmount = deceleration * Time.fixedDeltaTime;
                rb.velocity = new Vector2(Mathf.MoveTowards(rb.velocity.x, 0f, decelerationAmount),rb.velocity.y);
            }
        }```
#

dont mind first if statement

hexed fractal
#

OH MY GOD

#

@long matrix sir why did you ignore the bot

#

PLEASE use highlighting 😭

short hazel
#

They didn't?

long matrix
#

i did

polar acorn
#

They did format it, but not for C#

long matrix
#
        {
            float targetVelocityX = moveX * moveSpeed;
            rb.AddForce(Vector2.right * targetVelocityX * acceleration, ForceMode2D.Force);
            // Limit velocity
            rb.velocity = new Vector2(Mathf.Clamp(rb.velocity.x, -maxSpeed, maxSpeed),rb.velocity.y);
            // Decelerate if no input
            if (moveX <= 0f)
            {
                Debug.Log(rb.velocity.magnitude);

                // Gradually reduce velocity to zero
                float decelerationAmount = deceleration * Time.fixedDeltaTime;
                rb.velocity = new Vector2(Mathf.MoveTowards(rb.velocity.x, 0f, decelerationAmount),rb.velocity.y);
            }
        }```
summer stump
polar acorn
#

Doesn't matter much

long matrix
polar acorn
#

It's fine without highlighting

hexed fractal
long matrix
#

what?

short hazel
#

Ignore, let's just focus on the issue

summer stump
polar acorn
long matrix
#

its not mobile game

hexed fractal
#

i dont see where u got a mobile game from ngl 😭

summer stump
long matrix
#

So wtf mobile

polar acorn
long matrix
#

You rb.velocity in the movetwoards?

polar acorn
#

back on topic of the question

hexed fractal
short hazel
polar acorn
#

Log the velocity after moveTowards

hexed fractal
polar acorn
#

it's a reasonable thing to ask sometimes

short hazel
#

ESL? wtf

polar acorn
#

English as a Second Language

hexed fractal
#

non native english speakers

summer stump
#

To ask, not to declare in a mocking way

long matrix
#

float decelerationAmount = deceleration * Time.fixedDeltaTime;
Vector2 newVelocity = new Vector2(Mathf.MoveTowards(rb.velocity.x, 0f, decelerationAmount),rb.velocity.y);
rb.velocity = newVelocity; like this?

polar acorn
hexed fractal
polar acorn
#

See if it's changing

long matrix
#

Oh

short hazel
hexed fractal
#

nor that thats harsh

#

¯_(ツ)_/¯

polar acorn
#

Drop this or go in a thread there's an actual issue to resolve

summer stump
floral pewter
#

mate

long matrix
#

It still on wird numbers but it calls it every frame but i dont see like 5 goes down to 0 or this wired numbers

hexed fractal
long matrix
#

float decelerationAmount = deceleration * Time.fixedDeltaTime;
rb.velocity = new Vector2(Mathf.MoveTowards(rb.velocity.x, 0f, decelerationAmount),rb.velocity.y);
Debug.Log(rb.velocity.magnitude);

polar acorn
long matrix
#

the rb.velocity.x?

polar acorn
long matrix
#

Debug.Log(rb.velocity.x); its always 0 ill try wthout .x

#

Digiholic

#

it was like -6.3 went to -5.8 -5.3 -5.1 and than straight to 0

#

5 frames

polar acorn
# shell matrix

Okay, and presuming it doesn't change ever as you move around? Just for the sake of completeness, try this. I've modified your raycast to no longer check layers and to store the reference to the object so we can print out what it's hitting. It might be hitting something before it reaches the ground. What does this log print?

public bool CollisionCheck()
{    
  isGrounded = Physics.Raycast(transform.position, Vector2.down, out RaycastHit hit, groundCheckDistance);
  Debug.Log($"Raycasting from {transform.position}, distance of {groundCheckDistance}, hit object {hit.collider}");
  return isGrounded;
}
polar acorn
eternal falconBOT
long matrix
#

the fixedupdate?

#

void Update()
{
moveX = Input.GetAxisRaw("Horizontal");
if(Input.GetKeyDown(KeyCode.Space) && grounded)
{
jumped = true;
}
if(Input.GetKeyDown(KeyCode.K))
{
Time.timeScale++;
}
if(Input.GetKeyDown(KeyCode.L))
{
Time.timeScale = 1;
}
}
private void FixedUpdate()
{
if(movePlatfrom == null || !movePlatfrom.clouded)
{
float targetVelocityX = moveX * moveSpeed;
rb.AddForce(Vector2.right * targetVelocityX * acceleration, ForceMode2D.Force);
// Limit velocity
rb.velocity = new Vector2(Mathf.Clamp(rb.velocity.x, -maxSpeed, maxSpeed),rb.velocity.y);
// Decelerate if no input
if (moveX <= 0f)
{
// Gradually reduce velocity to zero
float decelerationAmount = deceleration * Time.fixedDeltaTime;
rb.velocity = new Vector2(Mathf.MoveTowards(rb.velocity.x, 0f, decelerationAmount),rb.velocity.y);
Debug.Log(rb.velocity);
}
}
if (movePlatfrom != null && movePlatfrom.clouded)
{
rb.velocity = new Vector2(moveSpeed * moveX + movePlatfrom.speed, rb.velocity.y);
}
if (jumped)
{
rb.velocity = Vector2.up * jumpSpeed;
jumped = false;
}
if (moveX > 0 && rotated)
{
transform.eulerAngles = new Vector2(0, 0);
rotated = false;
}
if (moveX < 0 && !rotated)
{
transform.eulerAngles = new Vector2(0, 180);
rotated = true;
}
if (moveX != 0)
{
anim.SetBool("IsRunning", true);
}
else
{
anim.SetBool("IsRunning", false);
}
}

polar acorn
#

The entire script

eternal falconBOT
hexed fractal
#

oh my..

long matrix
#

share it other way xd?

hexed fractal
#

on that bot

#

one of those

long matrix
#

like this?

polar acorn
#

Yes. It's not the full script like I asked for but it'll do

hexed fractal
#

lmao

long matrix
#

i just have oncollision enter and awake for refrences

hexed fractal
long matrix
#

ye but it wont matter anything

hexed fractal
#

oh my

#

not saying anything

polar acorn
# long matrix https://gdl.space/numukabexi.cs

Places that it could be jumping to 0:

  • The clamp, depending on what maxSpeed is
  • inside of if (movePlatfrom != null && movePlatfrom.clouded)
  • inside of if (jumped)

Any of those could set the x velocity to 0 before the deceleration takes it there

polar acorn
# shell matrix

Okay, so it does hit something. That's on me I should have had you log hit.collider.name, can you add that?

long matrix
#

if (movePlatfrom != null && movePlatfrom.clouded) it doesnt matter cuz it happen when its not true

#

i talk about first if statement

#

and even when im not jumping

#

Maybe

#

the problem is in the decelration value?

#

its 50

polar acorn
long matrix
#

the second if statement can only be true in other scene

#

and jumped if i click space and i dont

polar acorn
# long matrix its 50

Possible, your fixedDeltaTime should be 0.02 assuming you haven't changed it so it should be decelerating by 1 every physics step

long matrix
#

So what is a good value and i realy have to * fixeddeletetime?

polar acorn
visual hedge
#

how could one convert ?int to int? 🙂

polar acorn
#

So, if your X speed is 50, you'd reach zero in one second. If it's 25, it'd take half a second, and so on

polar acorn
long matrix
#

I removed it to 5 and i see if like i move straight a lot to max speed that is 8 it goes down like -8 -7 -6 -5 good till -4 and from -4 to -0.3 and why its - if i move right

#

move right*

visual hedge
final kestrel
#

--> https://hatebin.com/zuwbjangdy This script is responsible for teleporting the player to the destination point. It works just fine on the position.
-->https://hatebin.com/gqbmlptbri and uh this just calls the function and makes the teleport happen.
What i fail to understand is that when I teleport I want my camera to face the destination rotation. But when I come on the other side of the door my camera flickers till I move my mouse again. Can anyone point me the right direction?

long matrix
#

rb.velocity = new Vector2(Mathf.MoveTowards(rb.velocity.x, 0f, decelerationAmount),rb.velocity.y); maybe i should change to lerp?

polar acorn
#

Pretty sure the issue is something else is overwriting it with 0 and not the actual method of deceleration

long matrix
#

And the rb.velocity is - and im moving right it should be like that?

polar acorn
# shell matrix

Okay so it's not always hitting an object. Hang on let me update the function, I wrote that last one up on mobile and I missed some stuff, clearly

polar acorn
# shell matrix
public bool CollisionCheck()
{    
  isGrounded = Physics.Raycast(transform.position, Vector2.down, out RaycastHit hit, groundCheckDistance);
  Debug.Log($"Raycasting from {transform.position}, distance of {groundCheckDistance}");
  if (isGrounded){
    Debug.Log($"Raycast successful, hit object: {hit.collider.name} on layer {hit.collider.gameObject.layer}");
  }
  return isGrounded;
}
long matrix
#

Digiholic

#

Why does the rigidbody.velocity turns into negative number?

polar acorn
polar acorn
long matrix
#

Is it k that it becomes negative?

polar acorn
#

Probably. Assuming that's the direction you're going

shell matrix
long matrix
#

No if i go right it goes like up + and change to -

#

even if im moving right

polar acorn
# shell matrix nope

Hm, so the ray isn't hitting anything at all, ever. Are you sure all of your objects are at the same Z value? Do they all have 2D colliders?

polar acorn
long matrix
#

No when im moving float targetVelocityX = moveX * moveSpeed;
rb.AddForce(Vector2.right * targetVelocityX * acceleration, ForceMode2D.Force);
// Limit velocity
rb.velocity = new Vector2(Mathf.Clamp(rb.velocity.x, -maxSpeed, maxSpeed),rb.velocity.y); and i move right the rb.velocity start positive and go into negative

#

idk why

#

maybe vector2.right is the problem?

polar acorn
long matrix
#

So why it is - when i move right?

polar acorn
#

Unless your moveSpeed or acceleration is negative, it won't be. Again, leading me to believe something else is moving it

long matrix
#

O shit

#

i just all the time looked at the y

#

velocity

#

Wait i see the x isnt changing

#

float targetVelocityX = moveX * moveSpeed;
rb.AddForce(Vector2.right * targetVelocityX * acceleration, ForceMode2D.Force);
// Limit velocity
rb.velocity = new Vector2(Mathf.Clamp(rb.velocity.x, -maxSpeed, maxSpeed),rb.velocity.y);
Debug.Log("Velocity after clamping: " + rb.velocity);

shell matrix
polar acorn
long matrix
#

Wait so digiholic float targetVelocityX = moveX * moveSpeed;
rb.AddForce(Vector2.right * targetVelocityX * acceleration, ForceMode2D.Force);
// Limit velocity
rb.velocity = new Vector2(Mathf.Clamp(rb.velocity.x, -maxSpeed, maxSpeed),rb.velocity.y);
Debug.Log("Velocity after clamping: " + rb.velocity.x); the rb.velocity.x should be 0 when im moving?

polar acorn
long matrix
#

K ill explain

#

When im logging the x velocity while im moving the velocity in x is 0

#

shouldnt it have a higher value?

polar acorn
shell matrix
long matrix
#

float targetVelocityX = moveX * moveSpeed;
rb.AddForce(Vector2.right * targetVelocityX * acceleration, ForceMode2D.Force);
// Limit velocity
rb.velocity = new Vector2(Mathf.Clamp(rb.velocity.x, -maxSpeed, maxSpeed),rb.velocity.y);
Debug.Log("Velocity after clamping: " + rb.velocity.x);

shell matrix
polar acorn
shell matrix
#

so i delete the square ?

polar acorn
#

I have no idea what this square is

#

but everything involved in the collision needs to have the same z position

shell matrix
#

it s another border

buoyant schooner
#

How do I stop this from happening? I have a base class that has a few child classes on the same object. But the base class public references show on the child's scripts.

polar acorn
long matrix
#

Digiholic maybe the rb.velocity should be 0 and i have to check the magnitude fr idk what to do

polar acorn
#

You could make it protected so it's accessible by the child classes but not settable in the inspector

buoyant schooner
polar acorn
buoyant schooner
#

my base class has this:

protected GameObject mousePointCollider;
#

Then it wont show

#

wait

polar acorn
polar acorn
buoyant schooner
#

I only want the base class to show the variable

long matrix
#

Digiholic i should see the gameobject accelrating and decelerating in my game if it works?

polar acorn
buoyant schooner
#

hmm, idk. I don't want the children to set it. I have a singleton for my base class

#

I want them to reference the base class for that variable

shell matrix
polar acorn
polar acorn
shell matrix
buoyant schooner
polar acorn
buoyant schooner
#

yeah, I think i'm using child classes wrong in this instance

polar acorn
#

I can check a bunch of stuff at once

#

Oh, and do it while the game is running

glossy compass
#

what is the best way to move an object (the player) by dragging them with your mouse in 2D game? would i need to use raycast?

languid spire
glossy compass
languid spire
#

amongst other things, like drag and drop, yes

glossy compass
#

but im not sure what that or IPointer is lol

shell matrix
#

I noticed that now that line no longer appears

glossy compass
languid spire
polar acorn
#

That would probably explain a lot of your problems

shell matrix
#

and ground i p put ground

#

i put

polar acorn
shell matrix
# polar acorn Also

if I set it so that the other objects have z, it still changes as it was before

summer stump
summer stump
#

Wait, maybe I misread what you said. I thought you meant it was changing back

polar acorn
#

Can you fix all that and re-send the screenshot of the object with the Player script on it

long matrix
#

Debug.Log("Current Speed: " + rb.velocity.x);
float targetVelocityX = moveX * moveSpeed;
rb.AddForce(Vector2.right * targetVelocityX * acceleration, ForceMode2D.Force);
rb.velocity = new Vector2(Mathf.Clamp(rb.velocity.x, -maxSpeed, maxSpeed), rb.velocity.y); guys does any1 know why the rb.velocity.x returning 0 when i move no matter where i put the debug.log

polar acorn
#

I just realized something stupid I should have noticed before

#

Are you using Physics.Raycast or Physics2D.Raycast

shell matrix
#

Physics.Raycast

languid spire
#

whoops

polar acorn
#

By the time I actually had the full context I hadn't looked at the code in like an hour and forgot it was Physics.Raycast

long matrix
#

Digiholic now can you help me xd?

polar acorn
long matrix
#

the full code?

eternal falconBOT
long matrix
#

The moving platform and if statements arent matter dont mind them

polar acorn
#

and what is the problem

long matrix
#

when i check the current speed by using rb.velocity.x when im moving its x and i dont see any acceleration on the player

#

Debug.Log("Current Speed: " + rb.velocity.x);
float targetVelocityX = moveX * moveSpeed;
rb.AddForce(Vector2.right * targetVelocityX * acceleration, ForceMode2D.Force);
rb.velocity = new Vector2(Mathf.Clamp(rb.velocity.x, -maxSpeed, maxSpeed), rb.velocity.y);

hexed fractal
#

@polar acorn this guy doesnt listen 💀

#

istg

shell matrix
#

thank you very much, @polar acorn

eternal falconBOT
long matrix
#

for 4 lines why?

polar acorn
hexed fractal
#

if so

#

format ur code

long matrix
#

cs //hey

hexed fractal
#

it literally shows

polar acorn
hexed fractal
#

that you put your code

#

in the middle

#

not on the same line as it

long matrix
#

I expect to have acceleration to make my movement look smoth

#

smooth

#
// hey
polar acorn
#

Just calling AddForce over multiple frames should be causing acceleration

#

As long as the force is constant

long matrix
#

Bro all the day i got called that i need to add acceleration and deacceleration

hexed fractal
long matrix
#

so how to do the movement with addforce i dont understand

hexed fractal
#

i prefered Force over Velocity

polar acorn
#

You're already clamping the velocity so just add some constant force for movement

long matrix
#

i have movespeed

polar acorn
#

A direction times a value

#

that value determines how fast you accelerate

#

bigger number means you reach top speed faster

#

and the clamp keeps you from going over

long matrix
#

ye so direction * movespeed

#

so i dont need another float named acceleration?

polar acorn
#

Probably not

long matrix
#

i mean i want to move the player in a professional way

hexed fractal
long matrix
#

ye like hollow knight for example

hexed fractal
#

i use _rigidBody.AddForce();

long matrix
#

ye same but how to add the force inside?

#

just direction * movespeed?

hexed fractal
#

i use GetAxisRaw

#

inputs

long matrix
#

same

#

ye

hexed fractal
#

multiplied by a movement speed

#

converted to camera direction

#

then thats my force

long matrix
#

But than i remove the * acceleration that is 50 and i need to make speed be * 50 more like instead of 6 300

hexed fractal
#

so the players movement is the force

#

my movement speed is 500

#

kinda normal ish speed

long matrix
#

Wait so you tell me the addforce do the acceleration and the accleration is like make speed being 300 but 6 in inspector?

hexed fractal
#

dont talk about

#

acceleration

#

at all

#

lol

long matrix
#

but i want acceleration

hexed fractal
#

thats

#

what we are doing

#

addforce every frame

#

will speed ur player up every frame

#

by adding that force

#

until you reach a max constant speed

#

thats "acceleration"

#

the movement speed is how fast you want to accelerate and the top speed

#

which you can cap probably

#

so after you get the Vector3 player movement input

#

you put that in as force

#

then choose ur force mode

#

there is an acceleration one..

long matrix
#

And clamp the speed to max speed that it wont go more than that

hexed fractal
#

do you want mass to matter

#

in how fast you move

long matrix
#

But is it rlly different than rb.velocity?

#

i dont want mass

hexed fractal
#

ok then use ForceMode.Acceleration

languid spire
queen adder
#

Hard setting the velocity typically isnt a good idea

long matrix
#

But its 2d

hexed fractal
long matrix
#

!code

eternal falconBOT
queen adder
#

You still dont want to hard set the velocity

long matrix
queen adder
#

In 2D or 3D

long matrix
#

so you telling me this short code is fine for 2d movement in high level like hollow knight?

#

and forcemod2d doesnt have .acceleration

hexed fractal
#

ForceMode.Force just includes mass

#

ForceMode.Acceleration ignores mass

long matrix
#

But im using forcemode2d

hexed fractal
#

c o o l

long matrix
#

K last question

#

i want to check my current velocity like it starts on 5.5 and accelrate to 7 and want to see how fast how can i do that?

hexed fractal
#

just set the mass to 0 then

#

with Force

#

unless u need the mass

#

lol

long matrix
#

Every gameobject in my game has mass of 1 if using rb so doesnt matter

hexed fractal
#

o k

icy grotto
#

!code

eternal falconBOT
rancid tinsel
#

just to double check, doing it this way will mean that rather than editing all instances of the script, it will just be a single instance?

summer stump
rancid tinsel
swift crag
#

iceMachineScript will be whatever has been assigned to the specific instance of this component in the inspector.

#

Assigning it to iceMachineInstance does nothing other than copy that reference into the variable.

rancid tinsel
#

i see

swift crag
#

also, you declared a local variable

#

so you didn't assign to the iceMachineInstance field

#

you've assigned the reference into a new local variable that is then thrown out as the function ends

rancid tinsel
swift crag
carmine turret
#

is !dashUsed the same as dashUsed == false?

#

It is right?

swift crag
carmine turret
#

Thanks

#

just wanna shorten my code haha

swift crag
#

you rarely want to actually compare against a true or false literal

rancid tinsel
#

might be a silly question, but if I am starting a coroutine, does the next bit in the method still go through before the coroutine is finished? I'm assuming thats the case

swift crag
#

You can never block the main thread.

#

StartCoroutine does not "wait" until the coroutine method completes

rancid tinsel
#

im a bit stuck on what to do here

swift crag
#

When you invoke a method that returns IEnumerator, you're actually creating a whole state machine that keeps track of what step of the method you've reached

#

You pass that thing to StartCoroutine. It runs the enumerator until it hits its first yield instruction.

#

Then it stores the enumerator in a list somewhere in MonoBehaviour

#

By default, it resumes the enumerator method once per frame

#

which runs until it hits another yield

swift crag
#

Then StartCoroutine returns and OnCollisionEnter2D continues execution as per usual

#

notably, it sets enemyMovementInstance.moveSpeeed = instanceHolder.moveSpeed;

#

Six seconds later, the coroutine resumes. It runs instanceHolder.moveSpeed = originalMoveSpeed;

#

At that point, the coroutine is over.

rancid tinsel
#

i see

#

that makes sense

swift crag
#

one suggestion: you can just pass EnemyMovement to Slow

rancid tinsel
#

yeah i just asked gpt about it and thats the answer it gave

swift crag
#
StartCoroutine(Slow(enemyMovementInstance));
private IEnumerator Slow(EnemyMovement enemyMovement) {
   // ...
}
#

Storing the enemy movement object in a field means that you can only run a single Slow coroutine without breaking it

rancid tinsel
#

im completely lost when it comes to putting stuff in the ()

#

i dont really understand it

swift crag
#

when you invoke a method, you can pass arguments

buoyant knot
swift crag
#

The arguments you need depend on the parameters the method asks for

rancid tinsel
swift crag
#
public int Add(int a, int b) { return a + b; }
#

this is invoked as

rancid tinsel
#

but for simple issues its a useful tool imo

swift crag
#
int five = Add(2, 3);
swift crag
#

it does nothing because both enemyMovementInstace and instanceHolder reference the same thing

buoyant knot
#

chatGPT can produce a document with the right syntax that you request, on the topic of your request. But it doesn’t actually know anything, and so it cannot actually explain anything.

#

it knows language, not logic

tender stag
#

this adds a force up when a player is in water according how deep he is, so when hes at the top it doesnt add any```cs
if(!isUnderwater)
{
float distance = water.transform.position.y - transform.position.y;
float normalizedDepth = Mathf.Clamp01((distance - minDepth) / (maxDepth - minDepth));

float forceMagnitude = Mathf.Lerp(0f, maxForce, normalizedDepth);
Vector3 force = Vector3.up * forceMagnitude;

rb.AddForce(force, ForceMode.Acceleration);

}and then i have another force acting on the player for horizontal movementcs
rb.AddForce(moveDirection.normalized * swimAcceleration);```

#

can anyone explain why when i jump into the water and not move it works properly

#

and when u see in the second half of the clip im swimming around

#

and the player is bouncing up and down

buoyant knot
#

buoyancy is awkward to implement imo

tender stag
#

moveDirection = orientation.forward * y + orientation.right * x;

#

y and x are raw inputs

swift crag
#

I wonder if whatever you're doing to damp your velocity (you don't oscillate forever in the water in the first half) is getting messed up by movement

#

The second half is what I'd expect with no damping, actually

buoyant knot
#

in general, in fluids you want to:

  1. Damp your usual forces,
  2. Add force when making initial contact with fluid
  3. Apply buoyant force
swift crag
#

bobbing up and down forever

tender stag
#

might be my speed control

#

true

#

nope

buoyant knot
#

the main point I want to make is that order of application and modification of forces with force is very important

tender stag
#

its not

#

i turned it off

#

and it still bounces

buoyant knot
#

one way to get it to stop bobbing is to effectively calculate a center of volume/mass, and compare to the water level

#

and apply force that scales with the delta height

tender stag
#

it works tho

#

only when im not moving

buoyant knot
#

but you want it to stop bobbing

#

meaning the force needs to become weak near the surface

tender stag
#

it does

swift crag
#

It doesn't matter if the force becomes weaker

#

As long as there's no loss of energy, you will bob forever

quartz granite
#

guys i need help for the coding stuff

buoyant knot
#

yeah, some damping factor is probably worth

swift crag
#

I'm guessing you have code that tries to reduce your velocity to zero when you aren't holding down movement keys

swift crag
#

(or that incidentally does that)

tender stag
#

but its not affected when im swimming

#

u can see in the video

#

oh wait

#

it increased

#

in the video

#

when i wasnt moving

quartz granite
#

https://learn.unity.com/tutorial/displaying-score-and-text?uv=2022.3&projectId=5f158f1bedbc2a0020e51f0d#650b5addedbc2a3242890dd4 based on this tutorial for the script for player controller i follwed it step up step and for some reason the ball doesn't move but the rest object moves, so can someone help me with it?

Unity Learn

In this tutorial, you’ll: Revise the PlayerController script to store the value of collected PickUp GameObjects Create and configure UI Text Elements to display: The count value An end of game message

tender stag
#

so how can i damp the force myself?

quartz granite
valid palm
#

hi, does anyone have the same issue as I do? Whenever my character dies it takes two lives instead of one

swift crag
wintry quarry
valid palm
#

I will send it

swift crag
#

Sounds like you should just add drag when you're touching water

tender stag
#

i fixed the drag issue

#

now its always bouncing

#

so just add opposite force?

#

like down

#

to damp it

swift crag
#

I'd just make drag higher in water, all the time

valid palm
tender stag
quartz granite
quartz granite
wintry quarry
#

It's not necessarily the code that's the problem

#

could be something in the editor

#

e.g. attaching a script to the correct object, arranging the hierarhcy properly, or assigning the right thing to a field in the inspector

winter laurel
#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

winter laurel
#

I've been learning off of Game Makers Toolkit's video for making your first game and I finished the video. At the end he gives you a few promts to make for flappy bird and I wanted to make a start game screen. Im wondering how I change between two diffrent scenes and prevent code in one scene happening before I click a button to load the actul game screen?

swift crag
#

Objects in unloaded scenes do not exist at all

#

so until you load the game scene, nothing in it exists or does anything

winter laurel
#

How do I unload or load a game scene though?

swift crag
#

You'll want SceneManager.LoadScene

#

using UnityEngine.SceneManagement; is needed

wintry quarry
#

(look at all the SceneManager functions for how to load/unload scenes)

winter laurel
#

Thanks!

swift crag
#

The default mode is single, which means that the new scene replaces all existing scenes

winter laurel
#

Should I write the script to load and unload scenes outside of my gamestart and gameplay scenes? or should I write it in the gamestart scene?

#

Game start right?

wintry quarry
#

it should definitely be a separate script

winter laurel
#

so outside of both scenes and straight in the hiegharchy with no parents?

swift crag
#

An object can't be outside of a scene.

#

you can use DontDestroyOnLoad to move it into a special scene that never unloads

#

But if you just need to go from menu to game and game to menu, I'd just make a component for each case

#

one that loads the game scene when you click the "start game" button and one that loads the menu scene when you hit the "quit" button

#

I guess you could make one component that has a string field on it

#

to decide where you go

#
public class SceneChanger : MonoBehaviour {
  [SerializeField] string scene;

  public void LoadScene() {
    SceneManager.LoadScene(scene);
  }
}
#

something like that

#

then you could just use a UI button to call LoadScene

winter laurel
#

Rn I have this attached to a button

#

so do I than delete the void start stuff and put that in?

#

and change the names to fit the names of my scenes?

swift crag
#

That would instantly try to load a scene every frame (if the errors were corrected)

winter laurel
#

ohhh

swift crag
winter laurel
#

Would I still need that if I already had a play again button?

#

cause when the birb hits a pipe, it destorys object and that round is over

rancid tinsel
#

would this only change the value on the instance of the script or the script as a whole?

eternal needle
rancid tinsel
#

could you maybe explain it in simpler terms

eternal needle
# rancid tinsel i dont really understand

Oh I just realized you are changing a value on a different script. But to answer simply, if you are changing an int (written as you have above) it will change the int only for that instance of the script. If you have 2 scripts, these ints can both be different values.
If you use the static keyword, the int will be related to the type (class name) like IceScript.enemiesSlowed every instance of a class will see the same value

rancid tinsel
#

ah i see, so as long as its not static, it shouldn't change it for all of them?

eternal needle
#

These ints are completely unrelated no matter what

winter laurel
#

Right now I currently have two scenes that I want to go from one to the other. I have a title screen (Image 1) and a in game screen (Image 2). But right now they are over lapping (Image 3). How do i get the game to start on the first image, then be able to click the Let's play button to get to the second screen? (I have a working play again button for when the bird dies).

feral oar
low robin
#

Help i don't know what is going! i am sopossed to have varibles but for some reason after i added the custom inspector all the varibles went "Goodbye!"

slender nymph
#

Because you have a custom inspector that does not draw those serialized variables

low robin
#

how do i draw the varibles?!

slender nymph
split root
#

Following GMTKs tutorial for beginners and my "pipes" keep spawning off the screen. I've tried lowering/changing the offset from numbers 0-10 and same result. Does anyone know why/how this is happening? I've tried changing the actual position of the "pipe spawner" gameObject as well to see if it would fix but that didn't change anything either

#

(Pipe spawner gameObject)

slender nymph
#

You probably need to look at the pivot point of the object being spawned, it's likely lower than where you expect it to be

#

Either that or you have code on the pipes that changes their Y position

slender nymph
#

Make sure that your tool handle is set to pivot not center

split root
split root
slender nymph
#

Okay so you know it isn't the pivot. Now check your code to see if there is anything that can affect the Y position

#

Oh actually I found it. Read the code you posted before VERY carefully again

split root
slender nymph
#

Yes

split root
#

I need to change transform.position.x to .y

#

Thanks

last basin
#

Hello guys, I have a problem. My hp reset to 3 just when i change my current scene. no mention of "3" in my code. I have no idea where is the problem :/

ivory bobcat
last basin
#

i've searched 3 with the Search feature of VScode so ...

wintry quarry
last basin
#

I define my HP to 5 in my GameManager who is a singleton. When i click on my button to go to my main menu and load my game with a Resume button, it reset my value to 3. When i die and respawn for example the value is 5.

I use Playerprefs to save my data and when i get the value just before use .Save() or GetX() its the correct value, not 3.

wintry quarry
#

anyway you're missing something clearly

ivory bobcat
#

Make sure to save the player pref before changing scenes

wintry quarry
#

maybe it's set to 5 and then immediately you're losing 2hp for some reason

#

lots of possibilities

eternal falconBOT
last basin
#

Thanks guys, i'll investigate more

ivory bobcat
tidal belfry
#

ohh okays

#

thank u

modern spindle
#

i was wondering if anyone knew why whenever i set b_c to the same things as the line colidor one point get set too 0, 0 and the other is where it should be i modified the code slightly to debug so it might not work exactly as i said but please help here is the code

a example

#

!code

eternal falconBOT
modern spindle
#

!code ```cs
IEnumerator MakePlatform(Vector3 point1)
{
LineRenderer line_ren = GetComponent<LineRenderer>();
EdgeCollider2D coll = GetComponent<EdgeCollider2D>();
//PolygonCollider2D coll = GetComponent<PolygonCollider2D>();
line_ren.SetPosition(0, point1);
//coll.points[0] = line_ren.GetPosition(0);
building = true;
yield return new WaitForSeconds(0.5f);
yield return waitForKeyPress(KeyCode.Mouse1);
line_ren.SetPosition(1, new Vector3(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y, 0));
//coll.points[1] = line_ren.GetPosition(1);
//coll.points[2] = line_ren.GetPosition(1);
List<Vector2> list = new List<Vector2>();
list.Add(new Vector2(point1.x, point1.y));
list.Add(new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y));
coll.SetPoints(list);
GameObject bride = Instantiate(bridge, transform.position, Quaternion.identity);
LineRenderer b_l = bride.GetComponent<LineRenderer>();
b_l.SetPosition(0, point1);
b_l.SetPosition(1, new Vector3(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y));
EdgeCollider2D b_c = bride.GetComponent<EdgeCollider2D>();
List<Vector2> b_p = new List<Vector2>();
b_p.Add(new Vector2(0, 0));
b_p.Add(-new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y));
b_c.SetPoints(b_p);
yield return new WaitForSeconds(1);
building = false;
}

eternal falconBOT
modern spindle
#

this is the code

austere hedge
#

I'm trying to spawn an object at a specific position. But I can't figure out what I am supposed to put for the Quaternion. I don't know what the default Quaternion is supposed to be for 2D.

bar.Position is a Vector2, and I doubt Quaternion.identity is right, but I just threw it in there as a placeholder.

GameObject foo = Instantiate(objectToSpawn, bar.Position, Quaternion.identity);

What do I need to put as the third input parameter to get the correct Quaternion for the default 2D view?

#

Or is there a better way to spawn a 2D object at a position?

carmine turret
teal viper
austere hedge
#

Oh, good. That's exactly what I want. Thank you.

teal viper
#

In fact I think it would be true when you're airborne

#

Ah, no, it wouldn't. Still it's not really correct

summer stump
teal viper
#

I guess so. Anyways, || would be more correct here

summer stump
#

You pretty much never want to use | over || in this case though

summer stump
teal viper
radiant frigate
#

bug: the first spawned multishootingenemy works just right but the 2nd one doesnt shoot

#

i think its due to the 2nd one calling the class(or script) on the first one, and therefore doesnt do anything on its own

#

once i kill the first one spawned the 2nd one works just fine

#

i have thought of just creating another class inside the first one script so i have them in the same place and i can make everything private, but idk if having all the code of one enemy in the same script is good for the long term

teal viper
#

That last message feels like you've skipped several paragraphs of context...

radiant frigate
#

okay lemme elaborate on that

#

i have 3 main scripts in the enemy

radiant frigate
#

HpScript | MovementScript | ShootingScript

carmine turret
#

I thought that it makes it easy to read, and makes sure no frame errors happen

#

since everything is then neatly split up into their own functions

radiant frigate
# radiant frigate HpScript | MovementScript | ShootingScript

the movementScript takes information from the shooting script so in case its shooting (a bool) is true, then he has his rb2d.velocity set to 0.
what im guessing that is happening is that the 2nd one instead of taking out information from his own script is taking it from the first or something like that ( which makes no sense to me since i get the script by going through the components of the prefab and making a reference in that way)

potent nymph
#

I have an array of this struct VertexGrid[]

public struct VertexGrid
{
    public Vector3 position;
    public Vector2 gridPos;
    public float height;
}

How would I extract out only position, so I only have an array of Vector3? Vector3[]
I would like to assign the Vector3 array to a new variable

teal viper
# carmine turret Is this so bad?

It's confusing, because you'd think that of it enters into the method it would do some logic and not exit right away. The way I'd do it is take out the state check outside the state methods . But that's kinda of a preference thing. It's not like the way your code works would change.

summer stump
teal viper
carmine turret
#

So not a bad thing, just personal preference ^^

#

altough perhaps its less efficient data structure wise?

potent nymph
radiant frigate
summer stump
teal viper
carmine turret
#

Gotcha

teal viper
carmine turret
#

Im noticing one weird bug

#

My airdash uses Impulse

radiant frigate
carmine turret
#

and if I airdash whilst hugging a wal, it pushes teh player inside the wall (triggering the groundcheck)

#

before then forcing the player back out

teal viper
summer stump
#

Not sure of the context of what you're doing though

teal viper
#

That's an option too, although then you'll need to click the message to know

radiant frigate
#

so it would be debug.log(GameObject);

teal viper