#💻┃code-beginner

1 messages · Page 393 of 1

swift crag
#
var moveVector = Vector3.forward * forwardInput + Vector3.right * rightInput;
var worldVector = Camera.main.transform.TransformDirection(moveVector);
rocky canyon
#

this very useful method

#

it basically converts ur local directions into world directions

vapid yew
#

I have two Particle System components for my weapon's muzzle flash. However in this game you're not really shooting that much.
Should I disable the particle system gameObjects when not in use for a performance boost?
I'm also wondering what resources the particle systems are drawing when they're not in play-mode.

swift crag
#

you probably then want to subtract the vertical part from that vector

#

you can use Vector3.ProjectOnPlane(worldVector, player.transform.up) to get rid of the vertical part

#

then normalize it and multiply it by the original magnitude of worldVector

#

so that you don't walk really slowly if the camera is pointing into the floor

rocky canyon
vast sandal
rocky canyon
#

if thats what u mean

#

its cheaper than destroying and instantiating

swift crag
#

this is multiplying the x/y/z components of the two vectors together

vast sandal
vast sandal
#

brb

pine sun
#

hello, im following a tutorial and I cant understand why there's an error ( I highlighted the "problem in VS")

#

!vscode

eternal falconBOT
#
Visual Studio Code guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

https://on.unity.com/vscode

vast sandal
#
        movementDirection = cinemachineCamera.transform.forward * inputForward + cinemachineCamera.transform.right * inputSideways;
        movementDirection.y = 0;
        movementDirection.Normalize();
        movementVelocity = movementDirection * movementSpeed;
        playerRigidBody.linearVelocity = movementVelocity;

@swift crag @rocky canyon Tyvm!
This is what I came up with, this works 🙂
Any recommendations? Do I need a time.deltatime here? I assume no since its normalized right?

swift crag
#

Being normalized is not relevant

#

What is relevant is that you’re setting a velocity here. Don’t factor in deltaTime here

#

You use deltaTime when you’re changing something gradually over time

#

eg when applying gravity to change your velocity

#

or when applying velocity to change your position

prisma totem
#

i need some help making enemie ai i fail everytime and its getting annoying

vast sandal
swift crag
#

You’re not using your velocity to update your position here. You’re just telling the rigidbody how fast it’s going

short tusk
#

Copy that, much appreciate the clarification! 🙂

swift crag
vast sandal
swift crag
#

You’re not calculating a displacement here

pine sun
#

can someone help with this error, i cant seem to understand whats wrong

swift crag
#

(Which is indeed what you’d be doing)

vast sandal
swift crag
#

Yep!

prisma totem
#

enemi ai 😦

vast sandal
# swift crag Yep!

Any other suggestion on the code? or is that otherwise "fine-ish"?^^
How would I implement that with an acceleration btw? playerRigidBody.AddForce()?

wintry quarry
pine sun
#

i just changed my IDE and I'll rewatch the tutorial but thx

pine sun
languid spire
pine sun
#

i just did it a min ago

languid spire
rich adder
#

old version of VS

full hazel
#

can someone help me with fixing NullReferenceException: Object reference not set to an instance of an object
enemy.Awake () (at Assets/enemy.cs:30)
pls

languid spire
full hazel
#

player = GameObject.Find("player").transform;

rich adder
slender nymph
#

there is no object with that name in your scene at the time that code runs

languid spire
#

so you do not have a GameObject called player

fiery breach
#

may have messed up

full hazel
#

can someone help me fix "SetDestination" can only be called on an active agent that has been placed on a NavMesh.
UnityEngine.AI.NavMeshAgent:SetDestination (UnityEngine.Vector3)
enemy:AttackPlayer () (at Assets/enemy.cs:79)
enemy:Update () (at Assets/enemy.cs:43)

#

agent.SetDestination(transform.position);

rich adder
#

did you bake the navmesh? is it close enough to agent? is agent gameobject active ?

gusty lotus
#

Hello, I'm trying to make it a movement shooter like controller... When walking, I want to have my player gradually speed up to a target speed and then stop speeding up, but I also don't want to have a speed cap so that I am able to launch the player at higher speeds. How can I have my players stop speeding once they reach a target speed but also not use a speed cap? I'm trying to use the inbuilt force based system btw.

rich adder
gusty lotus
#

wont that mean that I wont be able to steer in the air then?

rich adder
#

its an example but just dont add onto vel

gusty lotus
#

how would I steer without adding onto the velocity

rich adder
#

only clamp the vel u got for inputs
if(vel > maxVel)
//control only steer dont add vel
else (addToVel + steer)

#

point being you dont have to clamp the whole rb vel or w/e

gusty lotus
#

the thing im confused about is

#

if I have a ton of speed

#

in a direction

rich adder
#

also your question was pretty vague to begin with

gusty lotus
#

okay mb

rich adder
#

e it a movement shooter like controller..

#

whats that mean?

gusty lotus
#

fair enough

rich adder
#

shooters come in all sorts of genres

gusty lotus
#

basically I'm just trying to get first person movement by not directly setting the speed to a velocity

#

all the tutorials I looked through directly set the speed

rich adder
#

so a rigidbody controller?

gusty lotus
#

yeah

rich adder
#

so yeah addforce would work fine

#

you dont have to clamp the whole rigidbody velocity, you can just clamp what ur max output from input controls are

#

thats if you used vel

gusty lotus
#

the thing is im trying to use force

#

should I change to vel?

rich adder
#

both have their pros and cons

#

addforce is more realistic and takes a bit more fiddling to get to be "instant"

#

changing the forcemode is one step

#

but you get deceleration and stuff out the box, drag n friction

gusty lotus
#

I heard theres a forcemode for velocity

#

should I use that?

rich adder
gusty lotus
#

ForceMode.VelocityChange

gusty lotus
#

this is really helpful

#

is it really hard to get friction and deceleration if I use a velocity based system

rich adder
#

you would have to probably manually lerp those values

gusty lotus
#

okay definetly not doing that

#

another time

#

thanks for the help tho

rich adder
#

np gl

rich adder
gusty lotus
#

possibly

#

im trying to keep my options open for later

rich adder
#

gotcha cause thats what I assumed from "launch the player at higher speeds."

gusty lotus
#

yeah thats exactly what I was thinking

#

I realized if I put a speed cap it would be really hard to implement those

rich adder
#

just cap how much output your inputs can give out when speed reaches limit, just steering

gusty lotus
#

ill look into that thanks

prisma totem
#

im looking to make a zombie ai can someone help me pls

rich adder
steep rose
prisma totem
#

i can make him follow idk how to make a attack

rich adder
#

make a basic state

prisma totem
#

idk how to do that

steep rose
#

there are tutorials

rich adder
#

if (dist <= minDistAttack)
//attack

#

break down the problem into smaller ones

#

first you already have follow so you got your target, get the distance so you know when you want to attack and ur done

swift crag
#

hell, you can start even simpler

#

just make the zombie constantly attack forever

steep rose
#

lol

swift crag
#

the attack can be controlled entirely by the animator

prisma totem
#

ok thanks that could work

swift crag
#

you can use an animation event to send a message to your component

steep rose
#

how would i store a velocity and apply it when jumping as a move() command in a character controller?

#

air control

rich adder
#

store it in a field*

#

Vector3 myVel;

steep rose
#

could i store the current velocity in there but only once?

rich adder
#

yeah just make the proper conditions to do so

