#💻┃code-beginner
1 messages · Page 393 of 1
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.
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
i like to use 1 particle and disable/enable it
Thats basically where I was at and why i asked for that weird vector..
Was trying to do Vector3.Scale(moveVector, inputVector)
but yeah it seems to "only" work like you're sayin
this makes no sense
this is multiplying the x/y/z components of the two vectors together
Yeah i realized 😄
Yeah I had a wrong thought 😉 Ima look into what you guys proposed and check that out 🙂
brb
hello, im following a tutorial and I cant understand why there's an error ( I highlighted the "problem in VS")
!vscode
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?
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
i need some help making enemie ai i fail everytime and its getting annoying
I assume you mean acceleration here?
So time.deltatime for accelerations but this is a velocity?
No. Both were written correctly — gravity is an acceleration
You’re not using your velocity to update your position here. You’re just telling the rigidbody how fast it’s going
Copy that, much appreciate the clarification! 🙂
Velocity times duration gives you displacement. That’s when you use deltaTime.
Yeah ik that its a acc..
Oh... I see, since im setting it to a specific velocity i DONT need deltatime here.
But as soon as its an acceleration I would need it?
You’re not calculating a displacement here
can someone help with this error, i cant seem to understand whats wrong
If you were adding an acceleration to your velocity, yes
(Which is indeed what you’d be doing)
Aaah gotcha, because its acc * TIME (or in this case, deltatime) gotcha!
Yep!
enemi ai 😦
Any other suggestion on the code? or is that otherwise "fine-ish"?^^
How would I implement that with an acceleration btw? playerRigidBody.AddForce()?
- You need to configure your IDE
- You didn't name your things the same as the tutorial
i just changed my IDE and I'll rewatch the tutorial but thx
its actually cus i didnt save the input actions......
you still need to configure your ide to get further help here
i just did it a min ago
screenshot your code editor
old version of VS
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
show the code line or do we just have to guess?
player = GameObject.Find("player").transform;
u dont have something named player
there is no object with that name in your scene at the time that code runs
so you do not have a GameObject called player
may have messed up
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);
so put your agent on the navmesh
did you bake the navmesh? is it close enough to agent? is agent gameobject active ?
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.
if(vel > maxVel) return;
//capturing inputs section
wont that mean that I wont be able to steer in the air then?
its an example but just dont add onto vel
how would I steer without adding onto the velocity
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
also your question was pretty vague to begin with
okay mb
no worries, just explain a little what exact mechanic are you going for
e it a movement shooter like controller..
whats that mean?
fair enough
shooters come in all sorts of genres
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
so a rigidbody controller?
yeah
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
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
ForceMode.VelocityChange
oh damn thank you
this is really helpful
is it really hard to get friction and deceleration if I use a velocity based system
you would have to probably manually lerp those values
np gl
btw are you trying to make like speed boost or jumper ramps ?
gotcha cause thats what I assumed from "launch the player at higher speeds."
yeah thats exactly what I was thinking
I realized if I put a speed cap it would be really hard to implement those
yeah aslong as you dont do basically this
rb.velocity > maxVel
rb.velocitity = maxVel
just cap how much output your inputs can give out when speed reaches limit, just steering
ill look into that thanks
im looking to make a zombie ai can someone help me pls
ask a specific question ?
there are plenty of tutorials for this
i can make him follow idk how to make a attack
make a basic state
idk how to do that
there are tutorials
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
lol
the attack can be controlled entirely by the animator
ok thanks that could work
you can use an animation event to send a message to your component
how would i store a velocity and apply it when jumping as a move() command in a character controller?
air control
could i store the current velocity in there but only once?
yeah
if(velWasRecorded) return;
myVel = vel;
velWasRecorded = true;
how would i apply that velocity as a movement in the mmove() command?
wait
its a vector3 so it will just take it
yeah look at the type your controller expects
you IDE should hopefully be telling you
yeah sorry, my brain isnt working 🥲
{
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
nothiong happends
nope
I should point out that "mouse 0" is NOT a valid key
what is "mouse 0"?
read the documentation for the method you are using
right click
use KeyCode mate
also, place a log at the top of the method to check that it runs . . .
using KeyCode prevents bad names, yes
i mean, is that the correct name for it?
or since its mouse you can also Input.GetMouseButton with button being index int
the method lays in an update method sooo
yes
well i changed ti KeyCode.mouse0 and nothing changed
same stuff
cause its still wrong..
so what? does the method run or not?
is your ide configured?
yes
should be capital M
yes
it is with a capital M
mouse
i just spellt it wrong
There's a keycode for mouse?
indeed
I just use Input.GetMouseButtonDown(0 or 1)
bro trust me it WORKS
ok did you check if code runs at all with what Random suggested?
putting the Debug in the method?
and not in the if statement?
yes
yeah then i get 1 log every frame
then one of your conditions isn't true 🤷♂️
both are tho
or u dont notice log inside
then check that both conditions are true . . .
if you got multilione && it helps to put them in a quick bool var to debug it
you have to see during playmode in code
then you'd get a log inside the if statement . . .
all that matters is what it is when the code supposed to run
but im not
never assume
i didnt
It's possible that it's being set to true later. The inspector will only show the result at the end of an Update.
so print both conditions
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 . . .
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.
bool mouseInput = Input.GetKey(KeyCode.Mouse0)
bool isSpearActive = Sp.isSpearActive
Debug.Log both
wait i found smth interesting when checking if the bool isSpearActive i dont detect if the bool is true
no shit
true is turned on
the code never lies 😏
what
There are two possibilities:
- You just found a compiler bug
- You made a mistake
The former is highly unlikely.
sooooh
also when you debug.log make sure you pass the gameObject
make sure its the same one you expect it to be
Debug.Log("whatever", this);
well my script is on smth else so i cant rlly grab the gameobject
wdym
your script is a component, you can pass itself to see which is calling that debug with that certain value
it has to be on a GameObject or else it won't run . . .
how else were you running Update lol
i dont think yall understood me
gameObject is inherently part of every monobehavior, which your script is because it is running every frame with update
also print clearer debugs
i cant grab the Spear Gameobject by doing Debug.Log("whatever", this);
because i have the script on the camera
mate..we need to know which script/component is running the checks
since those are the if conditions in the same code..
debugging you have to go through each possibility and check stuff off
{
isFistActive = false;
isSpearActive = true;
isPistolActive = false;
isARActive = false;
}```
this is in another script
you said smth about running the checks for the if conditions so this is how i get the true of false value for isSpearActive
also doing a inventory with bools is gonna be a nightmare
alr
yes and you need to check what the value is in the code when you try to hit the MouseButtonDown
smth like this?
{
UnityEngine.Debug.Log(yes);
if (Input.GetKey(KeyCode.Mouse0) && SP.isSpearActive == true)
{
yes = 1;
SpearAnimator.SetTrigger("Attack");
Spear.GetComponent<Collider>().enabled = true;
SP.isSpearActive = false;
}
}```
if(!Input.GetMouseButton(0))return;
Debug.Log($"{name} ready. is spear ready? {sp.isSpearActive} ", this);
if (!sp || sp.isSpearActive == false) return;
//do stuff
debugging "yes" thats helpful.
try this one
#💻┃code-beginner message
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)
it does
usually does yea
i just wanted you to put mainly this or print name in log so we know for sure its the same instance n whatnot
no when spear is ready i get no return
wdym by that sorry ?
like when its off i get that
but when its onn i get nothing
did you put anything past the return statement like another log
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;
}
}
if its not printing past that then its not reaching
try printing {SP.name} maybe
what?
are you sure you linked correct script
yes
idk code says false
im 100% sure
can you show how you set it to true
since i have 2 things that rely on SP
show the full context of the SpearAttack script. use https://gdl.space
i just click in thru the inspector
alr
pretty sure its smth with the Bool
so theres all the codes related to the spear
i removed the bool and i got this
yes
or setting isSpearActive anywhere else
only the fist has Stats
wait....
is that a scene object or the one in project prefab
ik it says scene but make sure
scene
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
yeah thats weird
trying to think what it can be now.. cause its odd
feel like I'm overlooking something obvious lol
me too
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.
pretty sure void aint valid type for a switch expression
use a traditional switch
right, cool thanks
the first example is an enumeration thats why it works it returns value of enum / int
try resetting both scripts and relinking the references
so its a bug?
YES SIR 🫡
yes
and Fist gets gameobject disabled?
lol
good thing I told you to print the name, now it makes more sense idk how I didn't see the ss
it happens
its cause i had a whiteblock before i 3d moddeled the hand and i just dissabld the mesh and renderer
al good just remember update cannot run on disabled scripts/gameobjects
ima put the Stats Script on the Camera or smth
i know
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
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
yes it does
ok ty :D
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;
}
That code isn't doing anything related to that inspector stuff, no
the layer overrides would control whether collisions happen at all
Oh I see, thanks for the information.
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
The physics engine has friction
you can remove it with custom physics materials
the default material has friction
guys what's the reference name for text mesh pro button in code
private TextMeshProUGUI text; like this but for a button
Button
do i need to import anything
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
using UnityEngine.UI; naturally
Your IDE should auto suggest it for you
If it isn't doing that, you need to configure your IDE.
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?
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
This will be super inefficient
Should I just make it modifiable?
IT's always gonna be inside something that wants to mofify it
1 GameObject per voxel is already extremely inefficient. Upping that to 7 is even worse
understood
Hand writing a camera script makes me actually want to die
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?
which part here are you actually considering the collision point with? I just see the instantiation with the local euler angles as a direction, which doesnt really make sense. Maybe you want to use the collision normal here
Quaternion.LookRotation(transform.localRotation.eulerAngles.normalized))
This doesn't make any sense at all
I was thinking about that real hard because I wasnt sure if it make sense 😅
the thing to feed into LookRotation must be a direction vector
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 😓
did you try what i wrote above? about using the collision normal
Are you using chatgpt? I dont know how u got that from "collision normal"
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
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
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
I'll try that
I'm assuming when you press space you set grounded to false because that's missing also.
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
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)
Physics raycast is not tied to fix update however it happens when you call it
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.
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)
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
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...
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
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?
just access the enum variable . . .
That's where I'm struggling, 'weaponType' doesn't show up as an 'acceptable' variable.
Oh hang on. Do I need to do
playerPrimaryWeapon.weaponType.Projectile (etc) as the 'cases'
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
}
Aaaah, I gotcha, thank you 🙂
notice how i capitalized WeaponType to differentiate from the enum and variable . . .
Yeah that makes sense when seeing it 'written out' 🙂
a bit picky, but i'd change txtWeaponName to weaponText. also, you should use Text Mesh Pro text instead of the legacy Text component . . .
Yeah, there are some things I want to change. tbh, I've never used TMPro, seems overkill for what I need tbh. But yeah the txtWeaponName is just a force of habit thing left over from my college VisualBasic days. lol.
yes, since WeaponType was created inside of PlayerPrimaryWeapon . . .
don't worry, it's not overkill. it's the default and new (not anymore) way to use text. that's why the package comes pre-installed. every thing about it is better than legacy text . . .
Yeah, it's just a 'what I'm used to' thing really, atm I'm just trying to learn the ins and outs of SO's. I haven't even 'built' the UI yet. lol.
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 . . .
Yeah, I know that part, and am finally understanding why they're beneficial. 🙂
You'd practically just reference the tmpro, ui or text and do the same thing you'd do with regular ui text. https://docs.unity3d.com/Packages/com.unity.textmeshpro@1.0/api/TMPro.TMP_Text.html
The main difference would be having higher resolution text (old school text can be blurry) and some added features of tmpro which you can ignore.
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
😅
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. 🫣
just be careful or you'll end up down the rabbit hole; creating pluggable methods (actions) with SOs and every script being runfrom an SO . . . 😅
Okay thanks 🙂 Will have a look once I have SO's sorted in my brain. lol.
each case will be each of your enum values . . .
I see a question mark but I'm not quite understanding the question. Yes you can write code to increase a value over time. Yes, you can implement it using a variable rate.
yeah mb like i want Value A to increase over time but the rate it increases by also increases over time
so basically the speed it increases by gets faster
Hmmm.......I'm doing something wrong somewhere as none of the values are showing up in the 'autocomplete' box 😕
How are you increasing the value in the first place?
uhhh thats kinda my question
each case should be from the actual enum type, not the instance:
case PlayerPrimaryWeapon.WeaponType.Projectile```notice i'm accessing the type, not the instance . . .
Yeah, literally just figured that out. lol. Thank you 🙂
Your question is about changing how often a value is increased. Surely you have a value that is already being increased if you ask this
Maybe you should show what you've tried and explain where you've gotten stuck.
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
Okay, sorry to be annoying, but in general, this should work right? (I haven't modified the shooting script to use the data from the SO yet beyond the Enum.)
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Does it work? We also cant even see the whole delay between increases part, which is the whole question
Ideally you would use Update for this
it doesnt
Then clearly it's not correct
I'm using a simple timer in this code.
Have a look and you should be able to figure it out.
thanks for the tip
looks fine to me, though there are spots you can refactor to reduce code repetition. i'd place the code within each case in a separate method. much easier to read and tweak, if necessary. does it work when testing?
I haven't tested as yet, need to rework some of the code before doing that. And yeah I know I can refactor the methods where I'm switching hands into one method. I like to work 'verbose' when figuring things out and then refactor.
Okay, well I just ran it and no errors throw up and it fires. So yeah the switch is working, which is awesome. 🙂
Sweet! Definitely test after making small changes. If you wait too long and change or create a lot of code, it'll be harder to debug . . .
Oh yeah I know. lol.
Thank you for the help, really appreciate it 🙂
No problem. I don't do much myself, but it's easier to help others . . .
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?
increase angular drag/drag on rigidbody, or friction on the materials, maybe
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.
i mean, it is rolling instead of sliding
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?
drag is proportional to velocity squared, so i don't think scaling should be too much of a problem
i mean, if you're looking to make it realistic to physics, then you would just have to get the parameters realistic 
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
this is my code - https://gdl.space/fuqaqatifi.cs
i don't mean realistic realistic, im just referring to the physics of the objects being believable
just physics being realistic
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?
yes, it's moving linearly
you're not applying a torque though, actually? you're applying a linear force
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
i think you would have to use the same drag as the force you're applying
so linear drag for linear force
Ok, and increase the gravity then?
is your jumping too floaty or something?
oh hm
yeah that makes sense
i can't think of anything definitely clean for that
maybe have a go at torque + angular drag?
Ok, I'll check the drawbacks of adding torque tho, might interfere with a load of other things
thanks tho
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
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;
}
if the coroutine stops, is it maybe just bouncing off with physics?
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.
Why dosent the player touch the Ground. When its easy to see it does?
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.
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.
so || that i guess?
or you could compare the entire vector
Tried || that then goes into a different direction.
I'll try comparing the two vectors.
that should be same as comparing != || !=
Interestingly it always goes in the opposite direction after the first step.
gonna need a bit more info to go off of here
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?
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?
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;
}
uh that was in response to the other guy
while enemy hp > 0 player will attack then applies cooldown inside the while loop
hey actually why is that in a coroutine? if you're trying to do it per frame, why not just put that in Update
i tried applying coroutine and its not working
yeah, how exactly are you implementing that
damn i cant show you the code cause im using visual scripting
what are the if/while conditions
I'm doing it as a corotine because I need to iterate through an array of position for the path of the ball.
i don't see how that relates to it being a coroutine
Use the distance value as a statement on the while loop. While(distance > 0.02){
//Recalculate distante
}
It so hard that an object achieve a specific position
maybe i just need to use the wait node with coroutine instead of minus delta time right?
maybe, no clue what you're trying to achieve
you probably need to set state instead of trying to do everything in a single pass
Also you will be maybe interested on a tween engine, like LeanTween, that automatic made the process of animation with a specific ease in case you need it
using direct comparison while also using Vector3.MoveTowards is fine because of MoveTowards implementation
Ah, good to know
im using state machine already
are you using it for "can attack" though?
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
okay im getting your point
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
That causes it to stop in place.
float duration = timeOfArrival - Time.time; I'm starting to think maybe the time extended duration over time might be the issue.
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
FCK!
it worked
im so dumb
thanks @naive pawn
your name is such a stranger
thanks again
this made so much sense to me lol
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 😅
how can i create a drag variable for my charactercontroller?
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
Am I missing something with Scriptable Objects or can you not assign GameObjects or Transforms that already exist in the scene to them?
Assets can't reference scene objects
It's the exact same situation that you have with a prefab
(because prefabs are assets, too!)
why isn't the value f updating?
Several things here.
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
ahhh
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
omg tysm i love this channel
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?
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.
why does the increase speed slow down at like 99?
your right, the collider was larger than the player
so this is a very common error
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
Because you are moving the object some percentage of the way between f and 100. That percentage is the amount of time between frames. So you're setting it to about 2-5% if the way between current and 100
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.
aka it'll never reach its target that way
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.
ohhh
note that my example does nothing with the result -- you presumably want to store it in another variable or use it
when u pass in the value ur lerping its gonna get closer and closer and closer but never get there
what is that unity doc website
wow thanks a lot guys
im learning so much this is so fun
https://docs.unity3d.com/Manual/ the manual?
Note: See the Manual page Character Controller component which describes stepOffset in detail.
https://docs.unity3d.com/Manual/class-CharacterController.html
The character will step up a stair only if it is closer to the ground than the indicated value. This should not be greater than the Character Controller’s height or it will generate an error.
yeah i checked that
stairs
oh ok
it's how high the knee is 👍
nu uh.. i can step up on things higher than my knee
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?
smh autojump user over here
😄 just messin w/ ya
If i is zero, this will skip nothing
I suspect you're getting stuck in the do-while forever
lol
so in recent Unity versions you get that message whenever your code gets stuck in a loop?
in older versions it just freezed
it's a coincidence: you're just seeing whatever the editor last displayed in the GUI
it got stuck, so it can't update the GUI anymore
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
i see
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
I want to lock the mouse, this doesnt work
It should work if the method is called and the game window is focused
It's not going to work when simply clicking Play. You should first click on the game window
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
Is tmp not 0, and isPaused true?
oh i found the problem
i forgot to update isPaused
it was just starting every frame
wait nvm
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.
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
It's my player object, so it has gravity and does hit the ground
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
Scene view, yeah
This is my player object
Guys i want my games quality and size to be the same for different phone aspect ratios how can i do that?
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?
The red line is the ray
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?
You shouldn't need to set the rotation at the end there.
it's because the bullet was faced the wrong way.
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.
it isn't
Ah, I got it working fen, it looks like i was confusing the tags with the layers. Thanks for helping me realise that lol
is shootingPoint rotated 180 degrees on the X/Y axes, or something?
ah, yeah, that'll do it
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
what was the issue?
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.
Yep, just spotted the typo. lol.#
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
I'm being such a spanner at the minute. lol. Could you point me in the rough direction for this please?
think about the units
Does anyone know an sulution i couldnt find one?
did you read the error message
notably, this part:
There is no implicit reference conversion from 'UnityEngine.GameObject[]' to 'UnityEngine.Object'.
Oh
You need to convert this into plain damage -- not damage per second
So you need to multiply this value by a duration
But why. Is it because the prefabs has children?
because i have done the list thing before
damage seconds damage
------ * ------- = ------
second 1 1
no, C# has no clue about your prefabs at all
You gave it an array of game objects.
It can't accept an array of game objects
Ever.
You're trying to reference a single GameObject prefab on instantiate, but your tiles are setup as an array
oh
Ah thank you. Sorry, brain a bit mushed. lol
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?
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
what should i do?
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
Does var mean it can be any datatype?
No, it just means that the type is inferred
var x = 1;
int x = 1;
These are equivalent
ohh
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
Ah thanks
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
implements IEnumerable?
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
That'd make this first example work properly.
Oh ok thanks
anyway, does this make sense?
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
Everything should continue to work just fine
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
Thanks sm it works perfectly
how would that help with the movement
that would make it move in the correct direction
Can someone help me with my issue whenever you guys are done helping him
there's also no queue, so just ask your question
It's strange to me how global and local pivos for your player are the same...
They have already asked it above
it was above but got lost in the messages
wym?
so i cant just change the one line and get it working
then maybe link to it or something next time instead of implying you haven't asked it yet
i don't know wtf you are referring to by that
the last line
I have the direction set, i just need it to translate by that in the direction the thing is facing
and i told you how to get the correct direction. so do that
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.
what tutorial can i watch, i dont know enough to understand how i can get from what you told me to do to the result
Could you give the screenshot with the local directions now?
do you really need a tutorial that tells you how to write one line of code to call a method i already explained how to use?
Do you know what local directions are?
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
And now show the arrows
i went on docs and it doesnt help me understand how transformdirection works
Transforms
directionfrom local space to world space.
did you not bother reading what i said about how to use it?
you said it will return the rotation
but how do i pass that into the new vector3()
each parameter is a diff axis
no i didn't, i said it returns the rotated vector
ohh okay
not a rotation. but rather the actual vector3 you will use
so then i would just translate that rotated vector?
wtf do you mean by "translate" it? tell me you aren't going to attempt to use transform.Translate
Now you can see the ordinate not going from the bottom to the top
i just call moving it translate
I don't understand what ordinate is exactly?
origin?
the rb.velocity = new vector3(x,y,z)
and transform.transformdirection is meant to go in here somewhere
words have meaning. you should use the correct words to mean the correct things otherwise you're going to run into issues where people are misunderstanding what you are actually trying to do
You may try using your browser
idk what else to call it, moving it?
notably, setting a velocity is not "translating" a rigidbody
you're setting the rigidbody's velocity
that's it
I read the defention but I don't understand it lol. It's a distance between coordinates?
at this point you are practically asking us to spoon feed you the answer. put in some effort at solving your issue with the information provided
i dont even know where to start tbf
new word located
there are only two objects in existence here
- rigidbody
- a vector
Is that a problem with your browser?
just call them the X/Y/Z axes and it'll be significantly more obvious what's being described
yeah
Currently, I prefer using cool words
I would never call the green arrow the "ordinate".
It's not a single coordinate. It's a basis vector of a coordinate space.
Well, I've mentioned that it's not the same as the player's global one now
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
if the transform.transformdirection function returns the rotation why do i need to pass in parameters
what?
it's like you didn't even bother reading what i said about using that method or what the docs said about it
the docs just say stuff that dont make sense to me
Yeah, but it seems like Rigidbody should move the character to the left, which is it's local down. So I'm not sure why it rotates it.
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"
same
so as you rotate your transform around, the resulting vector will change
This isn't the rotation I'd expect for an fbx imported from Unity
You get a 90 degree rotation around the X axis
ohhh okay
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?
So it's a problem with the fbx settings then?
I removed it didn't make a difference
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
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
The colliders could stay on the model.
But yes, you'd otherwise be moving most of your components to the new "Player" object
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..
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);
? is z not forward
oh
still moving scripts over atm
fairs
thank god nothing uses +X up
what about the y Axis?
I meant as he just put Time.deltaTime there
Bugs the crap out of me when stuff uses Z up/down lol.
Ah sorry, missed the conversation. lol.
lol. what?
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
I think you've answered your question (:
Unless you need the character to rotate on the X and Z axes, you could lock those axes in the rigidbody?
yeah but in terms of are there better solutions
also my character slides when i stop clicking the walk button
is that a rigidbody feature
y error?
or a coding issue
read it and it telsl you why
you cant directly set the property of a position v3
Case sensitive
well, if you don't set the velocity, then the rigidbody will keep moving as it was
first law of motion, etc.
there is friction, so it slows down
so how can i make it so it doesnt slide
your line is backwards
cause i dont need ice skating in the game
it tells me but it didn't help me lol my understanding was that playerRb.velocity.y gets current velocity and im just assigning it to an empty variable
set the velocity to 0 when you stop moving
good idea
that's what their error is, sure. but that's not their issue. the issue is that the assignment is backwards.
ohh yes mb just saw that
so something like this then? In the website it shows that he has to put pthen a dot for the coordinate like x or y its using right?
floats do not have a y coordinate
yes that's part of the issue
besides that, this one makes no sense on a float
are you calling the method anywhere
fixed update
dont grab inputs in fixedupdate
nah, that's perfectly fine here
is it? ohh cause its not a keydown
I thought physics related things should be in fixed update?
if i can do input.getaxisraw to detect WASD, is there a corresponding method which detects the release of those axis keys?
is your rigidbody dynamic with no constraints on any of the axes it is supposed to be moving on?
no u can check the float is 0 though
Yes
genius
its the only time it would actually be 0
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
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?
you lost me there icl
No I don't only rigidbody
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..
then show the entire class because something in the code must be wrong
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
I switched it when you told me to?
also make sure that your fields are set correctly in the inspector
at what point did i say to do that
someone told me to that it shouldn't be in fixed update
nah I was mistaken
someone said don't get input in FixedUpdate and then were immediately corrected
ah
#💻┃code-beginner message
If you wanna reread
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
interesting. I was always under the impression the first press can be missed, but it makes sense since the function spans over frames anyway
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
This is what I thought too tbh. Input in Update(), movement etc in FixedUpdate();
if you are just querying the current state of the input, that is fine to do where ever you are actually going to consume that input. if you are trying to react to changes in the input you need to do that in Update as FixedUpdate will likely not be fast enough for all changes to input
ahh okay that makes a lot more sense now
That is probably true, but as long as the input is registered at the time movement CAN happen, it is fine. If you are moving in fixed, then the missed updates wont actually make a difference
this is what is generally recommended because it is easier for newer people to understand. but it isn't always as cut and dry as that, the GetAxis methods can be used in either with very few issues happening
Aaah fair enough. 🙂
oh yeah that makes sense since its applied when the physics update runs
any ideas? I dont know how I can fix this
can you share your !code correctly so that i can copy/paste the lines that are causing that instead of typing them out manually
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
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);
}
}
Vector3 moveDir = rb.transform.TransformDirection(Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward);
what do you think this is doing
the * vector3.forward?
no the entire thing. what do you think that is doing
it gets the rotation of the vector and multiplies it by vector3.forward
now explain why you are doing that
tbh i copied the quaternion bit from some tutorial
and you didn't read what i told you about transforming your input
so you copied random code and mashed it together and you expect it to work
i get what your saying, im rusty at this
this is not a good mindset. you need to know why you're doing each thing
i did its just i didnt have the background knowledge to understand it
ig i am just having a rushed mindset cause i wanna make as much as possible in the time i have
this is a waste of everyone's time
read this again because there's pretty much no "background knowledge" required. i explained what you use and what to pass into it
#💻┃code-beginner message
tbh i dont see how since i learned the stuff that was stated to me
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
this is stuff you couldve learned on your own through an article or a video or docs, structured to teach
i mostly get this but i dont get what transforming the input really means
read the rest of the message to find out how to do it
is there one good way to learn stuff like this
i like learning through my own projects, but if its necessary to do something else
then sure
ive read it about 10 times, maybe my reading comprehension is bad but i dont really understand it
what did i tell you to pass into the TransformDirection method
whats a direction vector?
look at your variables
okay so ig your right ab the time wasting, cause if i knew the code i copied i would have understood what you said
there are several
ah so you didn't write any of this yourself?
if you don't know what a direction vector is, it is extremely unlikely that you know what TransformDirection does
no just the movedir line
is direction the rotation
cause thats what id call it
then surely you know what "your direction vector" is referring to considering you have a fucking variable named direction that is a vector
and that vector is made up of what?
yes, your input
oh yh i didnt right that one either
write
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
is it that deep?
there are beginner c# and unity courses pinned in this channel, start there
you dont need to be here
very useful method
