#💻┃code-beginner
1 messages · Page 156 of 1
it works here but not there thats why im confused
honeslty, I just need an event that is called automatically in editor, that must be called before I close the inspector for the SO
https://docs.unity3d.com/ScriptReference/AssetModificationProcessor.html
Maybe something like that? Have not really looked into it
Does OnValidate() not get called though? Could check if it does
or maybe SerializationCallback interface
Good thing I specified one change and gave you a resource then
it does, but I wanted to call a method less frequently
that saved me a considerable amount of time thanks to you.
Hello, I'm working on a game that involves soldiers automatically firing on enemy units within a certain range. I have functionality for aiming and firing at a set target, but its a bit choppy getting the logic for choosing a target down. Currently Im using a collider on trigger to determine range that sets collided objects to be the target. However on its own that meant soldiers were switching to new targets once they entered range instead of finishing off their old targets. I have a little progress where now I check to see if the target field is null before the collision sets a new target. The problem with this is that if there are two enemies close by, once the originally targeted enemy dies, the troopers do not target the other once because its already within the collider's sphere. Any ideas how to fix this?
Current relevant code:
private void OnTriggerEnter(Collider collider)
{
if (collider.TryGetComponent<EnemyID>(out EnemyID enemytroop))
{
if (targetTransform == null)
{
targetTransform = collider.gameObject.transform;
}
}
}
idk what did i do but it worked, i tried your comparetag but it didnt work then pressed ctrl z until i got my old code back but it worked again? thanks anyways
add to a list of transforms in range instead, that way you can just select a new target
bump 😄
OnTriggerStay or w/e it's called probably would fix the second problem.
along with managing how you want to focus a target
if this is for a lot of units, might want to consider just storing in a list. OnTriggerStay will be called 50 times each frame, for each target, for each enemy. If you dont have too much going on then its not a concern really.
With a list you can also have it easily compare which target is closest, which entered first/last etc
basically gives you more control of what to target
Give them an id and start with the lowest in the array
and what do your errors say?
Ive never seen a raycast done that way
the line that says if(Physics.Raycast(ray, out hitInfo, distance, mask))
not what line, what's wrong? it'll tell you
well when i hit play
you have 2 errors underlined in red that you can hover over and read
before you even hit play, you can see that there are errors
yes but what is wrong?
what does the error say? it should tell you
that you havent read the errors yet
sounds like you should check that function and make sure your arguments are in the correct order
you are using 3d raycast btw
(yeah that's the real problem but hopefully we'd get there through actual debugging)
yes
your hit is 2d
oh
they can't mix
So what the 2d hit doin
that was a stupid mistake
best kind to make since they are easy to fix
I imagine it still won't work
if you follow the errors they will get you there
was considering not saying anything, but them reaching that conclusion would probably take awhile since they werent even looking at errors at the start. Would have to see errors -> look docs for declarations -> notice it doesnt have raycasthit2d as a parameter
I cant see how they've got it setup working in the docs
Egg on my face, learn something new every day
So does Ray just store pos and direction?
yep a ray is an origin with a direction
hello, my script machine is fully broken, I can't right click or zoom in or out or anything. Does anyone know what's going on?
Script machine?
yea script machine component for visual scripting
this is for writing code,#763499475641172029 for that server
Haven't a clue, if in doubt restart the editor
reset your layout in the top right corner if the editor windows are messed up
visual scripting basically a disadvantage imo, less people use it
than standard scripting
IDEs are so complex now they basically are visual scripting
👀 interesting point of view
definitely not lol
You type like 2 letters in a configed Rider and it already knows what you wanna do
sometimes, usually just finishes word.. like autocomplete on ur cellphone.
that has nothing to even do with visual scripting
its not gonna autocomplete an entire script, or finish ur system for ya
anyways, give the #763499475641172029 a shot
maybe u can find some help in there
or if u can convert what u have into normal code u can just ask here, and convert it back into visual code
Wait, visual scripting does that?
that may be viable
no, lol not that know of.. but u made it sound like thats what an IDE does
so ur using Bolt?
should I use RigidBody or Logic to move my character in the overworld of a pokemon type Overworld???'
No, I just had in my head visual scripting was like that Unreal Engine type thing where you drag the lines around
its whatever is built into unity
Ideally you should learn to use both tools in tandem because visual scripting is a better solution sometimes, and other times, traditional code is best. Learning how and when to use each is one in the same as learning how to use unity.```
That is, indeed, visual scripting.
^ good reply to a forum thread where they asking regular's for help in visual scripting
Unreal encourages you to use Blueprints to produce specific behaviors after you write some "bedrock" code in C++
I think the same applies here.
How does Unity actually create the gameobjects in a scene when a scene is loaded? Is the actual creation in the c++ side of it?
You can hide the code (syntax) but you cannot hide the logic.
either way you'll use logic.. but i know what you mean.. and its pretty much up to you
like changing the transform.position I mean
do you need a Physics heavy character?
if not.. don't use a rigidbody.. use a CC instead
Not really, I´m worried about collisions
Character controller is a lot less of a headache
CC doesn't have Gravity so you'll have to code that in
a Rigidbody doesn't have Ground Checks or Stair Climbing Capability you'll have to code that in..
Or you can roll your own detection system if little to no common game movement is needed. Not very practical though.
I ´ve gone this way but I wanted to make sure because CC is tempting
they both can do teh same things as each other..
Stairs, slopes, ground detection, friction managing..
Vs
Adding gravity
physics is pretty easy to just setup and like the physics engine react..
Yeah, if you visualize a pokemon type player movement gravity isn´t necessary
a CC will be lots of coding to get elevators, or knockbacks, etc to work
but a Rigidbody will just work with that stuff, after you code in the ground checks and stuff
Never thought of that
If you're doing grid based old school jrpg/dungeon crawler-like, you'll not need anything complex to move your character.
The thing is I´ll make a transition between battle and overworld exploration
so maybe I can use CC for Overworld
and RigidBody for the combat phase
Yeah thats true, I´m facing a problem with my own logic which is that the character has this inertia/moment even if I stop pressing the key and I don´t know how to eliminate that
What would cause an object to freeze a variable after one use in a built version of a game?
Are you using Rigid Body physics?
My enemies should fire bullets at me, and yet they fire one round and then just stop firing
And it works fine in editor?
Yes
Maybe show your implementation and folks may help you debug.
They still follow the player which is even more confusing
Probably something running too high FPS that needs to be migrated from Update to FixedUpdate if I had to hazard a guess
Did you build as development?
It's a timed event though
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Uh... no
this sounds inappropriate
What's a development build do?
put things in FixedUpdate if they need to interact with physics
its like a debug version
you'll have a Console.. and see debug logs
show your code.
What
not applicable

like an inappropriate programming decision
not the other interpretation of "inappropriate"
(:
Like a paste bin version?
Alright
I mean, weren't given a lot to work with and that's the only thing I can think of that has caused me errors in build only
Your movement field would be the limiting factor as to whether there will be any movement or not.
It's assigned the x and y values every update, so perhaps set those values to zero if input is no longer being applied
Okay, lets see
We'd need to see where you're calling register x and y
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I thought of adding an if(is pressing w,a,s or d)
if (Input.GetKey(KeyCode.LeftShift))
{
_playerMovement.Run();
}
else if (Input.GetKeyUp(KeyCode.LeftShift))
{
_playerMovement.StopRunning();
}```
this is a little off... GetKeyUp() would be registered on the next frame..
bullet code
enemy code
getkey and getkeyup can't be triggered on the same frame
so the else if() really isnt necessary
if(transform.position.x == target.x && transform.position.y == target.y)
I'm not a huge fan of this. It actually should work okay, since you're using Vector2.MoveTowards, which returns exactly the "to" vector if it's close enough
But exact comparisons of floats like this are just inviting problems with floating point error
So your movement isn't the culprit. Do you've got anything else moving your character?
especially if you're setting the position into transform.position
Not really
That's going to update your transform's local position.
This may result in a slightly different world position than the one you asked for.
Instead, do this:
if (Vector3.Distance(transform.position, target) < 0.01f)
pick some small value
if (Input.GetKey(KeyCode.LeftShift))
{
_playerMovement.Run();
}
if (Input.GetKeyUp(KeyCode.LeftShift))
{
_playerMovement.StopRunning();
}```
for those to work they'd have to be in seperate if statements
With your second script, we can assume that the movement vector can be a zero vector. Anything multiplied by zero (all parts of the vector are zero) will result in a zero vector. Either movement somehow isn't zero or something else is moving the character.
the else if block checking for Input.GetKeyUp(KeyCode.LeftShift) might not be triggered if another key is pressed in between the Update frames. If another key is pressed, the else if block won't be executed even if the Left Shift key is released in the same frame.
Okay, fixed, thanks!
it is not a vector zero
im assuming that is directed at me, theres a good bit going on here lol
Nothing is jumping out at me here. You should check your Player log to see if there are errors being thrown.
yes :p
basically, favor checking if two vectors are really close together rather than testing if their x and y values are identical
will do, imma check the devbuild
the thing is that it is not a big movement but it is a tiny little space that my character advances because of inertia or moment of some kind
Were you saying your character doesn't stop if the keys are released or takes it's time to stop (delayed)?
yeah... i set a timer on em if they bounce off of something
it takes a liiiitle amount of time to stop
which I don´t like at all for a game of this characteristics
ill be back in a bit if i find anything odd
you can use an additional condition to check if ur registerX and Y are zero.. or (approximately 0) and if they are can call a function to stop the player
my controllers usually stop on their own. b/c they're continuously using the inputs with a multiplier to move..
when its 0 (0 * multiplier = 0) so no forces/movement goes thru the player
When you normalize the vector, your vector will attempt to give itself a magnitude of one. So even if the value is decreasing because the input was released, it'll delay a bit till it's too little to be normalized
https://docs.unity3d.com/ScriptReference/Vector3-normalized.html
Maybe consider raw input
sorry, what is raw input
With raw input, the values will be either zero, one or negative one. You'll not get the miniscule values in between, which you aren't wanting as those values will count towards the normalized result.
how'd u write ur code? most tutorials will explain the difference.. thats the very first thing i learned in unity
good segue on how smoothing works
does anyone know how i can get world bounds of a ui element?
thats a good one.
well odd i did indeed find
Could probably convert the screen coordinates to world coordinates, blue's on the more appropriate track
its saying the object that i want to instantiate is null after the first fire@swift crag
any idea what could cause that?
Oh, are you destroying the prefab
thanks
shouldnt be
sounds like you might be
should be destroying closes just like all the other enemies
Yeah. You’re destroying shot
bruh... clones*
you're discarding the instantiated object
i keep getting blocked by the mod bot lol
Good
var cloneBullet = Instantiate(prefab, ...);
// later
Destroy(cloneBullet);```
What you have right now is Destroy(prefab)
You should have been getting a bunch of warnings in your console about trying to destroy a prefab.
naming your variables more clearly would help avoid this btw. If your variable was called bulletPrefab you would be less likely to accidentally destroy it
if this is the issue, why would the other spawned objects not break?
what other spawned objects?
because you didn't do that to the other objects?
even if you hit your mailbox with your car, your front door will be fine
EnemyShooterAI does not destroy anything other than its shot prefab.
Don't you see how this code is destroying the prefab?
it used the same code that the player uses to fire its bullet, so im a bit confused
well you didn't show us that, so we can't tell you why things are different
fair enough
How to post !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 bet it's different
i presume it correctly destroys the instance, or doesn't destroy anything at all
It is passing the reference to the prefab to Destroy
Look in your console.
You will find out why.
the editor probably stops you from doing that and says "Destroying prefabs is bad, don't do it" in the console
oh...
you really shouldn't be ignoring warning messages in your console. Unity isn't printing them for fun.
im a dimwit
i have had an error for a while like that
wasnt causing issues so i ignored it
an error like this perhaps?
Yes.
wow im dense
A prefab is a kind of asset, and you were asking Unity to destroy the asset.
With an error, your play session will attempt to run the most recent working version that did not have any errors
huh?
Oh, runtime error
and when it's a compile error, unity just refuses to run :p
GameObject laser = (GameObject)Instantiate(CirclePrefab, firePoint.position /*+ new Vector3(0.0f, 0.0f, 0)*/, itGuy.rotation /*Quaternion.identity*/); so a variation of this should fix it?
thats the players version
okay, and what is the type of the CirclePrefab variable?
public GameObject CirclePrefab;
okay, so there's no need for that GameObject cast
that was confusing to me
anyway, yes, you'll save the reference returned by Instantiate
then pass that to your destroy coroutine
Alternatively
You can just do Destroy(thing, 2f); to destroy something after 2 seconds
is it not needed when getting rotations?
This code doesn't "get a rotation"
the rest does
if you mean when you pass a rotation to Instantiate, then no
Instantiate always returns whatever the type of its first argument is
`float worldHeight = Camera.main.orthographicSize * 2.0F;
float worldWidth = worldHeight * Camera.main.aspect;
Vector2 position;
position.x = Random.value * worldWidth - worldWidth / 2.0F;
Debug.Log("Laser 1 Fired Successfully");
GameObject laser = (GameObject)Instantiate(CirclePrefab, firePoint.position , itGuy.rotation );
Rigidbody2D rb = laser.GetComponent<Rigidbody2D>();
rb.velocity = transform.right * laserSpeed;
StartCoroutine(scheduleDestroy(5.0F, laser));
IEnumerator scheduleDestroy(float delay, GameObject target)
{
yield return new WaitForSeconds(delay);
Destroy(target);
}`
heres the full thing
lotta extra stuff that i didnt fix tho...
Ah, yeah. Not sure why I thought otherwise. Test builds maybe..
I don't see anything here that "gets a rotation" other than itGuy.rotation
which reads out the rotation of the Transform named itGuy
regardless, the cast is not necessary: the method will return a GameObject if you give it a GameObject
ah
The cast might have been necessary in Unity's ancient past
its a tag check mb
maybe before they included the generic Instantiate method
in that case, it would've always returned UnityEngine.Object
Why's your bold font so foul 👀
its for collisions maybe? if not then ya are right about it being unneccesary
you would not cast to GameObject in a collision method either
not even comparing gameboject tags?
the audio is set to be hearable up to the circle but i hear it max volume all the way in the house
yucky safari
looks like this to me with Vivaldi (which is chromium)
you'd just get the game object of the collider or rigidbody you hit directly
you would not do any casting here, no
Rarely do you have to cast something
Casting is necessary when you have a less-specific type than you want. This often indicates you're doing something wrong.
ig im just using non necessary stuff...
3D lvl was 0, mb
You should do things for strong reasons, not just because you saw it once!
its how ive done everything...
thats honestly a bad habit im guessing
Yes. It leads to code that implies things that aren't true, which makes it hard to reason about your code
GameObject foo = (GameObject) Instantiate(something); implies that something is not a GameObject
and there aren't many other valid types for something in that case
pretty much just UnityEngine.Object
carp, i still broke it lol
GameObject shot = (GameObject)Instantiate(shot, transform.position, Quaternion.identity);
You already have a variable called shot
Why the cast?
i thought i was the only one who said carp
Now, it's not an error to declare a local variable with the same name as a field
But this does shadow the field
shot no longer refers to the field
still giving the same error, do i need to directly add a prefab variable to the script?
So you're trying to pass shot, the local variable, to Instantiate
so im still killing the prefab...
oops
this will never compile.
what did you change it to?
im still coroutining the shot...
`if(timeBetweenShots <= 0)
{
//GameObject laser = (GameObject)Instantiate(CirclePrefab, firePoint.position /+ new Vector3(0.0f, 0.0f, 0)/, itGuy.rotation /Quaternion.identity/);
GameObject bullet = (GameObject)Instantiate(shot, transform.position, Quaternion.identity);
timeBetweenShots = startTimeBetweenShots;
StartCoroutine(scheduleDestroy(2.0F, bullet));
IEnumerator scheduleDestroy(float delay, GameObject target)
{
yield return new WaitForSeconds(delay);
Destroy(target);
}
}`
fixed it
and youwere right
This looks fine, save for the pointless (GameObject) cast that you can just get rid of.
shot also wasnt working lol, i didnt save the script when i ran it😂
removing it wont break anything?
Of course not, as long as the type of shot is GameObject
bullet = Instantiate(shot, transform.position, Quaternion.identity);
so like that?
GameObject bullet = Instantiate(shot, transform.position, Quaternion.identity);
ill try it, now im curious why i ever was casting it to start with?
my 3rd project and ive done it on all 3
but hear me out.
(int) (short) (long) (uint) (int) enumState
whats uint?
unsigned int
and enumstate
32 bits of unadulterated INTEGER
imma use that... wait, can it be assignd later?
an enum is an integer, with special named values
enumState is a variable name
wait, i read unassaigned
uint is really useful when you want to do bitmath, but negative numbers are confusing
I presume it's an enum type.
mb
an enum lets you declare a new type with a fixed set of values
public enum Color {
Red,
Green,
Blue
}
internally, an enum is just an integer
in this case, Red=0, Green=1, Blue=2
Enums show up fairly often in Unity. They're used wherever there's a small set of options.
so red green and blue are now integar variables?
uint just lets you handle the actual 32 bits without messing with negative numbers flipping bits and all that crap
Color myColor = Color.green;
oh...
don’t name your enum Color. That is confusing
public enum Cardinal { Up = 1, Right = 2, Down = 4, Left = 8}
This defines an enumeration type called Cardinal
now you're naming enums after birds!
let’s say i have Cardinal direction. This represents a direction, but in code, it is actually just an integer
oki, now i have a stupid unrelated question
but now I can do things like check direction == Cardinal.Up; instead of direction == 1, which makes no sense when you look at it
enum types are just integers with predefined values specific to that enum type
when running build, how do i force the build to specific screen size/resolution
my build makes the game look funny bc the resolution is way off
been a long time, but I would check Project settings
yeah... i tried that, and the internets unity looks different from mine
kinda triggering tbh
the how too looked easy and mine didnt even have the same settings
@swift crag thx man, ya fixed my broken enemy issue
can't reference a prefab in a prefab because.. FU that's why
EDIT: In the end, this was due to user error, and does actually work as one would expect
I have a simple overhead healthbar HUD Canvas thing that is a prefab. good luck getting it working on multiple enemy prefabs without jumping through so many hoops it would make an acrobat nauseous
prefabs can reference other prefabs and assets just fine
they just cant reference scene objects for obvious reasons
also there are many ways to make references, if enemies need health bars for example, just have them notify a system in your UI and pass a self reference
enemy health bar
@north kiln i removed the parenthesis, i dont get the error anymore but the debug.log is not being triggered
the issue is not adjusting the value of the Health Bar, it is getting it to recognize the health bar to begin with. it is a nested prefab. Best method i have found so far is FIndGameObjectWithTag. dilemma being, i assumed that since it was on the same object, finding each other would be a simple GetComponent, but it seems that is not the case with nested prefabs
and logs are not hidden in the top right of the console window?
Here is an example of what i am having issue with. i am sure there is a simple way around it, i just do not know it.
using UnityEngine;
using UnityEngine.UI;
public class HungryAnimal : MonoBehaviour
{
void Start()
{
Canvas WhyYouNoWork = GetComponent<Canvas>();
if ( WhyYouNoWork != null ) { Debug.Log("Found"); }
}
}
the Canvas is not found. this is after unpacking it, and also just flat out adding another Canvas as a test
Is the script on the Canvas/1 object?
No, it is on the main Prefab
Then why should it find it?
they are on the same object. why should it Not find it?
GetComponent only gets components on the same object.
ok, perhaps a misunderstanding. the Script and the Canvas are on the same Prefab
Does the prefab root have a canvas component?
Do you see it in the hierarchy inspector on the left side?
Okay, lets make things clear: what is displayed in the hierarchy?
And what is displayed in the inspector?
They are both in the image shared above.. what are we trying to get to here?
sorry, i do not know what you mean.. the screenshot is of the hierarchy..
I'm trying to figure out if you understand what a hierarchy is
https://docs.unity3d.com/ScriptReference/Component.GetComponent.html
Gets a reference to a component of type
Ton the same GameObject as the component specified.
Do you?
we have not seen a screenshot that shows your canvas component yet
is the hierarchy in the screenshot or not?
GetComponent only looks on the gameobject its called on and no further
In general
so will only find components on the exact same gameobject
is a prefab a gameobject?
It's made up of gameobjects.
its made of one or many gameobjects
ok, that is helpful
A hierarchy always shows only gameObjects and their relationship. Inspector only ever shows components(aside from materials and custom inspectors) of the selected object.
If you don't see a component in the inspector GetComponent wouldn't find it either.
Ok, so at this point, the way i am finding it is by Tag. it seemed to me that there should be a more direct route to 'find' it
Prefab or not doesn't matter. Consider prefab edit mode as a small separate scene. It doesn't change how components and gameObjects work.
A serialized reference would be direct
Ok, therein lies the problem, i cannot seem to serialize a reference to something in the same prefab
You can do that just fine
you can do that just fine, a prefab can have references to stuff inside of its self and assets including other prefabs
only restriction is scene objects
When i attempt to Drag the the thing titled Canvas, which is of Type Canvas from the Prefab (shared prefab), to the serialized reference spot, i get just a red circle with a line
take bigger screen shot that shows the object you are trying to drag in as well
it sounds like it is either not a canvas or its a scene object and not part of the prefab
Can you show the canvas' inspector?
You should be able to drag that object into that reference just fine, if it's not allowing you then that's very strange. Are you looking at that inspector with the root of the prefab selected from the hierarchy window? Or did you have it selected from the project
this is the main prefab that i double clicked in the Project
Perhaps select the root via the hierarchy and see if you can drag and drop then
Yes! Thank you
By having this 'active/highlighted' i was able to drag the Canvas to the Serialized Field
i am not 100% sure how i screwed it up, but i am sure it was user error
Thanks again everyone
You likely did not have it opened in the prefab editor and were trying to drag in a canvas from your scene not the one in the prefab
i think you are right. I must have been flip flopping between double clicked open, and single click selected, and not realizing it
Oh, no.. there is none in the Scene. pretty sure it was the half open, click vs double click thing
I can reproduce it now. when in this single clicked state, i cannot drag to it
but when in this double clicked state, i can
Yet, both show it available, and indentical Inspector (for most parts)
Obvious now, but in my frustration i did not realize i was alternating between fully open and not.
public class SocketIndicator : MonoBehaviour
{
public enum Status { Idle, On, Disconnect, Emit }
[SerializeField] private Text indicator;
[SerializeField] private int statusResetDuration;
public void OnStatusChange(Status status)
{
StopCoroutine(ResetStatus());
switch (status)
{
case Status.Idle:
indicator.text = "I";
break;
case Status.On:// 3 seconds reset to idle
indicator.text = "R";
StartCoroutine(ResetStatus());
break;
case Status.Emit:// 3 seconds reset to idle
indicator.text = "E";
StartCoroutine(ResetStatus());
break;
case Status.Disconnect:
indicator.text = "D";
break;
default:
indicator.text = "N/A";
break;
}
}
public void OnStatusChange_Reconnect(int attempt)
{
indicator.text = attempt.ToString();
}
private IEnumerator ResetStatus()
{
yield return new WaitForSeconds(statusResetDuration);
indicator.text = "I";
}
}```
is it optimized enough?
we planned to make an indicator UI that told users and beta tester the websocket status
as you see in the code, when websocket event is called, they will call this script as well
can someone help me, i still cant figure my movement controller out
so, to double verify, like the GetComponent, there is no GetObjectOfTypeAndName in this prefab?, it would always be a Find scenario? When not serializing, i mean
your best bet would be to put a link back to the original question when you are pinging for assistance
this
ok, that shows the final issue, but not anything about your actual controller
idk what is is though
Did you write code to make a controller, or are you using a third party controller code?
im using one from a video
So, you would need to share the code
/code
!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.
thanks
//using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private CharacterController controller;
public float speed = 12f;
public float gravity = -9.81f * 2;
public float jumpHeight = 3f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
Vector3 velocity;
bool isGrounded;
bool isMoving;
private Vector3 lastPosition = new Vector3(0f,0f,0f);
void Start()
{
controller = GetComponent<CharacterController>();
}
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float x = Input.GetAxisRaw("Horizontal");
float z = Input.GetAxisRaw("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
if (Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
if (lastPosition != gameObject.transform.position && isGrounded == true)
{
isMoving = true;
}
else
{
isMoving = false;
}
lastPosition = gameObject.transform.position;
}
}
Can you maybe start the game paused, switch to the scene view and take a screenshot from the bird's eye view?
alr
Also, when that happens, are you holding down a key, or does it just kamikaze off the side on its own?
Also if you could record a video of the issue with your mouse rotation disabled, it would be helpful.
you perhaps have a joystick or a space mouse attached to your computer?
no, i only have mouse and keyboard
ok
i just had to go back to a save, i bluescreened
how do i keep edits i make while playing?
I really think that the issue could be related to your mouse rotation code. Could you disable the component and record a video of the issue again?
yes
Mp4 please?
You don't normally.
figured out a way lol
@teal viper
hey so my Ai script was working just fine for some time but now it wont detect the player
it was not facing the right direction so to solve it i placed the scripts into a parent in the parent (but i dont think that could be affecting in any way)
heres how it looks (mazeDog: scripts + mesh, dog: animations and objects)
and heres the script
@teal viper
Okay. Can you make the input variables public or serialized fields so that we can see them in the inspector and record a video just like the one you made again?
yea, 1 second
Draw debug rays to see where they are cast and wether they hit anything
tbh i dont know how to do that
Just declare public float x and the same for y at the top of your script where the rest of the fields are. Then remove the "float" from the declaration in the update.
alr
so this
Yes. Now record a video like before.
alr 1 min, i have to throw some stuff away il be back
Can you lend me the code? It helps me a lot for other things? 
Don't take code from strangers. They might kidnap you and sell your kidneys.
what other way should i do this?
using UnityEngine;
public class Movement : MonoBehaviour
{
private Rigidbody rb;
[SerializeField]
private float speed;
private Vector3 direction;
private Animator anim;
void Start()
{
rb = GetComponent<Rigidbody>();
anim = GetComponent<Animator>();
}
void OnMove(InputValue value)
{
direction = value.Get<Vector3>();
}
void Update()
{
Motion();
if(rb.velocity.x > 0)
{
anim.SetBool("Walk", true);
}
else if(rb.velocity.x == 0)
{
anim.SetBool("Walk", false);
}
}
void Motion()
{
rb.velocity = direction * speed * Time.deltaTime;
}
}
can anyone tell why my player is going homelander mode and just flying without me pressing anything value of speed is 1000
From this video your input is pressed all the way until the end of the video.
so the game thinks im clicking/ pushing something
It thinks you're holding the movement keys
how would i fix that?
removing the animator fixed the issue it happens when i use the avatar of the player in animator if i remove it from there it works
Do you not actually hold them all the time?
no im not touching my keyboard
At all?
I still don't understand how this code works. How can I visualize this? ```cs
Vector2 direction = new Vector2(mousePos.x - playerPos.position.x, mousePos.y - playerPos.transform.position.y);
after i hit play no
Take a screenshot of your project - input settings with the axes in question visible.
Yes. Expand Horizontal and Vertical. Also, why do you have 2 of each??
idk, i have never touched these settings
1 sec letme move my mouse out of the ss
And the other one's?
its just so that you can see the setting that was coverd in horizontal
You have 2 Horizontal and Vertical. Take a screenshot of the other ones too
Remove these
ok
Or even just reset the whole input manager.
it was there when i reset the input manager
Click the 3 dots at the top right and select reset or clear.
Okay. Then maybe it's not related. Try removing them manually or changing the name.
Also, do you have a joystick connected?
i just deleted them
no
Does that fix the issue?
I'm having an issue with the player skipping frames when moving. I know its because its rotation, how can I solve this? ```cs
// Inside the Update Method
// This is the mouseCusor Code....
Vector2 direction = new Vector2(mouseCursorPosition.x - playerPosition.position.x, mouseCursorPosition.y - playerPosition.transform.position.y);
playerPosition.transform.up = direction;
// This is the Movement Code....
if (moveVector != Vector2.zero) {
rb.MovePosition(rb.position + moveVector.normalized * moveSpeed * multiplier * Time.fixedDeltaTime);
}
Okay. Then you probably have something recognized as a joystick connected.
And it provides input.
A USB stick..?🤔
yea, i unplugged it and it worked
Like a memory USB?
yea
Lol okay
idk how it works but idc it worked
Is there a way to get the magnitude of vectors?
!docs
hey so im trying to use my animation triggers but whenever i do set them off my project freezes, cant find a way where it wont do this
📃 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.
There's nothing there that should cause the editor to freeze
Do you mean that the editor freezes and you have to force quit it?
no just that the game preview freezes, sorry about the poor wording choice
i thought this would work for animation control but yeah it just always freezes, been lost only problem ive had, the triggers work when i set them with the editor so i dont think its the animations causing the freezing, im pretty sure theyre running over and over but i thought this wouldn't cause that, unsure what to do
Do the animations play at all?
not sure since it just freezes
lemme check if hte triggers even activate though
ummm i got my editor stuck fullscreen on one editor window, know how to fix this?, cant check the triggers cause of it
i did before but i cannot find it again forgot how lol
Double click the tab where it says the name of the tab and the icon
thank you so much
yeah it jsut makes the game freeze, the triggers dont even get a chance to run
the idle state bar is just stuck
Why is my INT not default assigned to 0
int point;
if (point == 0)
{
// CODE HERE
}
Use of unassigned local variable 'point'
the int should by default be 0
This is stack variable
whats that?
It doesnt have default value
Memory in stack
oh ok
or theyre ref types like lists
You don't have to initialize ref types if they're serialized in unity, though
Then they'd just be null.
guys why ;w;
for some reason when i use Kinetic rigidbody, it doesnt detect collision, but dynamic does?
i dont want dynamic cuz the bullets just send the enemies flying
umm im falling through the floor and sticking to the otherside of the floor... and the vs code not showing any error also there are no errors showing on unity any one have a clue to this issue?
i had a programming exam and my teacher said that a would equal to b is this true?
I have a Vector3 that represent movement of a player without considering direction.
How do I manipulate the vector to make the value facing on transform.forward?
I usually multiply the vector to transform.forward, and transform.right then sum them up. I wonder if there are more elegant solution.
Vector3 velocity = someVelocity();
Vector3 forwardMovement = velocity*transform.forward;
Vector3 sideMovement = velocity*transform.right;
Vector3 newVelocity = forwardMovement+sideMovement;
is this related to Unity?
yes
i will try
i did but it gives me an error
did you read the error?
cannot convert int to bool i know
you must use == in order to compare two values
in the answers i typed "The compiler would have gave you an error because you cant assign values inside the parameters in a "if" statement. Variabel a wouldnt have touched and would have remained at 1.
wanted him to guess it himself, but ok
This is exactly what i typed
lmao sorry bro 😔 ✊
kinda good asnwer
i know right
better answer would be
i got wrong
that the code wouldn't compile
yeah its translated so its bad english
if it was
a = b;
if (a==b)
{
//code
}
then it would be true, and a will be 2
but you cannot do
if(a=b)
yes i do know that but i got a wrong answer how do i convince my teacher to give me a point for that
Actually you can make assignments in the condition. It's legal. At least under certain circumstances.
not in his case
tell your teacher to try compile that code
Yeah and i still got a wrong answer so i dont know
he said he put an error there on purpose
but that a wouldnt equal 1
it will be equal to 1
because the code wont even compile
and wont run
so it wont change to anything
infact a wont even exist
because... the program didin't run and compile
yeah xd
a wont ever be declared
yeah thats the thing so im not sure why he said a would equal to b
what is the correct answer your teacher said?
a = b
ill tell him this thank you
Are you sure the question was not about bools?
im 100% sure
do you have the question?
maybe you misunderstood it
but you said "the teacher put this error on purpose"?
why would he do that?
ig to test us
so you spotted the error
i didnt misunderstood it the whole class got the same answer
and he knows that this code is wrong and wont compile
yes
unity has no dll in project file?
i need the assembly definition of default assembly
i believe the default one isn't in the project files
i made a tilemap for the background in my game, it had the grass tiles stone and so on. i was wondering is it possible to make another tile map to add rocks and stumps while still showing the other background behind it. as when i tried it looked liek this
if(a=b) is actually legit syntax in c++ to check assignment
c# it's a compiler error
the problem is i need to modify a script inside a plugin, that plugin has its own assembly/library , so all the scripts including that one is enclosed inside the library
from that script, i cant reference all my other managers because theyre all in default assembly, they dont have one
but, you cannot pull that one out from the plugin, so many other scripts are depending on that script
its sad scripts that dont have assembly can just reference other one by doing "using xxx;"
but theres no "using default;"
could probably just use a background image instead of another tilemap and set the sorting group so it renders behind it
the exam was related to Unity
atleast from what i understand
and it's not legal way to check assignement, even in c++
i was hoping to use a tile map for both as it woudl make it much easier for me to edit as i coudl just add decorations ontop using the tile thign instead of having to place images is there really no way of makign teh rocks have a transparent background around it to show teh bottom layer?
its a common mistake
yeah, I actually remember seeing a question like that going from java to c++ because it's also a compiler error in java haha
In C++, the expression if(a=b) is a valid assignment statement
C++ would compile it though
yes
and it will always evaluate to true
if a=2, and b=4
if(a=b) will return true in c++
because this is just a normal assignment
it's essentially checking if the assignment operation was successful, not if the numbers are matching
ok so im trying to change the scene in my game after a ceirtain time limit, i got it set to 30 seconds rn so i can test it, but for some reason when it loads the next scene it doesnt load anything like i need it to load, i cant move the player and no ui elements update
Is it related to the delay? Sounds like something else.
no it doesnt seem to be that
i could try something
but it wouldnt really fix the issue
rn the way i got it set up you gotta go through a character select screen in order to enter the level
There isn't enough information.
theres not alot of info i can give, i got no idea whats going on, all ik is that the way i got my game set up you gotta go through a character select screen in order to play the game but if i boot up the game from the game scene itself without going through the character select screen then the issue im having occurs, where i cant move the player and the UI doesnt update to show the current stats
Well, this is a coding channel so we're assuming you'd have some kind of code to be viewed.
if (stopwatchTime >= timeLimit)
{
SceneManager.LoadScene("Next Level");
}
this is the code i got rn that changes the current scene
ive tried difrent methods to load the next level but none work
Looks valid. Your issue is likely elsewhere.
if i boot up the game from the game scene itself without going through the character select screen
Meaning, you've got some dependency with the character selection screen. Maybe persistent data that's only generated in the character selection screen.
What loads in the character selection screen that's absolutely necessary?
theres nothing that gets added in the character select screen, it just has the buttons that send you to the next scene with all the needed dependencies to controll the character or obtain items
So something happens in that scene. That something is probably what's missing from your expected next scene if the prior isn't loaded first.
the only thing that happens is that the buttons are what allows the player to move
but if i do the same for the other levels then the player would just reset to the base stats
are you sure that this code doesnt execute several times?
causing to load the same scene every frame might cause some issues
You'd need to find some workaround. Maybe decouple the functionality from that particular scene and have it setup in an intermediary scene between where all other scenes would load this necessary scene as well prior to loading the non-working scene.
might need some kind of secure on that, like a bool isLoaded
nope
Likely it's just a timer delay before the scene is completely wiped out.
Sounds like the unwanted behavior is that skipping a particular scene would have another not work properly
how did you make sure of that?
Probably something along the lines of...
- Title -> Character Selection -> Play (works)
- Title -> Play (don't work - missing persistent data/configurations from Character Selection)
- Play (don't work- missing persistent data/configurations from Character Selection)
etc
i tested it earlier when the issue began showing up
put debug logs in there
Where the solution would be to decouple the dependent data from Character Selection and have an intermediary
- Title -> Character Selection -> Setup -> Play
- Title -> Setup -> Play
- Setup -> Play
Where all of the above would Play after loading the setups.
it just has the buttons that send you to the next scene with all the needed dependencies to controll the character or obtain items
Is that what's missing if you don't load the character selection screen first?
yes thats what missing
but if i just load it like i do there it resets the character back to 0
Sounds like it 
the issue im having occurs, where i cant move the player and the UI doesnt update to show the current stats
Hi, I'm trying to use the c# tripple quoted strings ( so I can use newlines in the string literal ) , like string str = """ .... """;
It just isn't working though, Visual Studio doesn't recognise it as a multiline string, and neither does Unity as the console thinks I need newlines etc..
Is this kind of """ string supported in unity c# ?
You have your terminology correct, it's a string literal and the first C# string literal in google gives you the answer 
Thanks for the link. That's not for the """ string though, that's the one that begins with @ by thelooks of it.
The """ string allows you to have newlines also. But I'm wondering if it is a later version of c# than Unity suppots maybe?
Hmm, then I don't understand the difference between 1 string with newlines and @ or $ in it, and your version with newlines. Never used that style outside of Python.
String literals with triple quotes is a C# 11 feature, Unity uses C# 9
Aha brill, thanks, ok I can stop tying that now 🙂
Actually, it makes me do things properly anyway, I was trying to just use a JSON string I was pasting in, but I'll do it properly with JSON Serialization instead now.
I may well be wrong about the details, but I think
@"greger "rgrege " // " /'"; Can have characters you'd otherwise need to esscape
and
"""
This sting can have characters you'd normally
have to ecape /|";//| etc..
but can also have newlines too
""";
@-strings can also have newlines but I'm not sure if that's also an addition to later versions
This seems to work just fine for me
no
Raw string literals are C# 11
Unity is C# ~9
raw string literals trim the newlines on subsequent lines so you don't have to remove the indent completely
comparing the pair
Thanks, that explains the difference then.
waaa, strange day today, now I just pressed a weird key combination in Visual Studio Community and all my code has gone a funny colour.
Has anyone seen this before? I'm not sure what I pressed or what it means. It is just this one cs file, and I've quite Visual Studio and reopned it and this file still has this weird colouring?
I must have turned on some mode, but I've never seen it before.
For some reasons OnCollisionEnter() is not working
I gave a debug log but doesn't appear when I collide with something
here's the code: https://paste.ofcode.org/6j4q5weQc6rHxdxp9iv9CK
Put the log outside the if block
if it still doesn't show up then go through https://unity.huh.how/physics-messages
hi, is anybody know how to debug / attach android from visual studio code in macos ?
did you try google?
yes, i cant find any
I can debug Unity Editor, but not the android. i cant find anything on google
you dont attach VS to your device you attach it in Unity in the build settings
How could you do a dash with the character controller? Cus you can't just add an impulse force like a rigidbody
The CC requires you manage your own velocity. Add a dash velocity to your movement that slows down to zero over a small amount of time.
Yep
I was thinking of just changing move velocity
Thanks thats a lot easier
Would I use a coroutine for making the dash velocity go to zero?
Sure you can override the movement instead. Up to you really.
Lots of people would use coroutines for that, yeah. I personally would not. Again, up to you in the end.
Out of curiosity how would you program a thing going to zero?
Idk what the word is
Update
I don't understand, usually we attach visual studio to android process. With script debugging checked on build setting.
I dont see any config for attach to android proccess
Do you not have 'Run Device' ?
Sorry I'm not a Mac user, this is Windows but I would expect it to be the same
I was able to run the app Ok in android,
what i need is debug the app, and setup breakpoint etc
Ah, then I suspect you would need Android Studio for that
https://pastebin.com/AP0H4P2F why doesnt my player move in the direction its looking in
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
the direction comes from OnMove -> whatever you pass as InputValue determines your direction, so maybe thats where the problem lies, not the Movement class because that seems okay (even though i would call Motion() in a FixedUpdate() and not a normal Update())..
any fix u might wanna suggest?
so roation works with the OnMove direction
if the direction your player is going to is wrong, then that's because value.Get<Vector3>(); does not give you what you expect
so should i use somthing like vector3.forward
(also i would not set velocity of a rigiybody directly, but rather use things like AddForce but thats another story)
Why doesn't it look in the direction it's moving?cs if(rb.velocity.sqrMagnitude > 0) transform.forward = rb.velocity.normalized;
would .velocity be a problem in the long run?
if you want to go forward i would use transform.forward as direction
let me try this
setting it directly can interfere with other things, it doesnt have to though 🙂
You've already got this line, so you could probably just insert it in here as well
nope isnt working
no wait
my bad
let me try one thing
naw
this looks so bugged
maybe cuz i m chaning the transform and rb.velocity at the same time
https://pastebin.com/mNgwEnNy tried something like this
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
still isnt working
transform.rotation = orientation.rotation;
how will this help?
You need to remove that line from your code
And your line 29 isn't corret
i mean it worked
like i showed no error
but still doesnt move in the direction i want
Just set the forward direction to the velocity vector...
i did that as well it bug proly cuz there r 2 motions at the same time 1 is transfom.forward and one is velocity
what?
What did you not understand?
you want me to use this right?
what direction is moving
the direction the camera is looking in
I want you to set the forward direction to the velocity vector if it's magnitude wasn't zero. I want you to remove the rotation assignment at the end of the function.
okk let me try
and what direction do you want to move
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
like this?
Likely he's moving relative to his velocity vector.
The only concern would be if jumping is implemented, he'd not want to evaluate the y component with it as well.
https://pastebin.com/zTPMBA0L this is my cam scirpt
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
still isnt working
value.Get<Vector3>(); i have never seen this syntax in my life
Define not working. (you'd want to tell folks what is happening instead)
its used to get the value from the new input system
New Input system
okay i see
it keeps moving in the forward direction and even tho the camera is looking somewhere else
To be specific, the Polling Actions section of https://docs.unity3d.com/Packages/com.unity.inputsystem@1.7/manual/Actions.html
I thought you were wanting to look in the direction you're moving...
i wanted to move in the direction im looking
Mhm
If you're wanting to move in the direction your camera is pointed towards, use https://docs.unity3d.com/ScriptReference/Transform.InverseTransformDirection.html
let me try
Relative to your direction field
Dalphat have you used unity events much
Make sure to revert to your original setup - remove the changes done.
When I add Rigidbody to Cube (5) it falls under the ground. How do I make it stay?
Usually, you'd just ask the actual question and people would give suggestions.
Does the floor have a collider?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
the player is rotating
but the movement is still the same
Yeah i did in the other channel 
I can walk on the floor and when there is no Rigidbody exactly on childs of Bottle nothing falls down. Bottle also has a Rigidbody, so I don't think it has to do anything with the floor
Oh sorry i read the question wrong
void OnMove(InputValue value)
{
direction = transform.InverseTransformDirection(value.Get<Vector3>());
}```
My bad
Assuming this script is on the camera or in the same orientation as the camera
Why do you need rigidbody on the bottle?
Bottle flip challenge 🔥 🔥 🔥 🔥 🔥 🔥 🔥 🔥 🔥 🔥 🔥 🔥 🔥
Why not just have a singular rigidbody?
sorry for jumping in middle of the convo, but by doing this, is the relative vector now the local forward of the transform, meaning transform.forward?
Vector3 relative;
relative = transform.InverseTransformDirection(Vector3.forward);
by doing this it only makes it move in 1st direction i m looking at i have to stop and move again to change the direction again
Then it would be a bobber, which I don't want
bobber?
Should be, yes.
it should have some challenge on flopping the bottle, but not like when the flop is 100% accurate that the bottle will go down at the good rotation
so basically it just converts world space direction into local space?
a bobber of a fishing rod. an item that is used for fishing
Transforms a direction from world space to local space.
id reckon just add one rigidbody to the main object and have a few box colliders attached to the bottle
^?
You can have multiple box colliders
Box colliders are attached to the children of the bottle
I don't recall how input is handled but if up direction is y then it'll not be correct for 3d.
yes up is y
You may want to use the other overload
public Vector3 InverseTransformDirection(float x, float y, float z);
Setting the x equal to your x direction and z equal to your y direction
They don’t need to be
so like InverseTransformDirection(dir.x,dir.y,dir.z);?
x equal to your x direction and z equal to your y direction
direction = Transform.InverseTransformDirection(value.Get<Vector3>().x,value.Get<Vector3>().z,value.Get<Vector3>().y); ?
I don't want to advise you to write code you aren't sure of, so I'll probably stop after this..cs var input = value.Get<Vector3>(); direction = transform.InverseTransformDirection(input.x, 0f, input.y);Edited
see it works but
If I make box colliders on a bottle then it would be sick
cuz once i choose a direction i have to stop and look into another one to go in that direaction it does not chage if i m in motion
proly cuz its in OnMove
i just want a way to put it in update
Likely so
Maybe just apply the changes to the result before assigning to velocity in Motion
i m trying to think of a logic to do that
So what I want to do is to make something like a hinge joint with those objects or something
then make a hinge joint
it should be of the same pattern but instead using the result @sonic dome cs var result = ...; rb.velocity = transform.InverseTransformDirection(result.x, 0f, result.y);
https://pastebin.com/jfqh7E5i new approach i want it to move in the direction of the the player rotation
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
What is the diffrent between 3d and 3d URP
what should i use in result?
direction vector?
he wont make the code for you
everytime
he showed you all the functions and approaches you can take
think of it yourself, then ask a specific question
and i believe this was already answered
var result = direction;
rb.velocity = transform.InverseTransformDirection(result.x, 0f, result.y);
but now the
player wont move forward
do you understand how InverseTransformDirection works
or you just blindly copy&pasted it
from the code he sent
it changes it to local space
right?
you ask me?
no thats what i think it does
well wtv i m trying once it works ill be able to understand it better
you will understand it even better if you do it yourself instead of someone else making it for you
i am not asking him to code anything for me
https://pastebin.com/T9BkC8MT can anyone tell why the force keeps stacking and my player reaches the speed of light?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
📃 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.
because you are calling Motion every frame
so whats the proper way to do it?
i should use impulse mode?
what are you trying to achieve
well tbh this new input system wasnt working out for me so i just went back to basics and now everything works
the input has no relelation to this, you changed how you call the movement
velocity is a fixed value instead of AddForce, which...keeps adding force duh
That's not the problem
ya but there were some complications like OnMove would only take the 1st input and not change my direction mid motion
thats not related
https://gdl.space/iheyehopuk.cs why is my player moving for a while even tho its velocity now?
I'm trying something, how do I make an object change local position to another local position?
move for a while? wdym
ya ik i just said that cuz i dont have the prevous issue cuz i chaged the moment type
its like i m slipping on ice
also u should not use GetInput in fixed update
why?
because it could miss the initial keydown and only "catchup" on the next physics loop
not noticeable with GetKey as much as GetKeyDown but you still have slight delays
so i should do all that in update and then do the motion in fixed update?
okk
what bout this?
huh as for slipping, it shouldnt with velocity
are you sure the script was applied from old?
thats what is confusing
yes
also remove time.deltaTime
for .velocity
void Update()
{
movement.x = Input.GetAxis("Horizontal");
movement.y = Input.GetAxis("Vertical");
LookRot();
}
Vector2 movement;
void FixedUpdate()
{
if (movement != Vector2.zero)
{
rb.velocity = movement.y * speed * transform.forward;
}
}```
srry if im being annoying but is anyone able to help me in #archived-code-general
ooooo yeaaaaa i forgot that was something ,one question tho if i slow down the time scale
will it slow the velocity as well?
timescale affect physics object yes
tysm
btw keep in mind .velocity will override any external forces, including gravity
so it "Falls slow"
or if at all
yes thats something which scares me
One option is to split the current velocity into two parts
- aligned with gravity
- not aligned with gravity
you then only modify the second part
hows that done?
using Vector3.Project and Vector3.ProjectOnPlane
Vector3.Project tells you how much of the first vector is aligned with the second vector
Vector3 gravityVelocity = Vector3.Project(rb.velocity, Vector3.down);
so its like Dot product basically?
well, actually, what I just said is what the dot product is, whoops
I should say that Project gives you the part that's aligned
Vector3.ProjectOnPlane does the opposite. It gives you the part that's not aligned
Vector3 movementVelocity = Vector3.ProjectOnPlane(rb.velocity, Vector3.down);
hmm i think i don't get it