#

maybe a simple bool flag will do

steep rose
#

yeah

rich adder
#

if(velWasRecorded) return;
myVel = vel;
velWasRecorded = true;

steep rose
#

how would i apply that velocity as a movement in the mmove() command?

#

wait

#

its a vector3 so it will just take it

rich adder
#

yeah look at the type your controller expects

#

you IDE should hopefully be telling you

steep rose
#

yeah sorry, my brain isnt working 🥲

strong wren
#
    {
        if (Input.GetKey("mouse 0") && SP.isSpearActive == true)
        {
            UnityEngine.Debug.Log("Spear Attack");
            SpearAnimator.SetTrigger("Attack");
            Spear.GetComponent<Collider>().enabled = true;
            SP.isSpearActive = false;
        }
    }```
#

why is this not working?

#

isSpearActive is true

swift crag
#

define "not working"

#

does nothing get loggeD?

strong wren
#

nothiong happends

strong wren
swift crag
#

I should point out that "mouse 0" is NOT a valid key

cosmic dagger
swift crag
#

read the documentation for the method you are using

strong wren
rich adder
#

use KeyCode mate

cosmic dagger
#

also, place a log at the top of the method to check that it runs . . .

swift crag
#

using KeyCode prevents bad names, yes

cosmic dagger
rich adder
#

or since its mouse you can also Input.GetMouseButton with button being index int

strong wren
strong wren
#

well i changed ti KeyCode.mouse0 and nothing changed

#

same stuff

rich adder
cosmic dagger
rich adder
#

is your ide configured?

strong wren
rich adder
#

should be capital M

strong wren
strong wren
rich adder
#

mouse

strong wren
#

i just spellt it wrong

static bay
#

There's a keycode for mouse?

rich adder
static bay
#

I just use Input.GetMouseButtonDown(0 or 1)

strong wren
#

bro trust me it WORKS

rich adder
strong wren
#

and not in the if statement?

rich adder
#

yes

strong wren
#

yeah then i get 1 log every frame

rich adder
#

then one of your conditions isn't true 🤷‍♂️

strong wren
#

both are tho

rich adder
#

or u dont notice log inside

cosmic dagger
strong wren
#

isSpearActive is True

rich adder
#

if you got multilione && it helps to put them in a quick bool var to debug it

rich adder
cosmic dagger
rich adder
#

all that matters is what it is when the code supposed to run

strong wren
rich adder
#

never assume

strong wren
static bay
# strong wren

It's possible that it's being set to true later. The inspector will only show the result at the end of an Update.

rich adder
#

so print both conditions

cosmic dagger
# strong wren

break them into separate if statements. you're responding with assumptions and we have no idea because you're not showing us the actual results . . .

covert cairn
#

Consider printing the status of both the mouse input and the isSpearBought to the console at runtime

#

If one isn't outputting what you expect, you've found what is causing the issue.

rich adder
#

bool mouseInput = Input.GetKey(KeyCode.Mouse0)
bool isSpearActive = Sp.isSpearActive
Debug.Log both

strong wren
#

wait i found smth interesting when checking if the bool isSpearActive i dont detect if the bool is true

rich adder
#

no shit

strong wren
#

true is turned on

rich adder
#

the code never lies 😏

strong wren
swift crag
strong wren
#

sooooh

rich adder
#

also when you debug.log make sure you pass the gameObject

#

make sure its the same one you expect it to be

swift crag
#
Debug.Log("whatever", this);
strong wren
#

well my script is on smth else so i cant rlly grab the gameobject

rich adder
#

your script is a component, you can pass itself to see which is calling that debug with that certain value

cosmic dagger
#

it has to be on a GameObject or else it won't run . . .

rich adder
#

how else were you running Update lol

strong wren
covert cairn
#

gameObject is inherently part of every monobehavior, which your script is because it is running every frame with update

rich adder
strong wren
#

i cant grab the Spear Gameobject by doing Debug.Log("whatever", this);
because i have the script on the camera

rich adder
#

since those are the if conditions in the same code..

#

debugging you have to go through each possibility and check stuff off

strong wren
#

this is in another script

rich adder
#

what about it?

#

ur using it in the if(Sp.isSpearActive )

strong wren
#

you said smth about running the checks for the if conditions so this is how i get the true of false value for isSpearActive

rich adder
#

also doing a inventory with bools is gonna be a nightmare

strong wren
#

its not an inv

#

i have 4 items so

rich adder
#

alr

strong wren
#

i already did the inv

#

but now for no reason my spear animation stopped working

rich adder
strong wren
rich adder
#
if(!Input.GetMouseButton(0))return;
Debug.Log($"{name} ready. is spear ready? {sp.isSpearActive} ", this);

if (!sp || sp.isSpearActive == false) return;
//do stuff
rich adder
swift crag
#

it's a variable

#

however, comma,

#

you need to log all of the relevant values here

rich adder
#

oh wops lol

#

weird naming for a var

swift crag
#

the "yes" variable, the result of Input.GetKey(KeyCode.Mouse0) and SP.isSpearActive

#

(i've never used GetKey for a mouse button. i wonder if that even works properly)

rich adder
#

usually does yea

strong wren
rich adder
#

i just wanted you to put mainly this or print name in log so we know for sure its the same instance n whatnot

rich adder
#

aka not active

strong wren
rich adder
strong wren
rich adder
#

did you put anything past the return statement like another log

strong wren
#

no

#

nothing changed

rich adder
strong wren
# rich adder show current code rq
    {
        if(!Input.GetMouseButton(0))return;
        UnityEngine.Debug.Log($"{name} ready. is spear ready? {SP.isSpearActive} ", this);

        if (!SP || SP.isSpearActive == false) return;
        UnityEngine.Debug.Log(SP.isSpearActive);
        if (Input.GetKey(KeyCode.Mouse0) && SP.isSpearActive == true)
        {
            SpearAnimator.SetTrigger("Attack");
            Spear.GetComponent<Collider>().enabled = true;
            SP.isSpearActive = false;
        }
    }
rich adder
#

try printing {SP.name} maybe

strong wren
rich adder
#

are you sure you linked correct script

strong wren
#

yes

rich adder
#

idk code says false

strong wren
#

im 100% sure

rich adder
#

can you show how you set it to true

strong wren
#

since i have 2 things that rely on SP

rich adder
strong wren
#

i just click in thru the inspector

rich adder
#

alr

strong wren
#

pretty sure its smth with the Bool

#

so theres all the codes related to the spear

#

i removed the bool and i got this

rich adder
#

which bool?

#

SP.isSpearActive ?

strong wren
#

yes

rich adder
#

are you sure you don't have 2 Stats scripts in the scene?

#

maybe grabbed wrong one

strong wren
#

nope

#

only 1

rich adder
#

or setting isSpearActive anywhere else

strong wren
#

only the fist has Stats

rich adder
#

wait....

#

is that a scene object or the one in project prefab

#

ik it says scene but make sure

strong wren
#

this is my sp

#

the thing is

#
   {
       if (Input.GetKey(KeyCode.Mouse0) && SP.isFistActive == true)
       {
           FistAnimator.SetTrigger("Slap");
           Slap.GetComponent<Collider>().enabled = true;
           SP.isFistActive = false;
       }
   }
```â
#

this code works

#

and its a copy and paste

rich adder
#

yeah thats weird

#

trying to think what it can be now.. cause its odd

#

feel like I'm overlooking something obvious lol

strong wren
#

me too

sour ruin
#

Hi, I've been referencing the example from the c# docs with the directions. See mine with the darker background. Normally i'd chatgpt syntax stuff but it seems to be giving the wrong answers, don't know where else to ask. FYI All the OnX methods are void returners.

rich adder
#

use a traditional switch

sour ruin
#

right, cool thanks

rich adder
#

the first example is an enumeration thats why it works it returns value of enum / int

strong wren
#

i just reread my code

#

and have no clue

rich adder
strong wren
#

so its a bug?

rich adder
#

wait

#

the script was running on Fist

strong wren
#

YES SIR 🫡

strong wren
rich adder
#

and Fist gets gameobject disabled?

strong wren
#

omg

#

no

rich adder
#

lol

#

good thing I told you to print the name, now it makes more sense idk how I didn't see the ss

strong wren
#

NOOO

#

omg

#

this is embarring

rich adder
#

it happens

strong wren
#

its cause i had a whiteblock before i 3d moddeled the hand and i just dissabld the mesh and renderer

rich adder
#

al good just remember update cannot run on disabled scripts/gameobjects

strong wren
#

ima put the Stats Script on the Camera or smth

rich adder
#

these types of scripts should really just be their own gameobjects

#

if I have an Inventory / Weapon switch script it would not be on the camera lol

stuck palm
#

just realised

#

nvm

rich adder
mortal spade
#

hi rlly quick question about playerprefs?
if i use PlayerPrefs.SetInt(KeyName, Value); but a playerpref with the KeyName doesnt exist yet, itll just create it with the Value i give it right ?

#

cuz im assuming thats what it does but from what i can find its not explicitly stated

mortal spade
#

ok ty :D

dense root
#

Does setting the player overrides in the inspector and the following script accomplish the same thing?

        if (collision.gameObject.layer == LayerMask.NameToLayer("Player"))
        {
            hasEntered = false;
        }
wintry quarry
#

the layer overrides would control whether collisions happen at all

dense root
#

Oh I see, thanks for the information.

gusty lotus
#

I have a 3d fps player controller and it always seems like it has friction applied to it while on the ground even when I have drag and angular drag set to 0. I want to stop the friction from being applied, anyone know how?

#

This is the material of the only thing the player is standing on

#

I don't have it set to anything

wintry quarry
#

you can remove it with custom physics materials

#

the default material has friction

gusty lotus
#

oh damn okay

#

thank you 🙏

whole parcel
#

guys what's the reference name for text mesh pro button in code

#

private TextMeshProUGUI text; like this but for a button

whole parcel
#

do i need to import anything

wintry quarry
#

The only thing about a TMPro button is that the Text compponent in the child object is a TextMeshProUGUI.

The Button component itself is normal

wintry quarry
#

Your IDE should auto suggest it for you

#

If it isn't doing that, you need to configure your IDE.

jade mulch
#

Hello! I'm making a 3D game played on a voxel grid. Like Minecraft basically, but on a smaller scale. Each block is a game object consisting of 6 child game objects that are planes making up a full cube. When blocks are placed next to each other, faces that are not visible to the player are not rendered by disabling the corresponding child game object.

Is this method acceptable or would it be more efficient to use a mesh renderer to render the required faces?

remote osprey
#

So I have a property in my Summon class that is closed to modification, but I want to Modificate it whenever Summon needs it.

public class Summon : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler, IDamageable
{
    public static event Action<Summon,Summon> OnSummonClash;
    public static event Action<Summon,Player> OnSummonPlayerClash;
    public Action Call;

    public CardData data { get; private set; }

The property in question is public CardData data

wintry quarry
remote osprey
#

Should I just make it modifiable?

#

IT's always gonna be inside something that wants to mofify it

wintry quarry
jade mulch
#

understood

restive bone
#

Hand writing a camera script makes me actually want to die

vapid yew
#
ParticleSystem fx = Instantiate(sphereParticles, transform.parent.position, Quaternion.LookRotation(transform.localRotation.eulerAngles.normalized)).GetComponentInChildren<ParticleSystem>();

I have a projectile that becomes kinematic on collision. This line instantiates a parent GameObject which has multiple children with Particle Systems.

I have set the Particle System's Simulation Space to Local and enabled Align To Direction under the shape module and yet the angle is still off!

How do I make the particle system parent GameObject flush with the collision point and have its children face forward?

eternal needle
wintry quarry
eternal needle
#

I was thinking about that real hard because I wasnt sure if it make sense 😅

wintry quarry
#

the thing to feed into LookRotation must be a direction vector

vapid yew
#

I'm really not sure tbh -- any guidance would be great.

#

The reason why I'm using transform.localRotation is because the projectile is placed into a parent gameObject and retains its rotation. And since the same class is instantiating the particles parent, I figure to use the same local rotation.

#

But I'm guessing that was a mistake 😓

eternal needle
vapid yew
#

Vector3 hit is a local method variable. I pass: col.GetContact(0).point

#

Wait fuck

eternal needle
vapid yew
#

I should be using otherCollider

#

I'm just passing through the data in a unique way. That's not the problem.

#

Although I do see the problem now

eternal needle
#

Honestly it looks like you're responding to something else, because I have no clue what you're saying in relation to what I said/suggest. Theres probably a good amount of context missing

#

Regardless, you dont wanna use the point. You want a direction, and the collision directly has the normal (aka a direction facing outwards from the object) of the surface hit

fluid fossil
#
private void Update() 
    {
        if (Input.GetKey(KeyCode.Space) && grounded)
        {
            rb.AddForce(jumpingForce * Vector3.up, ForceMode.Impulse);
        }

        Ray ray = new Ray(this.transform.position, Vector3.down);
        if (Physics.Raycast(ray, out RaycastHit hit, 1f))
        {
            grounded = true;
        }
    }

Issue:
I'm having this issue where if I hold down my space bar key, my jump input gets sent multiple times before (what I assume to be true:) grounded gets set as false and it stops allowing me to do the jump input.

Intended Behavior:
I want to be able to hold down my space key so that when I hit the ground, I immediately jump again (only once), like bhopping in a source game.

#

The raycast should immediately return false as I begin the jump, but I have reason to believe it takes anywhere between 1-7 frames to register as false

vapid yew
#

Swap the if statements around

#

@fluid fossil

fluid fossil
#

I'll try that

vapid yew
#

I'm assuming when you press space you set grounded to false because that's missing also.

fluid fossil
#

yeah I just realized that was missing, it was there before and the problem still persisted. I just accidentally got rid of it before posting here

#

the issue still persists

#

it's usually not on the first jump though

#

it's when I'm coming back down and hitting the ground

#

and I assume it's because my character is actually clipping into the ground for a frame or two before realizing it's not supposed to do that

#

it's like a 50/50 that it'll happen when im just on the ground

#

but either way, even with grounded being set to false, it still douple (and even triple) jumps

vapid yew
#

Physics calcs are done separate to update

#

You should consider using an overload with a LayerMask. Editing your projects physics settings will allow you to refine your physics calls also.

#
Physics.CheckSphere(groundCheck.position, .5f, groundMasks) && !isPlayingSFX && !isGrounded)
charred spoke
#

Physics raycast is not tied to fix update however it happens when you call it

vapid yew
#

This is what I use for my FPS controller and it works like a charm

#

In this case for context:

groundMasks = LayerMask.GetMask("Ground", "Lava", "Water");
#

You're shooting a single ray from your transform.forward. A more accurate and realistic grounding detection would be Physics.CheckSphere or Physics.OverlapSphere

#

OverlapSphere may return an array of Colliders.

#

Whereas CheckSphere does not.

ruby python
#

Mornin' all. I'm continuing on my learning SO journey and trying to figure out the 'best' way of doing things.

Currently I'm planning on different weapon types (Projectile/Laser/FlameThrower etc.)

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.VFX;
using MoreMountains.Feedbacks;

public class PlayerPrimaryWeapon : ScriptableObject
{
    public Text weaponName;
    public GameObject bulletPool;
    public int numberOfShots;

    public Transform firingPointLeft;
    public Transform firingPointRight;

    public MMF_Player leftArm;
    public MMF_Player rightArm;

    public VisualEffect weaponMuzzleFlashLeft;
    public VisualEffect weaponMuzzleFlashRight;

    public float firingRateMultiplier;
    public bool isDualWeild;

    public AudioSource weaponSound;
    public float volumeMultiplier;
}

This is my current SO setup, obviously this is essentially just for the projectile type weapon. I was wondering if anyone had any pointers in terms of adding/adjusting this to be able to deal with all weapon types.

Ideally I'd like to use a single 'one size fits all' SO and 'Shooting Script'

This is my current shooting script (hasn't been updated to make use of the SO as yet)

https://hastebin.com/share/oyewaloyaj.csharp

rich egret
#

yoooo

#
    {
        Vector3 targetLocalPosition = playerCamera.transform.TransformPoint(playerCameraRootPosition);
        transform.localPosition = Vector3.Lerp(transform.localPosition, targetLocalPosition, Time.deltaTime * 5f);
    }```

It's part of a weapon code, the code is meant to make the weapon be in the same position relative to the camera, but it doesn't work well...
storm pine
# rich egret ```void Update() { Vector3 targetLocalPosition = playerCamera.transf...

If you want it to be in the same position relative to the camera why just don't set the weapon as a child of the camera on the Start()? This will be also more efficient that calculating and updating the position frequently.
Also if you want on Update, localPosition is to change the position of the object relative to the parent and transform.position if you want to move it on the worldspace.
You maybe need this also to make sure your Camera position is updated when you do the update of the weapon: https://docs.unity3d.com/ScriptReference/MonoBehaviour.LateUpdate.html
Anyways, I still think the best option is to set the weapon as a child of the camera

ruby python
#

Hi again all,

So I've reworked my Weapon SO a bit and have got some Inheritance built in, but I'm struggling with how to get an Enum value out of the SO in my weapon firing script......

'Base' SO with the Enum.

using UnityEngine;
using UnityEngine.UI;

public class PlayerPrimaryWeapon : ScriptableObject
{
    [Header("Base Stats")]
    public string weaponName;
    public Text txtWeaponName;
    public bool isDualWeild;
    public Transform firingPointLeft;
    public Transform firingPointRight;
    public AudioSource weaponSound;
    public float volumeMultiplier;
    public enum weaponType
    {
        Projectile,
        Laser,
        Flamethrower
    }
}

What I'm trying to do is use the Enum value to control a Switch/Case in my shooting script, but can't seem to figure out how to get the value out.

Anyone have any pointers please?

cosmic dagger
ruby python
#

Oh hang on. Do I need to do

playerPrimaryWeapon.weaponType.Projectile (etc) as the 'cases'

cosmic dagger
#

oh, weaponType is an enum. you need to create a variable of weaponType in your SO . . .

#
using UnityEngine;
using UnityEngine.UI;

public class PlayerPrimaryWeapon : ScriptableObject
{
    public enum WeaponType // Enum declaration
    {
        Projectile,
        Laser,
        Flamethrower
    }

    [Header("Base Stats")]
    public string weaponName;
    public Text txtWeaponName;
    public bool isDualWeild;
    public Transform firingPointLeft;
    public Transform firingPointRight;
    public AudioSource weaponSound;
    public float volumeMultiplier;
    public WeaponType weaponType; // Variable declaration
}
ruby python
#

Aaaah, I gotcha, thank you 🙂

cosmic dagger
#

notice how i capitalized WeaponType to differentiate from the enum and variable . . .

ruby python
#

Yeah that makes sense when seeing it 'written out' 🙂

cosmic dagger
#

a bit picky, but i'd change txtWeaponName to weaponText. also, you should use Text Mesh Pro text instead of the legacy Text component . . .

ruby python
cosmic dagger
cosmic dagger
ruby python
cosmic dagger
#

they're great to use. just make sure not to modify their values. basically, they're read-only c# classes that you can edit in unity . . .

ruby python
ivory bobcat
chrome shadow
#

If i want to write a code that can increase a value but the speed it increases by also increases over time?

Like initially it starts off slow but after a few seconds it increases really fast

#

still new to coding and im not sure how to do this

#

😅

ruby python
# cosmic dagger they're great to use. just make sure not to modify their values. basically, they...

This might be really stupid, but what should I be referencing for the 'cases'?

        switch(playerPrimaryWeapon.weaponType)
        {
            case playerPrimaryWeapon.weaponType.Projectile:
                // Do things here
                break;

            case playerPrimaryWeapon.weaponType.Projectile:
                //Do things here
                break;
            default:
                //Default Stuff Here
                break;

        }

The current 'cases' are just broken/not recognised, so not really sure what I should be referencing. 🫣

cosmic dagger
ruby python
cosmic dagger
ivory bobcat
chrome shadow
ruby python
eternal needle
chrome shadow
cosmic dagger
chrome shadow
#

im not sure how to do this idea

#

part

ruby python
eternal needle
ivory bobcat
eternal needle
#

Regardless youd just keep track in update how long it's been, a simple timer using time.deltaTime. compare that to some value (how long it should be between increases). Change that value as needed

chrome shadow
#

sorry mb

#

is this correct

ruby python
eternal needle
#

Ideally you would use Update for this

chrome shadow
#

it doesnt

eternal needle
#

Then clearly it's not correct

ruby python
chrome shadow
#

thanks for the tip

cosmic dagger
ruby python
#

Okay, well I just ran it and no errors throw up and it fires. So yeah the switch is working, which is awesome. 🙂

cosmic dagger
ruby python
cosmic dagger
silver flicker
#

Hey, making a 2d platformer with circular objects that have to roll, and i need the movement snappy. After using rb.AddForce(), the first contact and first movement is great, but after letting go of all the keys the object keeps moving for a long time. Is there any way around this?

naive pawn
#

increase angular drag/drag on rigidbody, or friction on the materials, maybe

silver flicker
#

So another small question, I adjusted the friction on the physics materials for both the ground and the player object, but neither made much of a difference.

naive pawn
#

i mean, it is rolling instead of sliding

silver flicker
#

(And both at the same time)

#

Yeah, I was hoping itd still work

naive pawn
#

friction doesn't make much difference for rolling

#

that's how rolling works

silver flicker
#

Angular drag rlly doesnt change much either, I'd have to increase the speed and then increase the drag forever

#

Would any other movement methods work better?

naive pawn
#

i mean, if you're looking to make it realistic to physics, then you would just have to get the parameters realistic thonk

silver flicker
#

Im not exactly looking for realism tbh, but I'm just unsure on which movement methods would benefit me the most. I need the rolling effect and the gravity scale

naive pawn
#

just physics being realistic

silver flicker
#

Yeah, I need that, but i need a fast deceleration after adding the force which I cant quite work out

#

If I were to increase the angular drag, it slows down my playerobj. That means that I would have to increase the speed which causes the same problem

#

Would linear drag apply to a rolling object?

naive pawn
naive pawn
silver flicker
#

No, not applying a torque

#

I think I'm getting somewhere with the linear drag

#

Now I'm gonna have a battle with the stiffness

naive pawn
#

i think you would have to use the same drag as the force you're applying

#

so linear drag for linear force

silver flicker
#

Ok, and increase the gravity then?

naive pawn
#

is your jumping too floaty or something?

silver flicker
#

Well it falls rlly slowly

#

When I increase the drag

naive pawn
#

oh hm

#

yeah that makes sense

#

i can't think of anything definitely clean for that

#

maybe have a go at torque + angular drag?

silver flicker
#

Ok, I'll check the drawbacks of adding torque tho, might interfere with a load of other things

#

thanks tho

steep rose
#

!code

eternal falconBOT
lavish dove
#

I wonder if anyone can help I have a very strange issue. I have a corountine that tweens this ball from one point to the next, but after the first point it shoots off into a different direction and the code is no longer called anymore.

    public IEnumerator MoveObjectAtTime(float timeOfArrival, Vector3 target)
    {
        float duration = timeOfArrival - Time.time;
        float distance = Vector3.Distance(transform.position, target);
        float speed = distance / duration;
 
        while (transform.position.x != target.x && transform.position.y != target.y)
        {
            //Not sure about the Time.deltaTime, maybe try without and tweak it to see what results you get
            transform.position = Vector3.MoveTowards(transform.position, target, speed*Time.deltaTime);
            //wait for the frame to finish calculating
            yield return null;
        }
 
        //stops the coroutine
        Invoke("BeginNextFlightPath", 1.0f);
        StopCoroutine(flightPathCoroutine);
        // yield break;
    }
naive pawn
#

if the coroutine stops, is it maybe just bouncing off with physics?

lavish dove
#

There's nothing to bounce off. I'm thinking it might be how MoveTowards works, but in the documentation nothing explains why that would happen.

lethal bolt
#

Why dosent the player touch the Ground. When its easy to see it does?

lavish dove
#

With an explicit call to a target location with a call target location it does go to the right place, then predictably it crashes because it's an infinite loop in the code.

lavish dove
#

I think I see the problem
while (transform.position.x != target.x && transform.position.y != target.y)
Both the values need to no equal the target x or y, otherwise it skips over it, causing weird issues.

naive pawn
#

or you could compare the entire vector

lavish dove
#

Tried || that then goes into a different direction.

#

I'll try comparing the two vectors.

naive pawn
#

that should be same as comparing != || !=

lavish dove
#

Interestingly it always goes in the opposite direction after the first step.

naive pawn
hoary ice
#

im using float x - delta time as a cooldown
but i feel like its not working inside a while loop

when i put it outside the while loop its working fine
am i missing something?

naive pawn
#

while is blocking, time doesn't progress while you're inside the while (unless it's with a coroutine)

#

how exactly are you using it?

lavish dove
#

It's in a coroutine.

    public IEnumerator MoveObjectAtTime(float timeOfArrival, Vector3 target)
    {
        float duration = timeOfArrival - Time.time;
        float distance = Vector3.Distance(transform.position, target);
        float speed = distance / duration;
 
        while (transform.position.x != target.x && transform.position.y != target.y)
        {
            //Not sure about the Time.deltaTime, maybe try without and tweak it to see what results you get
            transform.position = Vector3.MoveTowards(transform.position, target, speed*Time.deltaTime);
            //wait for the frame to finish calculating
            yield return null;
        }
 
        //stops the coroutine
        Invoke("BeginNextFlightPath", 1.0f);
        StopCoroutine(flightPathCoroutine);
        // yield break;
    }
naive pawn
#

uh that was in response to the other guy

hoary ice
#

while enemy hp > 0 player will attack then applies cooldown inside the while loop

naive pawn
hoary ice
#

i tried applying coroutine and its not working

naive pawn
hoary ice
#

damn i cant show you the code cause im using visual scripting

naive pawn
#

why not

#

just screenshot it

hoary ice
#

okay wait

#

subgraph attackcooldown is just basically attack - deltatime

naive pawn
#

what are the if/while conditions

lavish dove
naive pawn
#

i don't see how that relates to it being a coroutine

storm pine
hoary ice
#

maybe i just need to use the wait node with coroutine instead of minus delta time right?

naive pawn
#

you probably need to set state instead of trying to do everything in a single pass

storm pine
broken cargo
hoary ice
naive pawn
#

are you using it for "can attack" though?

hoary ice
#

ooh good point

#

ill implement

#

but does wait for seconds work inside a while loop?

naive pawn
#

no, it needs to be in a coroutine

#

im not sure how exactly visual scripting works, but i'd guess that you don't need the while at all

#

there's already a loop, going on every frame

#

your code would be running on that loop already

#

you can only attack once per frame, so you would just use an if instead

hoary ice
#

okay im getting your point

naive pawn
#

so, if there's an enemy this frame, and you can attack, attack

now the problem is in "you can attack", how would you check for that
that's where you need the timer

lavish dove
naive pawn
#

you could use a coroutine to set "can attack" back on after a delay, or you could use your original apprach and set "time until next attack" which you count down each frame

hoary ice
#

FCK!

#

it worked

#

im so dumb

#

thanks @naive pawn

#

your name is such a stranger

#

thanks again

hoary ice
lavish dove
#

YESSSS

#

That was the problem.
Appropriately public static Vector3 MoveTowards(Vector3 current, Vector3 target, float maxDistanceDelta); If the maxDistanceDelta is negative the object will move in the opposite direction.
My code had timeOfArrival - Time.time; so on the first frame it's 5f - 0, but the next time round it'll be 5-f - 10.81f whatever so it's a negative.

#

Thank you for helping me rubber duck this one guys 😅

#

Always remember to understand fully the code you've copied off the internet 😅

topaz fractal
#

how can i create a drag variable for my charactercontroller?

swift crag
#

drag is just a reduction in velocity over time

#

very simple drag could just be

#
velocity = Vector3.MoveTowards(velocity, Vector3.zero, Time.deltaTime);
#

this slows you down by 1 m/s per second

ruby python
#

Am I missing something with Scriptable Objects or can you not assign GameObjects or Transforms that already exist in the scene to them?

swift crag
#

Assets can't reference scene objects

#

It's the exact same situation that you have with a prefab

#

(because prefabs are assets, too!)

ruby python
#

Ah bugger.

#

Okay, thanks.

chrome shadow
#

why isn't the value f updating?

swift crag
#

Several things here.

chrome shadow
#

oh wait

#

i realised

swift crag
#

f is a local vareiable of Update. It does not exist outside of Update, and it does not persist.

#

You're modifying f after you use it, so the change you made on the last line of Update isn't visible anywhere

#

Notice how your IDE is highlighting the variable here

chrome shadow
#

ahhh

swift crag
#

It's warning you that the assignment was pointless.

#

thirdly: Mathf.Lerp(0, 100, 10f) does not use the f variable at all

#

(the "f" in 10f just means that it's a float, rather than an integer)

#

Mathf.Lerp(0, 100, 10) will just return 100. Lerp gives you a value that's a percentage of the way between the first and second arguments.

#

The third argument is clamped into the [0..1] range, so you don't get 1000 or something

chrome shadow
#

omg tysm i love this channel

carmine sierra
#

what in this code is causing my character to move up from a y pos of 1.96 to 3.32 on the click of any key?

swift crag
#

It's probably starting out stuck in the ground.

#

When you move a character controller, it will find a position that isn't stuck inside a collider.

chrome shadow
#

why does the increase speed slow down at like 99?

carmine sierra
#

your right, the collider was larger than the player

swift crag
rocky canyon
swift crag
#

Lerp gives you a value that's a percentage of the way between two values.

#

If the first value is approaching the second value, then moving 10% of the way moves you less and less each time.

#

Mathf.Lerp(0, 100, 0.1f) gives you 10

#

Mathf.Lerp(90, 100, 0.1f) gives you 91

polar acorn
swift crag
#

If you want to linearly move between two values, you should track how much time has passed in your variable, and then use that as the third argument to Lerp.

rocky canyon
#

aka it'll never reach its target that way

swift crag
#
float progress = 0;

void Update() {
  progress += Time.deltaTime;
  Mathf.Lerp(0, 100, progress);
}
#

This will give you a value ranging from 0 to 100 across one second.

chrome shadow
#

ohhh

swift crag
#

note that my example does nothing with the result -- you presumably want to store it in another variable or use it

rocky canyon
#

when u pass in the value ur lerping its gonna get closer and closer and closer but never get there

carmine sierra
#

what is that unity doc website

chrome shadow
#

wow thanks a lot guys

carmine sierra
#

with all components

#

nvm found it

chrome shadow
#

im learning so much this is so fun

rocky canyon
carmine sierra
#

yh i found it

#

what is step offset for?

#

it doesnt help in the docs

swift crag
#

Note: See the Manual page Character Controller component which describes stepOffset in detail.

rocky canyon
carmine sierra
#

oh ok

naive pawn
#

it's how high the knee is 👍

rocky canyon
#

nu uh.. i can step up on things higher than my knee

spiral oak
#

Hey, I'm having trouble with an issue I don't understand. For any reason, whenever I remove a +1 from my code, Unity hangs with the "Waiting for user code in mscorlib.dll to finish executing" message. Any idea what could be happening?

naive pawn
rocky canyon
#

😄 just messin w/ ya

swift crag
#

I suspect you're getting stuck in the do-while forever

rocky canyon
spiral oak
#

in older versions it just freezed

swift crag
#

it got stuck, so it can't update the GUI anymore

spiral oak
#

oooooh gotcha

#

thanks mate :>

swift crag
#

the editor would run really really slowly if it could only do one "thing" every time it updated the UI

#

so it might show you something stale as it freezes

spiral oak
#

i see

carmine sierra
#

!code

eternal falconBOT
carmine sierra
#
  void Start()
  {
      Cursor.lockState = CursorLockMode.Locked;
  }

I want to lock the mouse, this doesnt work

willow scroll
#

It's not going to work when simply clicking Play. You should first click on the game window

sullen zealot
#

does anyone know why the particlesystem wont start?

if (tmp == 0)
        {
            DustParticleSystem.Stop();
            isPaused = true;
        }
        else if (isPaused)
        {
            DustParticleSystem.Play();
        }
#

it stops but it wont start

willow scroll
sullen zealot
#

oh i found the problem

#

i forgot to update isPaused

#

it was just starting every frame

jaunty bone
#

wait nvm

wintry quarry
silver flicker
#

Hey, been trying to get this raycast working for a while now, - https://gdl.space/aziyanusal.cs - the isGrounded bool never becomes true and I can't figure out why. All of the layers have been correctly assigned and the distance can be visually seen through the ground.

swift crag
#

Is transform.position flush with the ground?

#

or is it a bit above the ground?

#

In 2D physics, you can configure whether or not queries can hit colliders they start inside of

silver flicker
#

It's my player object, so it has gravity and does hit the ground

swift crag
#

that doesn't answer my question

#

where is transform.position? show a screenshot with the player selected

#

make sure you're set to "Pivot" and "Local" in the top left corner

silver flicker
#

In game view or in scene view?

#

Scene** got it

swift crag
#

Scene view, yeah

silver flicker
#

This is my player object

errant pilot
#

Guys i want my games quality and size to be the same for different phone aspect ratios how can i do that?

swift crag
silver flicker
swift crag
#

Okay, so that's at the center of the collider. It's not at the bottom. That's good.

#

Make sure that includedLayers is correct.

#

Also, can I see an example where the ray is visible?

silver flicker
#

The red line is the ray

cyan shoal
#
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;

public class PlayerShooting : MonoBehaviour
{
    public GameObject bulletPrefab;
    public Transform shootingPoint;
    public float bulletForce = 20f;
    public float bulletCount = 10f;

    private void Start()
    {
        Debug.Log("BULLETS: " + bulletCount);
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Mouse0) && bulletCount > 0)
        {
            bulletCount -= 1f;
            Fire();
            Debug.Log("BULLETS: " + bulletCount);

            if (bulletCount == 0)
            {
                Debug.Log("No More Bullets!");
            }
        }
    }

    public void Fire()
    {
        GameObject bullet = Instantiate(bulletPrefab, shootingPoint.position, shootingPoint.rotation);
        Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
        rb.AddForce(shootingPoint.up * bulletForce, ForceMode2D.Impulse);
        bullet.transform.rotation = Quaternion.Euler(0, 0, shootingPoint.rotation.eulerAngles.z);
    }
}
``` can someone help me on why my bullet doesn't go forward, it just falls down?
swift crag
#

You shouldn't need to set the rotation at the end there.

cyan shoal
#

it's because the bullet was faced the wrong way.

swift crag
#

You're already using the shootingPoint's position and rotation in the Instantiate call

#

This shouldn't make the bullet fail to move, though

#

Make sure that bulletForce isn't set to 0 in the inspector.

cyan shoal
#

it isn't

silver flicker
#

Ah, I got it working fen, it looks like i was confusing the tags with the layers. Thanks for helping me realise that lol

swift crag
cyan shoal
#

well, I'll see, but I just need help on the bullet not shooting outwards, and just falling

#

nvm got it working perfectly

#

thank you @swift crag

swift crag
#

what was the issue?

ruby python
#

Hey all, I'm having a little bit of a brain blockage atm, and hope someone can point me in the right direction.

            if(hitInfo.collider.gameObject.CompareTag("Enemy"))
            {
                GameObject enemyHit = hitInfo.collider.gameObject;
                Enemy enemyScript = enemyHit.GetComponent<Enemy>();
                EnemyImpactController enemyImpactController = enemyHit.GetComponent<EnemyImpactController>();
                enemyScript.enemyCurrentHealth = enemyScript.enemyCurrentHealth = playerPrimaryWeapon.laserDPS;
                enemyImpactController.EnemyHealthCheck(enemyHit.transform.position);
            }

I have this code which is for a laser weapon, it works great but I need to 'slow down' the amount of damage that is sent to the enemy script (enemyCurrentHealth) on this line.

enemyScript.enemyCurrentHealth = enemyScript.enemyCurrentHealth = playerPrimaryWeapon.laserDPS;

Current laserDPS is set to 0.1f. I can't for the life of me think of how to 'slow down' the subtraction of laserDPS as at the moment it's instant 0.

#

This gets called in Update btw.

swift crag
#

this just sets the enemy's health to 0.1

#

you wrote an = sign

ruby python
#

Yep, just spotted the typo. lol.#

swift crag
#

Also, you need to factor in Time.deltaTime once you're subtracting

#

Otherwise you're subtracting 0.1 every physics update

#

so you'd be doing 0.1*50 = 5 damage per second

ruby python
swift crag
#

think about the units

lethal bolt
#

Does anyone know an sulution i couldnt find one?

swift crag
#

playerPrimaryWeapon.laserDPS

#

this is measured in damage per second

swift crag
#

notably, this part:

#

There is no implicit reference conversion from 'UnityEngine.GameObject[]' to 'UnityEngine.Object'.

lethal bolt
#

Oh

swift crag
#

So you need to multiply this value by a duration

lethal bolt
#

because i have done the list thing before

swift crag
swift crag
#

You gave it an array of game objects.

#

It can't accept an array of game objects

#

Ever.

ruby python
#

You're trying to reference a single GameObject prefab on instantiate, but your tiles are setup as an array

lethal bolt
#

oh

ruby python
misty pecan
#

RaycastHit2D[] hits = Physics2D.CircleCastAll(transform.position, targetingRange, (Vector2)transform.position, 0f, enemyMask);

Hashtable hitsTable = new Hashtable();
foreach (RaycastHit2D hit in hits)
{
hitsTable.Add(hit.transform.gameObject.GetComponent<Enemy>().progress, hit.transform);
}
target = ?;

I want the target to be the highest progress enemy's transform, ive been stuck trying to figure out how?

swift crag
#

don't use Hashtable; it's non-generic

#

so it just holds object

#

you should use Dictionary in its place

#

however, that's also not appropriate here

misty pecan
#

what should i do?

swift crag
#

You really just need to keep track of the enemy with the highest progress

#

there's no need to store an entire collection

#
float best = -1;
Enemy bestEnemy = null;

foreach (var hit in hits) {
  if (hit.transform.TryGetComponent(out Enemy enemy)) {
    if (enemy.progress > best) {
      best = enemy.progress;
      bestEnemy = enemy;
    }
  }
}

if (bestEnemy) {
  // do something with it
}
#

note a few other changes here

#

there's no need to do hit.transform.gameObject -- you can just use the hit transform directly to call TryGetComponent

#

and TryGetComponent means that this won't throw an error if you accidentally hit something that doesn't have an Enemy on it

misty pecan
#

Does var mean it can be any datatype?

swift crag
#

No, it just means that the type is inferred

#
var x = 1;
int x = 1;
#

These are equivalent

misty pecan
#

ohh

swift crag
#

var is not an "any" datatype, like object (roughly) is

#

the really scary one is dynamic, where the type is figured out at runtime

#

You can use var whenever the type can be figured out from context

misty pecan
#

Ah thanks

swift crag
#

An annoying exception is enumerating a Transform

#
foreach (var child in transform)
#

child winds up being an object

#
foreach (Transform child in transform)
#

this works correctly

#

it's because Transform implements IEnumerable, not IEnumerable<Transform>

#

All it promises is that it'll give you objects

misty pecan
#

implements IEnumerable?

swift crag
#

That's the interface that lets your class be used with foreach

#

(among other things)

#

Most of the time, you implement IEnumerable<T> where T is some specific type

swift crag
misty pecan
#

Oh ok thanks

timid oriole
#

why is my character flipping on its side help 🙂

swift crag
carmine sierra
#

I know that velocity needs to be applied as a new vector3

#

but since i was using a character controller before, i wanna know how I can change what i had previously into a WASD movement system

swift crag
#

Everything should continue to work just fine

slender nymph
#

you need to transform your input to be relative to the rigidbody's rotation. you can achieve that by calling transform.TransformDirection on the rigidbody's transform and pass in your direction vector. it will return the rotated vector

misty pecan
carmine sierra
slender nymph
#

that would make it move in the correct direction

timid oriole
#

Can someone help me with my issue whenever you guys are done helping him

slender nymph
#

there's also no queue, so just ask your question

willow scroll
willow scroll
timid oriole
carmine sierra
slender nymph
slender nymph
carmine sierra
#

I have the direction set, i just need it to translate by that in the direction the thing is facing

slender nymph
#

and i told you how to get the correct direction. so do that

willow scroll
# timid oriole wym?

The player is moved down. Your scene shows the player's global arrows. It gets reversed, but still moved down, so, for some reason, it's ordinate, the yellow (or green) arrow is not changed.

carmine sierra
timid oriole
#

hmmm so Is this a coding issue ?

#

or rigidbody issue

willow scroll
slender nymph
timid oriole
willow scroll
timid oriole
#

local direction is different than world space direction

#

local direction is relitive to the object I think where direction is just direction in space that's static

willow scroll
#

Yeah, I want you to select Local Space in the scene window

timid oriole
#

i selected it

willow scroll
#

And now show the arrows

carmine sierra
timid oriole
willow scroll
slender nymph
carmine sierra
#

you said it will return the rotation

#

but how do i pass that into the new vector3()

#

each parameter is a diff axis

slender nymph
#

no i didn't, i said it returns the rotated vector

carmine sierra
#

ohh okay

slender nymph
#

not a rotation. but rather the actual vector3 you will use

carmine sierra
#

so then i would just translate that rotated vector?

slender nymph
#

wtf do you mean by "translate" it? tell me you aren't going to attempt to use transform.Translate

willow scroll
# timid oriole

Now you can see the ordinate not going from the bottom to the top

carmine sierra
timid oriole
#

origin?

carmine sierra
#

the rb.velocity = new vector3(x,y,z)
and transform.transformdirection is meant to go in here somewhere

slender nymph
willow scroll
carmine sierra
swift crag
#

notably, setting a velocity is not "translating" a rigidbody

#

you're setting the rigidbody's velocity

#

that's it

timid oriole
slender nymph
carmine sierra
swift crag
#
  • rigidbody
  • a vector
willow scroll
swift crag
#

in common usage

#

in some fields, perhaps

timid oriole
swift crag
#

just call them the X/Y/Z axes and it'll be significantly more obvious what's being described

willow scroll
#

What else has y? Right! Vectors!

timid oriole
#

yeah

willow scroll
swift crag
#

I would never call the green arrow the "ordinate".

#

It's not a single coordinate. It's a basis vector of a coordinate space.

willow scroll
timid oriole
#

perhaps this issue stems from incorrect blender export settings?

#

as unity and blender planes are different

#

the y in unity is up where blender y is horizontal

carmine sierra
#

if the transform.transformdirection function returns the rotation why do i need to pass in parameters

slender nymph
swift crag
#

did you read anything we've told you? I genuinely don't think you have.

carmine sierra
willow scroll
swift crag
#

You give it a vector. It gives you a new vector.

#

The vector you give it is interpreted as a local-space direction

#

The vector you get is a world-space direction

#

If you give it Vector3.forward, you'll get a world-space vector that points in the direction that is your "forward"

swift crag
#

so as you rotate your transform around, the resulting vector will change

swift crag
# timid oriole

This isn't the rotation I'd expect for an fbx imported from Unity

#

You get a 90 degree rotation around the X axis

swift crag
#

It transforms a direction.

#

hence the name

willow scroll
# timid oriole same

I suppose, Rigidbody.velocity uses world space, so it should move the character down, as it does. Not sure whether it also rotates it. Perhaps, you have any animations, which may do it?

timid oriole
timid oriole
swift crag
#

you can avoid this problem entirely by parenting the model to an empty object

#

and then putting the rigidbody, etc. on the empty object

#

Now you can rotate the model however you want

timid oriole
#

Didn't fix it it still rotated

#

do you mean move everything all my scripts rigidbodys and colliders onto the empty object?

#

and have the playermesh just be a mesh

swift crag
#

But yes, you'd otherwise be moving most of your components to the new "Player" object

carmine sierra
#

I know this is inefficient code, but not sure how I can make this better

swift crag
#

I guess I'd just do moveDirection.z = 10f instead of using the constructor again

#

note that this means you're flying into the sky at 10m/s..

willow scroll
# timid oriole Didn't fix it it still rotated

Is it rotated if you move the object using its Transform instead of Rigidbody?

Vector3 direction = new(moveDirection.x, Time.deltaTime, moveDirection.z);

transform.Translate(direction);
carmine sierra
swift crag
#

oh

swift crag
#

🤦

#

Blender brain

carmine sierra
#

fairs

swift crag
#

thank god nothing uses +X up

ruby python
#

y = up

#

up/down

timid oriole
#

I meant as he just put Time.deltaTime there

ruby python
#

Bugs the crap out of me when stuff uses Z up/down lol.

ruby python
ruby python
#

lol. what?

carmine sierra
#

is locking my characters rotation until something triggers it a good idea

#

by un freezing it through script

#

cause they flop over when they stop walking

swift crag
#

I think you've answered your question (:

ruby python
#

Unless you need the character to rotate on the X and Z axes, you could lock those axes in the rigidbody?

carmine sierra
#

also my character slides when i stop clicking the walk button

#

is that a rigidbody feature

timid oriole
#

y error?

carmine sierra
#

or a coding issue

rich adder
ruby python
#

Case sensitive

swift crag
#

first law of motion, etc.

#

there is friction, so it slows down

carmine sierra
slender nymph
carmine sierra
#

cause i dont need ice skating in the game

timid oriole
swift crag
#

set the velocity to 0 when you stop moving

carmine sierra
#

good idea

slender nymph
#

that's what their error is, sure. but that's not their issue. the issue is that the assignment is backwards.

rich adder
#

ohh yes mb just saw that

timid oriole
slender nymph
#

floats do not have a y coordinate

timid oriole
#

wait

#

im dumb it was a spelling error

#

V was not capitlized

slender nymph
#

yes that's part of the issue

rich adder
timid oriole
#

yeah u right

#

However it still cannot move for some reason

slender nymph
#

are you calling the method anywhere

timid oriole
#

fixed update

rich adder
#

dont grab inputs in fixedupdate

slender nymph
#

nah, that's perfectly fine here

rich adder
#

is it? ohh cause its not a keydown

timid oriole
#

I thought physics related things should be in fixed update?

carmine sierra
#

if i can do input.getaxisraw to detect WASD, is there a corresponding method which detects the release of those axis keys?

slender nymph
rich adder
carmine sierra
rich adder
#

although to be sure I would store it in a v3 and use that for comparison
since it has approximation, but prob overkill for GetAxis

slender nymph
# timid oriole Yes

do you have anything else interfering with its position such as a CharacterController or Animator that controls the transform.position in any of its states?

carmine sierra
#

you mean if the key were to be pressed down very minimially?

#

minimally

rich adder
# carmine sierra you lost me there icl

normally is fine don't even worry. GetAxis will just give you 0 if you're not inputting
Im just saying I would store them in a v3 so I can do things like if(moveInputs != Vector2.zero) //not moving
`moveInputs = new Vector2(GetAxis("Horizontal"), GetAxis("Vertical")) etc..

slender nymph
timid oriole
slender nymph
#

okay for starers, you do know that Update is not FixedUpdate, right? so you are calling this in Update not FixedUpdate like you said you were

timid oriole
#

I switched it when you told me to?

slender nymph
#

also make sure that your fields are set correctly in the inspector

slender nymph
timid oriole
#

someone told me to that it shouldn't be in fixed update

rich adder
#

nah I was mistaken

slender nymph
#

someone said don't get input in FixedUpdate and then were immediately corrected

timid oriole
#

ah

summer stump
#

GetButtonDown or Up or things that are only true a single frame have issues in FixedUpdate, but held inputs like GetAxis are fine since they will always last longer than a single frame anyways

rich adder
#

interesting. I was always under the impression the first press can be missed, but it makes sense since the function spans over frames anyway

carmine sierra
#

ignore this line

#

the rotation of the char is working

#

just the movement is locked to the z axis

#

i know where the issue is, just not how to fix it

ruby python
slender nymph
rich adder
#

ahh okay that makes a lot more sense now

summer stump
slender nymph
rich adder
carmine sierra
slender nymph
eternal falconBOT
carmine sierra
#
    void Move()
    {
        //Movement
        float horizontal = Input.GetAxisRaw("Horizontal");
        float vertical = Input.GetAxisRaw("Vertical");
        Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;
        //Movement Rotation
        if (direction.magnitude >= 0.1f) {
            float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
            float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
            transform.rotation = Quaternion.Euler(0f, angle, 0f);
            Vector3 moveDir = rb.transform.TransformDirection(Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward);
            rb.velocity = new Vector3(moveDir.x,moveDir.y,moveDir.z);
        }
        else if (direction.magnitude < 0.1f) {
            rb.velocity = new Vector3(0f, 0f, 0f);
        }
    }
slender nymph
#

Vector3 moveDir = rb.transform.TransformDirection(Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward);
what do you think this is doing

slender nymph
#

no the entire thing. what do you think that is doing

carmine sierra
#

it gets the rotation of the vector and multiplies it by vector3.forward

slender nymph
#

now explain why you are doing that

carmine sierra
#

tbh i copied the quaternion bit from some tutorial

slender nymph
#

and you didn't read what i told you about transforming your input

swift crag
#

so you copied random code and mashed it together and you expect it to work

carmine sierra
swift crag
#

this is not a good mindset. you need to know why you're doing each thing

carmine sierra
carmine sierra
swift crag
slender nymph
carmine sierra
#

like i know what transformdirection does and the diff between character controllers and rigidbodys

#

and how to use move each one

#

so i dont see how its a waste of your time

naive pawn
#

this is stuff you couldve learned on your own through an article or a video or docs, structured to teach

carmine sierra
slender nymph
#

read the rest of the message to find out how to do it

carmine sierra
#

i like learning through my own projects, but if its necessary to do something else

#

then sure

carmine sierra
slender nymph
#

what did i tell you to pass into the TransformDirection method

carmine sierra
#

whats a direction vector?

slender nymph
#

look at your variables

carmine sierra
#

okay so ig your right ab the time wasting, cause if i knew the code i copied i would have understood what you said

naive pawn
slender nymph
swift crag
#

if you don't know what a direction vector is, it is extremely unlikely that you know what TransformDirection does

carmine sierra
carmine sierra
#

cause thats what id call it

slender nymph
#

and that vector is made up of what?
yes, your input

carmine sierra
#

write

slender nymph
#

oh fuck off then. stop wasting everyone's time by trying to fix a bunch of code that you didn't write that you also have no understanding of

carmine sierra
#

is it that deep?

slender nymph
#

there are beginner c# and unity courses pinned in this channel, start there

carmine sierra
#

you dont need to be here