#💻┃code-beginner
1 messages · Page 256 of 1
ah yeah good point
the script is within the player
so they arent the same
lol
cant i just use
camera.main
than have a variable for that
Yeahhh still nothing. I got all the extensions installed to my VSC so idk why its acting like it doesn't exist
https://docs.unity3d.com/ScriptReference/Random.html
Name resolution ambiguity
Because the classes share the name Random, it can be easy to get a CS0104 "ambiguous reference" compiler error if the System and UnityEngine namespaces are both brought in via using. To disambiguate, either use an alias using Random = UnityEngine.Random;, fully-qualify the typename e.g. UnityEngine.Random.InitState(123);, or eliminate the using System and fully-qualify or alias types from that namespace instead.
Read the message. It's not saying it doesn't exist. Quite the opposite, you've imported two namespaces that both have a class Random
You have to pick one
although in this case it's a collision between UnityEngine.Random and Unity.Mathematics.Random rather than System.Random
oooh I see. thx
im confused the hell u mean
do what praetor told you
where
i did
Show the updated code
just do what praetor said.
you are literally telling me that i can remove multiplications and MAGICALLY use something else
so i DONT need to do that?
since you clearly don't understand it, then don't fucking do it
you wont tell me what you are on about
Show the updated code
then dont tell me what i should do if you then say i dont need to
What's going on in here?
It was a suggestion
You ignored them, and didn't read the next message
I dunno I'm trying to find out but they won't send code
Hey all! I have this first person game and I am trying to do the door mechanic. What method or ways should I look into to be able to interact with the door only when I'm looking at it?
A raycast from the camera's your best bet, or a box/sphere cast if you want to be looking near it but not directly at it
Vector3 movementForce = ((Input.GetAxisRaw("Vertical") * Vector3.forward) + (Input.GetAxisRaw("Horizontal") * Vector3.right)).normalized * movementSpeed;
movementForce = cameraTransform.TransformDirection(movementForce);
_rigidBody.AddForce(movementForce, ForceMode.Force);
I thought you were talking to another person
Thanks!
if only there was [extra context](#💻┃code-beginner message) that was added that made it pretty clear all you needed to do was what praetor told you to do which is also what i said you should be following after the fact
this message told me absolutely nothing
Incorrect
its just them saying that i should do what they "suggested"
Okay, so, you've got movementForce as a vector in X and Z, then you apply the camera's transform to that, which turns it into camera's right and forward, then you add that force to _rigidbody. What is happening that you aren't expecting to happen?
thats literally all it told me
Then you misread it. Because that is not what it says at all
Those blue words are a link
Hello, I have a question about camera movement, is there a general way to avoid moving the whole body towards where the camera is looking at?
i know?
it was useless to look at it
because i already seen it
I have a character that faceplants on the ground when i look at the ground
what conversion
they are probably now interpreting the message i linked to as something they should do, rather than as context for why they don't need to shouldn't remove the TransformDirection call
So, you've got movement relative to the camera, but since the camera's at an angle, you're moving into the floor, right?
what
how many times i read that i dont see anything saying i shouldnt do that
uh it's more like the character moves along with the camera
😭
and i want it to not move when im looking up or down, but it can rotate its body if i move left and right with the cam
https://docs.unity3d.com/ScriptReference/Vector3.ProjectOnPlane.html
You take the camera-space vector and project it on the plane with the normal Vector3.up. So instead of using your camera vector, use Vector3.ProjectOnPlane(thatVector, Vector3.up)
@hexed fractal if I had to guess, I think that might be your problem as well, but I don't know what the exact issue is
or maybe its not related to code but to cam hierarchy idk
now i gotta rotate the player smoothly towards the direction im moving
its working so
Ah, alright then
i dont see any difference to transform.forward and Vector3 forward
to the movement
i guess its just "correct"
They're the same if and only if this object is pointing at exactly negative z
if the object rotates at all, they become different values
when i walked in a diagonal with transform.forward it was jittery. the player
In this case, you don't want the rotation of this object to affect your movement, just the rotation of the camera, so you'd use Vector3.forward and then transform it in the camera's direction
Vector3.forward is literally (0,0,1)
transform.forward is whatever direction the object is facing
Vector3.forward made it smooth and move straight
Also note that cam.TransformDirection(Vector3.forward) is the same as cam.forward
Yeah, it probably rotated slightly when it hit the wall and caused the calculation to be slightly different, then when you transformed it to the camera, it became off in the opposite direction, and basically pingponged back and forth
Y i p p e e
if it makes you feel better I don't really understand why people seems to be so upset with you...
anyways, reading this makes a lot of sense. there isn't anything inherently more correct about using transform.forward vs Vector3.forward but they don't work the same, and that's important to be aware of. for a VR game transform might make more sense honestly, but for a 'normal' third person game, Vector3 is more inline with 'standard' movement.
m k
Im assuming SmoothDamp for the player rotating to its moving direction?
lol
I give up... I tried fixing and it still adds to that list.
Logic is next:
My basic attack has
[SerializeField]
protected List<StatusEffectList> applyStatusEffects = new();
public List<StatusEffectList> ApplyStatusEffects { get => applyStatusEffects; protected set => applyStatusEffects = value; }
Basic attack itself does not apply any, but when we have certain passive skills, they work only if the hero is using basic attack.
So for that I take that list from the struct, and add needed status effect in there. It was supposed to add status effect to some instance, and not to the source. This is how it appears there.
And now I have no idea how to prevent it modifying the source.
again, List is a reference type. when you make a copy of a struct that has a reference type as one of its fields it copies the reference to that object. so your struct has been copied, but it's still the same list
yeah, that's what gets that trouble. How do I work around that?
create a new list
and if that list contains reference types then you'd want to create new instances of those too
Easiest way to copy a list is new List<___>(oldList)
dammit... will try, while I was trying to fix that issue I guess I broke good working code now 😄
After i actually get good at programming
in c#
id want to make classes for enemies i guess
ok thank you
I have some questions.
what are some must have free resources or plugins to use with unity that could help?
do i start with 2d or 3d which is more for beginners?
How do i get an idea if im struggle with ideas or overthinking ideas?
that is it for now, i know there silly but im debating if gamedev is even for me or not.
var PassiveSkills = GetComponent<Abilities>().PassiveSkills;
List<StatusEffectList> NewList = new (actionSettings.applyStatusEffects);
for (int i = 0; i < PassiveSkills.Count; i++)
{
if (PassiveSkills[i].trigger == Trigger.DEAL_MELEE_DAMAGE)
{
NewList = PassiveSkills[i].ApplyEffect(NewList);
}
}
and ApplyEffect(NewList); =
public virtual List<StatusEffectList> ApplyEffect(List<StatusEffectList> effects)
{
List<StatusEffectList> NewEffects = new(effects);
if (ApplyStatusEffects.Count > 0)
{
foreach (StatusEffectList status in ApplyStatusEffects)
{
NewEffects.Add(status);
}
}
Debug.Log("ActionSettings updated with new information");
return NewEffects;
}
dammn... going to test that now...
LESSSSGGGOOO! that works, thank you!
Hello guys. I'm having a problem with drawing a line in Unity's OnDrawGizmos() function. The line, intended for ground checking from the player's position down, is misaligned and appears next to the player instead of through it. Any advice on troubleshooting and resolving this would be helpful, thanks a lot!
Any recommendation on how to "split" big character controller to multiple sub-system scripts?
I want to know what is the correct/popular way to do this, thanks in advance to all the helpers! 🙂
First step is to think about what the script is doing now
How big is it?
Do you have animation included? Things like that?
What's the goal exactly? The best reason to split it is if you want to reuse some part of it elsewhere without the rest of it
Share the code
for example I want to create an extensible Combat system that will be used with both character and ai enemies
Combat would surely not be part of movement, for example. So there is AT LEAST two scripts
Enemy AI would probably have a brain
That controls various components
So I just attach both scripts on the character?
it doesn't override stuff by any chance (like the update function) right?
Well, you would attach things that need to be used. What do you mean override? Like inheritance? It's up to you
sorry for the basic question, new to unity lol
It's all good!
You could probably remove the if statement as having zero elements would end the foreach statement immediately.
Woudl smth. like this work?
private IEnumerator ResetBool(bool boolToReset, float cd)
{
yield return new WaitForSeconds(cd);
boolToReset = true;
}
I am trying to make a function that can reset any bool that is passed in
[SerializeField] private GameObject pawn;
void Start()
{
StartCoroutine(SpawnPawnRepeatedly());
}
IEnumerator SpawnPawnRepeatedly()
{
// Loop indefinitely
while (true)
{
// Wait for 3 seconds
yield return new WaitForSeconds(3);
// Instantiate the pawn at the same position as the current GameObject
Instantiate(pawn, transform.position, Quaternion.identity);
}
}
Why the pawn spawns in the center instead of where my empty object is?
the script is attached to the empty game object
there is an animation on the pawn but only changes rotation of it
boolToReset will not reflect on the argument being passed in
is there an easy way to do that or do I have to create sperate functions?
You could use ref I think?
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/method-parameters#ref-parameter-modifier
👆, but you can't use it with an iterator method (yield).
The variable would need to be visible to the calling function if it's a primitive.
Yeah, that's what I was considering. I've never used ref with a coroutine
wasn't sure if it would work and it looks like it can't
thank you, you are right. Done )
alternatively you could make your coroutine accept an Action parameter then just invoke that action after the delay
that would allow you to use it for more than just resetting bools
and you would just pass in a delegate that changes the value of the bool whenever you call it
Hi I am trying to make a 2d game where i can launch stuff and the further you go the more money you get and the player is a water melon. does anyone know what to do?
don't crosspost. but what specifically are you having trouble with?
if the answer is "all of it" then you should start with some beginner courses like the ones on the unity !learn site
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
The player is a watermelon? Well, it's going to take a whole lot of science to genetically modify a watermelon capable of holding a controller
would that be a good game do you think?
like would you play it
i would eat a watermelon
You don't want your players to break. Might lead to criminal charges.
public Animator amim;
public Rigidbody2D rb;
public float speed = 9;
public float jumpForce;
private float xInput;
private float yInput;
private int facingDir;
private bool facingRight;
private bool isGrounded;
[Header("Collison info")]
[SerializeField] private float groundCheckDistance;
[SerializeField] private LayerMask ground;
void Start()
{
rb = GetComponent<Rigidbody2D>();
amim = GetComponentInChildren<Animator>();
}
// Update is called once per frame
void Update()
{
xInput = Input.GetAxisRaw("Horizontal");
yInput = Input.GetAxisRaw("Vertical");
Move();
if (Input.GetKeyDown(KeyCode.Space))
{
if (VerifyCollision())
{
Jump();
}
}
AnimatorControllers();
AutomaticFlip();
//CollisionCheck();
}
public void Move()
{
rb.velocity = new Vector2(xInput * speed, rb.velocity.y);
}
public void Jump()
{
rb.velocity = new Vector2(rb.velocity.x, yInput * jumpForce);
}
public void AnimatorControllers()
{
bool move = rb.velocity.x != 0;
amim.SetBool("move", move);
}
public void Flip()
{
facingDir = facingDir * -1;
facingRight = !facingRight;
transform.Rotate(0, 180, 0);
}
public void AutomaticFlip()
{
if (rb.velocity.x > 0 && facingRight)
{
Flip();
}
else if (rb.velocity.x < 0 && !facingRight)
{
Flip();
}
}
private void OnDrawGizmos()
{
Gizmos.DrawLine(transform.position, new Vector3(transform.position.x, transform.position.y - groundCheckDistance));
}
public bool CollisionCheck()
{
isGrounded = Physics.Raycast(transform.position, Vector2.down, groundCheckDistance, ground);
return isGrounded;
}
public bool VerifyCollision()
{
if (CollisionCheck())
{
return true;
}
else
{
return false;
}
}
}
!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.
why does this happen
You have code that changes the value
show the Player class
press0, press1, and press2 are ints. I'm looking for a more optimized way to do this, since this would require 10 if's for every digit pressed:
if (press0.IsPressed())
{
NumPadController.Attack(0);
}
else if (press1.IsPressed())
{
NumPadController.Attack(1);
}
else if (press2.IsPressed())
{
NumPadController.Attack(2);
}
I'm assuming I need to do a for loop, but I haven't figured out how to get the proper syntax. How to I increment the number on the int's name and the number in the NumPadController.Attack() input parameter?
int doesn't have an IsPressed() method
so it's unclear what you mean by them being ints
you're creating a new instance right there in Start
The very first thing you do is create a new Athletics object which completely overwrites anything you had there before
So yes, you do have code setting it to 0
press0, press1, and press 2 are bindings for the InputController class.
So they're actually InputAction you mean, not int?
put all the InputActions in an array.
for (int i = 0; i < myActions.Length; i++) {
if (myActions.IsPressed()) NumpadController.Attack(i);
}```
Sorry, yes. They are InputActions. I was mistaking int because I was feeding an int to the next method.
Hello guys. I'm having a problem with drawing a line in Unity's OnDrawGizmos() function. The line, intended for ground checking from the player's position down, is misaligned and appears next to the player instead of through it. Any advice on troubleshooting and resolving this would be helpful, thanks a lot! https://paste.ofcode.org/XkpWZFPZCec3yfhi9mRqNV
Can you show a screenshot of the object selected with the gizmo visible
Hello i have an object transform rotation (0,90,-90) in my code i need to extract it in this form so i did transform.rotation.euleurangle but i return me (0, 90 ,270) i cant find a function who works properly help
Those are the same values
yea
this sounds like an XY problem
https://xyproblem.info
what is the actual purpose of getting the rotation as signed angles
So, whatever you're doing shouldn't care what form the rotation is in, those are the exact same rotation so it should work
thanks next question im working on UV mapping an object in unity to access it in game like im flattening a cube when i click on a face of his patron it access the cube is there any way to do it easly or i need to sort every face manually?
just out of curiosity... even is I would make that list Private, it would still be modified, right?
public InputAction[] press = new InputAction[9];
// Start is called before the first frame update
void Start()
{
for (int i = 0; i < press.Length; i++)
{
press[i].Enable();
Debug.Log(press[i] + "has been enabled.");
}
}
I'm not sure press 0-9 is being enabled since the log is showing press[i] as blank in the Debug.Log section. I've also tried press[i].ToString().
did you actually assign your InputActions in the array?
based on this code it's just going to give you blank serialized input actions that you'd have to set up in the inspector
especially since you made it public it's being serialized
this?
No, the object, in the scene, with your drawn gizmo available
make sure the object is selected so it also draws the transform gizmo
unity isn't working fro me
Can you elaborate?
No, I ended up losing all my bindings when doing this unfortunately. I'm trying to figure out how to assign them as an InputAction.
how did you get the references before?
Use the same approach, just put them in the array
it says something about unity version control
Could you be a little more vague please?
i m lost
I did it like this.
public InputAction press0;
public InputAction press1;
public InputAction press2;
public InputAction press3;
public InputAction press4;
public InputAction press5;
public InputAction press6;
public InputAction press7;
public InputAction press8;
public InputAction press9;
oof - why
yeah definitely use an array instead of this
So you just need to do that again, but in the array
yes, private does not prevent the reference from being the same when you copy the struct
send a screenshot of the object, selected, with the gizmos available
And what is the issue?
I can't create a projekt
Deselect the cloud option or select an organization
Just LOOK at the stuff there
Not sure what the syntax is for adding those InputActions to the array.
I tried these:
public InputAction[] press = new InputAction[press0, press1, press2, ...];
public InputAction[] press = new InputAction[InputAction press0, InputAction press1, InputAction press2, ...];
nah
Add them in the inspector
Just public InputAction[] pressActions; and set them up in the inspector @austere hedge
Just declare the array and then define them in the inspector
My gizmos appear only in the game window, in the scene window it does not appear
That is like, the opposite of how gizmos work
They only appear in the game window if you specifically enable them
they're always present in scene view
and what do I do if it does not appear in the scene window?
How can I prevent the player from, falling over edges?
Like having an invisible wall
As I add or remove elements from the InputAction array, it is changing the name from element to Input Action. Does it matter that it changes?
You can use raycasting to see if the ground drops too much
I also thought about this, but how can I implement that if there is an edge it cant move in this direction?
Nah
Well the raycast would tell you there is an edge, and you just disable movement in that direction
Then I guess just send a screenshot of the object in scene view with the transform gizmo visible and a separate screenshot in game view with your custom gizmo visible
Thank you PraetorBlue and digiholic, I have the InputAction array working properly. 
i can't find the device simulator link to instal it in package manager
I have this code which generates 5k particles as objects into my game, it gets the object viewer very cluttered. Is there a way I can make these and nest them under another object to keep the menu readable?
Give them a parent object
ayo! am i right in assuming ahead-of-time dictionaries are like ahead-of-time lists except they have attached values?
if so, i'm thinking of using a dictionary instead of a list to have a chance value (right column floats/integers) dictate object occurance (left column, with strings/objects)
is that what this sort of thing is used for?
Sometimes I feel like I need a cert in googling, thx for this
I, uh, I have no idea what this is
and I've been using Unity for like ten years
Is this a plugin or package?
it's some #763499475641172029 stuff
ignore the picture.
tldr: AoT lists and AoT dictionaries, are dictionaries just lists with the second value flavouring the first?
no
damn
I don't know what AoT means but a Dictionary is like a list but indead of the index being a numerical value counting up from 0, it's whatever you want it to be
Dictionaries are a collection of Key Value pairs. where a key (the first item) is used instead of an index to get the value (the second item)
keys are unique in a dictionary and you also cannot have a null key
wait so like, where a list is
thing1 = 0
thing2 = 1
thing3 = 2
a dictionary is
thing1 = (what ever number i pick)
thing2 = (what ever number i pick)
thing3 = (what ever number i pick)
?
Where a list is [thing1, thing2, thing3] a dictionary is {thing1: value1, thing2: value2, thing3: value3}
Which, to be clear, isn't your example above digi's. You just made three similarily named variables, which is not a list.
i can't find the device simulator link to instal it in package manager
this is a code channel
It's also still a experimental package (I believe), so you'll probably have to enable experimental packages in your manager.
oh! so i /can/ set something like rarity in those value fields?
'''{card1name: 25, card2name: 30, card3name: 70}
it has dawned on my that i don't know how to start code blocks in discord
Sure, you can look up a value by name. Think about an actual dictionary. You look up a word (key) and get a definition (value)
Is "starts pressing" different than "pressed down"?
no, those methods do the same thing. but one is used to query a specific key (Input.GetKeyDown) the other queries a button set up in your input manager settings (Input.GetButtonDown)
also for future reference, don't crop the method name out. i had to actually open the docs manually to see what that second one was
oh my bad
well if they are the same then why are their desciptions different
bc when i try to use the first method, i have to press the key multiple times for it to work
let me show u the full code
one sec
one lets the player setup their own buttons i think
let me guess, you're calling this in FixedUpdate?
lol yup there it is.

don't poll input in physics updates. input should be checked in Update
there's also a good chance that this could just a be a physics query instead of relying on trigger messages
well i want to return true only when the player is colliding with that object AND pressing the button
should i make a bool for the collision check and use it in update?
you could, or (again) this could just be a physics query like an OverlapBox or whatever. so you check for input, if the input is true then you perform the overlapbox, if that is true then you call the method
what is an overlapbox
then you won't be relying on trigger messages and can even get rid of the trigger collider
is my method valid
this ?
this?
Sure but show the transform gizmo, the thing that shows up when you select an object. The arrows that let you move something around
don t work to put the picture
a ok work
Send a picture of this object with the transform gizmos visible and set to "pivot"
okk
was set
So it looks like the line is doing exactly what it should be doing
is it me or does setting transform.up reset the entire rotation, I'm trying to set transform.up to the inverse of my gravity direction and rotate the player based on the movement direction and camera rotation. each seperately works but the moment I put them together it just dies
I made the line so that when it touches the ground it jumps and it doesn't jump
Hey. I wrote a script that teleports the player when the conditions are met. The teleportation works just fine, but I also want to reset player's camera position to the destination position which is the other side of the door. I tried to do the thing on the second script but the camera just flickers till I move my mouse.
https://hatebin.com/slucqzpmgk, https://hatebin.com/sbdquuyqsl.
Well, yes, it rotates the object such that it's up direction points in whatever value you set it to
destination is just a simple empty with a trigger box collider.
just run or stay but doesn t jumb and before to do the line
This is a different problem than the one you asked about
Show the code
First off, literally what is the point of this function
Just call CollisionCheck()
All this function does is call CollisionCheck. You should just do that
Second, what is ground and what layer is your actual ground object on
Also groundCheckDistance
not sure how to fix my problem then...
ground it s layer mask object i use to make Raycast and groundCheckDistance I can set how long the line that appears in the editor
What are they set to
i m lost again
device simulator doesn't work cause of this
Compiler error CS0121
I literally do not know how else to ask this
This isn't even complicated
I just want to know what those are set to
Is this package code? Make sure your packages are all up to date.
give me this damn link to dowload it i can't find it
device simulator
It's a package, you manage it from the package manager
where
float targetVelocityX = moveX * moveSpeed;
rb.AddForce(Vector2.right * targetVelocityX * acceleration, ForceMode2D.Force);
// Limit velocity
rb.velocity = new Vector2(
Mathf.Clamp(rb.velocity.x, -maxSpeed, maxSpeed),
rb.velocity.y
);
// Decelerate if no input
if (moveX == 0f)
{
float decelerationAmount = deceleration * Time.fixedDeltaTime;
rb.velocity = new Vector2(
Mathf.MoveTowards(rb.velocity.x, 0f, decelerationAmount),
rb.velocity.y
);
} guys is it a good way to move 2d character horizontaly? how can i make it smoother
its not here
i need the link
The link to what?
where in the package manager
this?
Im currently refactoring my code to not be a complete mess, Im trying to understand enumerator and how its used as I felt this would be a better solution than having a million bools for each state since none of them can be true at the same time.
How do I check if the enumerator is currently set to a specfiic one?
ie
public enum movementState{
Grappling,
Hookshoot,
Grounded,
Airborne
}
The obvious thought if(movementState == "Grappling") doesnt work so I clearly dont understnad enums
if (someMovementStateVariable == movementState.Grappling)
(Ill probably use a switch instead of if statements though)
Oh, do I need to have a second movement state variable to store it?
Do you have a first movementState variable?
the enumerator
Then what are you trying to check the value of
where is device simulator
It is. You've created a type named movementState and you can have a variable of that type, just like you can int or bool or GameObject
you need to change packages to all and then search for it
It's a variable that can only hold those specific values
oh wait so ive made a datatype?
Yes, that's what an enum is
Layer 'ground' is set to 'Ground' in Unity project. => [SerializeField] private LayerMask ground;
Yes, you can kind of think of it as a boolean with more options
no goddammit what layer is the object on
the one you're trying to check if you hit
show it
Just under the object name in the inspector it shows the layer
Look there for the ground object
well i wanna hit the Border
Okay, good, it's on the right layer. I'm wondering if the distance might be slightly too short. Increase the distance to 2.1 and see
Actually, now that I look at the code a bit closer, is the issue even that you're not getting the raycast to connect? Have you tried logging isGrounded after your raycast?
{
Debug.Log(rb.velocity.magnitude);
// Gradually reduce velocity to zero
float decelerationAmount = deceleration * Time.fixedDeltaTime;
rb.velocity = new Vector2(Mathf.MoveTowards(rb.velocity.x, 0f, decelerationAmount),rb.velocity.y);
}``` guys i think something is not right in my decelration skript the magnitude isnt go down to 0 it stay on like '1.322223E-08'
yep, never check a float for equality
Steven wdym?
this
if (moveX == 0f)
whats wrong i check if he stop move i want deaceleration that it wont immediatly stop
just do if its >= 0
moveX is the input.getaxisraw("horizontal")
skill
floats don't work like that, you can never guarantee an EXACT number
Because they never read the bot
1.322e-08 is very close to zero, but not zero. Your condition will fail
xd
but >= 0 if its >0 he is moving
then do <=
oh
geez
you sure its the problem cuz the debug.log() works
== is equality. expecting an exact value equal
float targetVelocityX = moveX * moveSpeed;
rb.AddForce(Vector2.right * targetVelocityX * acceleration, ForceMode2D.Force);
// Limit velocity
rb.velocity = new Vector2(Mathf.Clamp(rb.velocity.x, -maxSpeed, maxSpeed),rb.velocity.y);
// Decelerate if no input
if (moveX <= 0f)
{
Debug.Log(rb.velocity.magnitude);
// Gradually reduce velocity to zero
float decelerationAmount = deceleration * Time.fixedDeltaTime;
rb.velocity = new Vector2(Mathf.MoveTowards(rb.velocity.x, 0f, decelerationAmount),rb.velocity.y);
}
didnt fix ti
so just use greater and less thans
it still stay on wird numbers
!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.
<= 0 won't do anything as their value is still greater than 0. Something like < 0.001f should do the trick.
Or use Mathf.Approximately(num, 0)
o k a y?
what weird numbers
9.998757E-10
lol
xd
That is scientific notation
why do you name ur script Player
this number is so small it is effectively 0
it's just not equal to 0
That's roughly 0.0000000099875, but written so it takes up less space
And if im not moving it always call it btw i should also check if the magnitude isnt 0?
Yeah that's 0
machines have issues with stuff like that
No ,I don t do that .
set distance with 2.1 and it s the same
`` if (moveX <= 0f)
{
Debug.Log(rb.velocity.magnitude);
// Gradually reduce velocity to zero
float decelerationAmount = deceleration * Time.fixedDeltaTime;
rb.velocity = new Vector2(Mathf.MoveTowards(rb.velocity.x, 0f, decelerationAmount),rb.velocity.y);
}`` guys shouldnt it like start from 5 and go down to 0? it just start fro mthe small number
!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.
omg bro..
0.00001 is not less or equal to zero.
i didnt 111
Share the full code
lets hope he does it this time
{
float targetVelocityX = moveX * moveSpeed;
rb.AddForce(Vector2.right * targetVelocityX * acceleration, ForceMode2D.Force);
// Limit velocity
rb.velocity = new Vector2(Mathf.Clamp(rb.velocity.x, -maxSpeed, maxSpeed),rb.velocity.y);
// Decelerate if no input
if (moveX <= 0f)
{
Debug.Log(rb.velocity.magnitude);
// Gradually reduce velocity to zero
float decelerationAmount = deceleration * Time.fixedDeltaTime;
rb.velocity = new Vector2(Mathf.MoveTowards(rb.velocity.x, 0f, decelerationAmount),rb.velocity.y);
}
}```
dont mind first if statement
They didn't?
i did
They did format it, but not for C#
{
float targetVelocityX = moveX * moveSpeed;
rb.AddForce(Vector2.right * targetVelocityX * acceleration, ForceMode2D.Force);
// Limit velocity
rb.velocity = new Vector2(Mathf.Clamp(rb.velocity.x, -maxSpeed, maxSpeed),rb.velocity.y);
// Decelerate if no input
if (moveX <= 0f)
{
Debug.Log(rb.velocity.magnitude);
// Gradually reduce velocity to zero
float decelerationAmount = deceleration * Time.fixedDeltaTime;
rb.velocity = new Vector2(Mathf.MoveTowards(rb.velocity.x, 0f, decelerationAmount),rb.velocity.y);
}
}```
Are you on mobile?
It doesn't show on mobile
Doesn't matter much
It's fine without highlighting
does it look like mobile
what?
Ignore, let's just focus on the issue
I was just wondering. But yeah, it's not important at all
Formatting is important, highlighting is not
Try logging rb.velocity after your MoveTowards
its not mobile game
i can tell your english isnt that great
i dont see where u got a mobile game from ngl 😭
Woah
So wtf mobile
Ignore that please
You rb.velocity in the movetwoards?
back on topic of the question
someone kinda said to ignore
How about you don't say stuff like that?
Log the velocity after moveTowards
?? i was just observing
I mean, there are many people who are ESL on this server
it's a reasonable thing to ask sometimes
ESL? wtf
English as a Second Language
non native english speakers
To ask, not to declare in a mocking way
float decelerationAmount = deceleration * Time.fixedDeltaTime;
Vector2 newVelocity = new Vector2(Mathf.MoveTowards(rb.velocity.x, 0f, decelerationAmount),rb.velocity.y);
rb.velocity = newVelocity; like this?
Just log the value. Debug Log
i dont understand what ur on about
See if it's changing
Oh
Yeah you could have formulated in a way that's a little bit less abrasive
I didnt know words inflict pain
nor that thats harsh
¯_(ツ)_/¯
Drop this or go in a thread there's an actual issue to resolve
Can you just stop
mate
It still on wird numbers but it calls it every frame but i dont see like 5 goes down to 0 or this wired numbers
im kinda being talked to by people therefore im responding
float decelerationAmount = deceleration * Time.fixedDeltaTime;
rb.velocity = new Vector2(Mathf.MoveTowards(rb.velocity.x, 0f, decelerationAmount),rb.velocity.y);
Debug.Log(rb.velocity.magnitude);
Don't log the magnitude, log the velocity itself. See if the X value moves towards zero
the rb.velocity.x?
That'd be fine too, or just rb.velocity
Debug.Log(rb.velocity.x); its always 0 ill try wthout .x
Digiholic
it was like -6.3 went to -5.8 -5.3 -5.1 and than straight to 0
5 frames
Okay, and presuming it doesn't change ever as you move around? Just for the sake of completeness, try this. I've modified your raycast to no longer check layers and to store the reference to the object so we can print out what it's hitting. It might be hitting something before it reaches the ground. What does this log print?
public bool CollisionCheck()
{
isGrounded = Physics.Raycast(transform.position, Vector2.down, out RaycastHit hit, groundCheckDistance);
Debug.Log($"Raycasting from {transform.position}, distance of {groundCheckDistance}, hit object {hit.collider}");
return isGrounded;
}
Does anything else modify velocity? Share the full !code of the script
📃 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.
the fixedupdate?
void Update()
{
moveX = Input.GetAxisRaw("Horizontal");
if(Input.GetKeyDown(KeyCode.Space) && grounded)
{
jumped = true;
}
if(Input.GetKeyDown(KeyCode.K))
{
Time.timeScale++;
}
if(Input.GetKeyDown(KeyCode.L))
{
Time.timeScale = 1;
}
}
private void FixedUpdate()
{
if(movePlatfrom == null || !movePlatfrom.clouded)
{
float targetVelocityX = moveX * moveSpeed;
rb.AddForce(Vector2.right * targetVelocityX * acceleration, ForceMode2D.Force);
// Limit velocity
rb.velocity = new Vector2(Mathf.Clamp(rb.velocity.x, -maxSpeed, maxSpeed),rb.velocity.y);
// Decelerate if no input
if (moveX <= 0f)
{
// Gradually reduce velocity to zero
float decelerationAmount = deceleration * Time.fixedDeltaTime;
rb.velocity = new Vector2(Mathf.MoveTowards(rb.velocity.x, 0f, decelerationAmount),rb.velocity.y);
Debug.Log(rb.velocity);
}
}
if (movePlatfrom != null && movePlatfrom.clouded)
{
rb.velocity = new Vector2(moveSpeed * moveX + movePlatfrom.speed, rb.velocity.y);
}
if (jumped)
{
rb.velocity = Vector2.up * jumpSpeed;
jumped = false;
}
if (moveX > 0 && rotated)
{
transform.eulerAngles = new Vector2(0, 0);
rotated = false;
}
if (moveX < 0 && !rotated)
{
transform.eulerAngles = new Vector2(0, 180);
rotated = true;
}
if (moveX != 0)
{
anim.SetBool("IsRunning", true);
}
else
{
anim.SetBool("IsRunning", false);
}
}
The entire script
!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.
oh my..
share it other way xd?
Yes. It's not the full script like I asked for but it'll do
lmao
i just have oncollision enter and awake for refrences
is that included in the script
ye but it wont matter anything
Places that it could be jumping to 0:
- The clamp, depending on what
maxSpeedis - inside of
if (movePlatfrom != null && movePlatfrom.clouded) - inside of
if (jumped)
Any of those could set the x velocity to 0 before the deceleration takes it there
Okay, so it does hit something. That's on me I should have had you log hit.collider.name, can you add that?
if (movePlatfrom != null && movePlatfrom.clouded) it doesnt matter cuz it happen when its not true
i talk about first if statement
and even when im not jumping
Maybe
the problem is in the decelration value?
its 50
I'd still put a log in there just in case, if it were true for one frame it'd be enough to zero out the x velocity before going back to the first if
the second if statement can only be true in other scene
and jumped if i click space and i dont
Possible, your fixedDeltaTime should be 0.02 assuming you haven't changed it so it should be decelerating by 1 every physics step
So what is a good value and i realy have to * fixeddeletetime?
Yes, if you multiply it by fixedDeltaTime then your deceleration can be thought of as units per second. Right now, you'll decelerate by 50 every second
how could one convert ?int to int? 🙂
So, if your X speed is 50, you'd reach zero in one second. If it's 25, it'd take half a second, and so on
.Value but if you're doing that without checking it for nulls you might as well just not use the ? notation at all
I removed it to 5 and i see if like i move straight a lot to max speed that is 8 it goes down like -8 -7 -6 -5 good till -4 and from -4 to -0.3 and why its - if i move right
move right*
thank you, not using ? works just fine )
--> https://hatebin.com/zuwbjangdy This script is responsible for teleporting the player to the destination point. It works just fine on the position.
-->https://hatebin.com/gqbmlptbri and uh this just calls the function and makes the teleport happen.
What i fail to understand is that when I teleport I want my camera to face the destination rotation. But when I come on the other side of the door my camera flickers till I move my mouse again. Can anyone point me the right direction?
rb.velocity = new Vector2(Mathf.MoveTowards(rb.velocity.x, 0f, decelerationAmount),rb.velocity.y); maybe i should change to lerp?
Pretty sure the issue is something else is overwriting it with 0 and not the actual method of deceleration
And the rb.velocity is - and im moving right it should be like that?
Okay so it's not always hitting an object. Hang on let me update the function, I wrote that last one up on mobile and I missed some stuff, clearly
public bool CollisionCheck()
{
isGrounded = Physics.Raycast(transform.position, Vector2.down, out RaycastHit hit, groundCheckDistance);
Debug.Log($"Raycasting from {transform.position}, distance of {groundCheckDistance}");
if (isGrounded){
Debug.Log($"Raycast successful, hit object: {hit.collider.name} on layer {hit.collider.gameObject.layer}");
}
return isGrounded;
}
Okay, does the second log ever appear?
Probably because it becomes negative?
Is it k that it becomes negative?
Probably. Assuming that's the direction you're going
nope
Hm, so the ray isn't hitting anything at all, ever. Are you sure all of your objects are at the same Z value? Do they all have 2D colliders?
If you're still using the MoveTowards then it won't go from positive to negative of vice-versa, you're stopping at 0. This leads me to believe that something else is changing it
No when im moving float targetVelocityX = moveX * moveSpeed;
rb.AddForce(Vector2.right * targetVelocityX * acceleration, ForceMode2D.Force);
// Limit velocity
rb.velocity = new Vector2(Mathf.Clamp(rb.velocity.x, -maxSpeed, maxSpeed),rb.velocity.y); and i move right the rb.velocity start positive and go into negative
idk why
maybe vector2.right is the problem?
That's just the constant (1, 0)
So why it is - when i move right?
Unless your moveSpeed or acceleration is negative, it won't be. Again, leading me to believe something else is moving it
O shit
i just all the time looked at the y
velocity
Wait i see the x isnt changing
float targetVelocityX = moveX * moveSpeed;
rb.AddForce(Vector2.right * targetVelocityX * acceleration, ForceMode2D.Force);
// Limit velocity
rb.velocity = new Vector2(Mathf.Clamp(rb.velocity.x, -maxSpeed, maxSpeed),rb.velocity.y);
Debug.Log("Velocity after clamping: " + rb.velocity);
yes the border have colliders 2d
Are they all at the same Z position
Wait so digiholic float targetVelocityX = moveX * moveSpeed;
rb.AddForce(Vector2.right * targetVelocityX * acceleration, ForceMode2D.Force);
// Limit velocity
rb.velocity = new Vector2(Mathf.Clamp(rb.velocity.x, -maxSpeed, maxSpeed),rb.velocity.y);
Debug.Log("Velocity after clamping: " + rb.velocity.x); the rb.velocity.x should be 0 when im moving?
Please don't try to mix words with code and please format the code. I can't tell the sentences from the code
K ill explain
When im logging the x velocity while im moving the velocity in x is 0
shouldnt it have a higher value?
That doesn't sound right
yes , all object from scene has the Z coordonates (0,0,1)
float targetVelocityX = moveX * moveSpeed;
rb.AddForce(Vector2.right * targetVelocityX * acceleration, ForceMode2D.Force);
// Limit velocity
rb.velocity = new Vector2(Mathf.Clamp(rb.velocity.x, -maxSpeed, maxSpeed),rb.velocity.y);
Debug.Log("Velocity after clamping: " + rb.velocity.x);
player and board have the same z coordonates bur square doesn t
I don't know what any of these objects are, but everything involved in this collision need to have the same Z position
I have no idea what this square is
but everything involved in the collision needs to have the same z position
it s another border
How do I stop this from happening? I have a base class that has a few child classes on the same object. But the base class public references show on the child's scripts.
So you don't want it to show up in the inspector?
Digiholic maybe the rb.velocity should be 0 and i have to check the magnitude fr idk what to do
You could make it protected so it's accessible by the child classes but not settable in the inspector
I don't want the child classes showing the same public field
How would you assign them then?
my base class has this:
protected GameObject mousePointCollider;
Then it wont show
wait
If the object is moving but the logs show a velocity of 0, then it's obviously changing after the log somewhere or it wouldn't be moving
That's what you want, right?
I only want the base class to show the variable
Digiholic i should see the gameobject accelrating and decelerating in my game if it works?
Then how are you assigning it on the derived class
hmm, idk. I don't want the children to set it. I have a singleton for my base class
I want them to reference the base class for that variable
should I start the whole project again?
Did you put them all at the same Z position? You said one was different
If you don't want the child classes to have this variable, why are they child objects
I deleted the object that had different z
tbh.. idk! I'll not make them the base class and just use the instance instead
I don't know if you're using child classes properly. You'd make PlayerMovement a child class of PlayerInput if you want it to be a PlayerInput. It extends another class. It is everything that class is plus some
yeah, I think i'm using child classes wrong in this instance
Tell you what let's just try to speed things along. Send me a screenshot of your entire unity window, with the console visible, with your raycaster object selected, and then another one with the ground below it selected
I can check a bunch of stuff at once
Oh, and do it while the game is running
what is the best way to move an object (the player) by dragging them with your mouse in 2D game? would i need to use raycast?
take a look at the IPointer interfaces
is that to detect whether or not my mouse has clicked an object?
amongst other things, like drag and drop, yes
okay i was searching around in unity docs and stuff and most people are just using ScreenToWorldPoint
but im not sure what that or IPointer is lol
Time to learn
https://docs.unity3d.com/Manual/UIE-Pointer-Events.html
okay i will thanks
Sorry, that was the wrong link. Try
https://docs.unity3d.com/2018.3/Documentation/ScriptReference/EventSystems.IPointerClickHandler.html
and the other IPointer interfaces
I noticed that now that line no longer appears
will this also work with rigidbody2d and physics? so i can move the player around and when i let go the rigidbody2d will still work
no, if you are moving outside of physics you will need to disable the Rigidbody for the duration of the drag and then reenable it on drop
last time I set it to 2.1, anyway it still doesn't work to jump
and ground i p put ground
i put
Also
if I set it so that the other objects have z, it still changes as it was before
Are you changing it while the scene is playing?
no
Wait, maybe I misread what you said. I thought you meant it was changing back
Can you fix all that and re-send the screenshot of the object with the Player script on it
Debug.Log("Current Speed: " + rb.velocity.x);
float targetVelocityX = moveX * moveSpeed;
rb.AddForce(Vector2.right * targetVelocityX * acceleration, ForceMode2D.Force);
rb.velocity = new Vector2(Mathf.Clamp(rb.velocity.x, -maxSpeed, maxSpeed), rb.velocity.y); guys does any1 know why the rb.velocity.x returning 0 when i move no matter where i put the debug.log
Wait a minute
I just realized something stupid I should have noticed before
Are you using Physics.Raycast or Physics2D.Raycast
Physics.Raycast
whoops
By the time I actually had the full context I hadn't looked at the code in like an hour and forgot it was Physics.Raycast
Digiholic now can you help me xd?
I dunno are you going to format your code and separate your text from your code so I can read any of it
the full 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.
and what is the problem
when i check the current speed by using rb.velocity.x when im moving its x and i dont see any acceleration on the player
Debug.Log("Current Speed: " + rb.velocity.x);
float targetVelocityX = moveX * moveSpeed;
rb.AddForce(Vector2.right * targetVelocityX * acceleration, ForceMode2D.Force);
rb.velocity = new Vector2(Mathf.Clamp(rb.velocity.x, -maxSpeed, maxSpeed), rb.velocity.y);
thank you very much, @polar acorn
!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.
cs //hey
it literally shows
I don't know what this means. What are you expecting to happen that isn't happening
Just calling AddForce over multiple frames should be causing acceleration
As long as the force is constant
Bro all the day i got called that i need to add acceleration and deacceleration
thats what i did with my movement
so how to do the movement with addforce i dont understand
i prefered Force over Velocity
You're already clamping the velocity so just add some constant force for movement
i have movespeed
A direction times a value
that value determines how fast you accelerate
bigger number means you reach top speed faster
and the clamp keeps you from going over
Probably not
i mean i want to move the player in a professional way
You mean easy to control and simple
ye like hollow knight for example
i use _rigidBody.AddForce();
multiplied by a movement speed
converted to camera direction
then thats my force
But than i remove the * acceleration that is 50 and i need to make speed be * 50 more like instead of 6 300
so the players movement is the force
my movement speed is 500
kinda normal ish speed
Wait so you tell me the addforce do the acceleration and the accleration is like make speed being 300 but 6 in inspector?
but i want acceleration
thats
what we are doing
addforce every frame
will speed ur player up every frame
by adding that force
until you reach a max constant speed
thats "acceleration"
the movement speed is how fast you want to accelerate and the top speed
which you can cap probably
so after you get the Vector3 player movement input
you put that in as force
then choose ur force mode
there is an acceleration one..
And clamp the speed to max speed that it wont go more than that
ok then use ForceMode.Acceleration
fyi, Shift+Enter is a thing, please use it
Hard setting the velocity typically isnt a good idea
But its 2d
jfk
!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.
You still dont want to hard set the velocity
In 2D or 3D
so you telling me this short code is fine for 2d movement in high level like hollow knight?
and forcemod2d doesnt have .acceleration
But im using forcemode2d
c o o l
K last question
i want to check my current velocity like it starts on 5.5 and accelrate to 7 and want to see how fast how can i do that?
Every gameobject in my game has mass of 1 if using rb so doesnt matter
o k
how
!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.
just to double check, doing it this way will mean that rather than editing all instances of the script, it will just be a single instance?
What is the point of moving the reference from one variable to the other?
And yeah, if that is an instance (not a prefab), then it will only reference that instance
i dont want to accidentally edit the script itself again so im double checking if im doing it right
iceMachineScript will be whatever has been assigned to the specific instance of this component in the inspector.
Assigning it to iceMachineInstance does nothing other than copy that reference into the variable.
i see
also, you declared a local variable
so you didn't assign to the iceMachineInstance field
you've assigned the reference into a new local variable that is then thrown out as the function ends
yeah thats my bad i didnt notice that
There is no situation in which modfying iceMachineScript can "edit all instances of the script"
if dashUsed is a bool, then yes, it's the same outcome
you rarely want to actually compare against a true or false literal
might be a silly question, but if I am starting a coroutine, does the next bit in the method still go through before the coroutine is finished? I'm assuming thats the case
You can never block the main thread.
StartCoroutine does not "wait" until the coroutine method completes
im a bit stuck on what to do here
When you invoke a method that returns IEnumerator, you're actually creating a whole state machine that keeps track of what step of the method you've reached
You pass that thing to StartCoroutine. It runs the enumerator until it hits its first yield instruction.
Then it stores the enumerator in a list somewhere in MonoBehaviour
By default, it resumes the enumerator method once per frame
which runs until it hits another yield
So, when you call StartCoroutine(Slow()), the Slow method gets executed up to the yield return new WaitForSeconds(6f)
Then StartCoroutine returns and OnCollisionEnter2D continues execution as per usual
notably, it sets enemyMovementInstance.moveSpeeed = instanceHolder.moveSpeed;
Six seconds later, the coroutine resumes. It runs instanceHolder.moveSpeed = originalMoveSpeed;
At that point, the coroutine is over.
one suggestion: you can just pass EnemyMovement to Slow
yeah i just asked gpt about it and thats the answer it gave
StartCoroutine(Slow(enemyMovementInstance));
private IEnumerator Slow(EnemyMovement enemyMovement) {
// ...
}
Storing the enemy movement object in a field means that you can only run a single Slow coroutine without breaking it
im completely lost when it comes to putting stuff in the ()
i dont really understand it
when you invoke a method, you can pass arguments
do not respect any explanation given by chatGPT
The arguments you need depend on the parameters the method asks for
well yeah have to take it with a grain of salt
but for simple issues its a useful tool imo
int five = Add(2, 3);
enemyMovementInstance.moveSpeed = instanceHolder.moveSpeed makes no sense, by the way
it does nothing because both enemyMovementInstace and instanceHolder reference the same thing
oh yeah true lol
chatGPT can produce a document with the right syntax that you request, on the topic of your request. But it doesn’t actually know anything, and so it cannot actually explain anything.
it knows language, not logic
this adds a force up when a player is in water according how deep he is, so when hes at the top it doesnt add any```cs
if(!isUnderwater)
{
float distance = water.transform.position.y - transform.position.y;
float normalizedDepth = Mathf.Clamp01((distance - minDepth) / (maxDepth - minDepth));
float forceMagnitude = Mathf.Lerp(0f, maxForce, normalizedDepth);
Vector3 force = Vector3.up * forceMagnitude;
rb.AddForce(force, ForceMode.Acceleration);
}and then i have another force acting on the player for horizontal movementcs
rb.AddForce(moveDirection.normalized * swimAcceleration);```
can anyone explain why when i jump into the water and not move it works properly
and when u see in the second half of the clip im swimming around
and the player is bouncing up and down
buoyancy is awkward to implement imo
I would look at moveDirection
moveDirection = orientation.forward * y + orientation.right * x;
y and x are raw inputs
I wonder if whatever you're doing to damp your velocity (you don't oscillate forever in the water in the first half) is getting messed up by movement
The second half is what I'd expect with no damping, actually
in general, in fluids you want to:
- Damp your usual forces,
- Add force when making initial contact with fluid
- Apply buoyant force
bobbing up and down forever
the main point I want to make is that order of application and modification of forces with force is very important
one way to get it to stop bobbing is to effectively calculate a center of volume/mass, and compare to the water level
and apply force that scales with the delta height
but you want it to stop bobbing
meaning the force needs to become weak near the surface
it does
It doesn't matter if the force becomes weaker
As long as there's no loss of energy, you will bob forever
guys i need help for the coding stuff
yeah, some damping factor is probably worth
I'm guessing you have code that tries to reduce your velocity to zero when you aren't holding down movement keys
(or that incidentally does that)
i increase drag
but its not affected when im swimming
u can see in the video
oh wait
it increased
in the video
when i wasnt moving
https://learn.unity.com/tutorial/displaying-score-and-text?uv=2022.3&projectId=5f158f1bedbc2a0020e51f0d#650b5addedbc2a3242890dd4 based on this tutorial for the script for player controller i follwed it step up step and for some reason the ball doesn't move but the rest object moves, so can someone help me with it?
so how can i damp the force myself?
huh
hi, does anyone have the same issue as I do? Whenever my character dies it takes two lives instead of one
well, you wrote the code :p
Typically this means you did something incorrectly. Go back and make sure you don't miss anything
I will send it
Sounds like you should just add drag when you're touching water
i fixed the drag issue
now its always bouncing
so just add opposite force?
like down
to damp it
I'd just make drag higher in water, all the time
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.
cant use drag
i did everything step-by-step
can u check my codes and see what's the error
you missed something or did something incorrectly
It's not necessarily the code that's the problem
could be something in the editor
e.g. attaching a script to the correct object, arranging the hierarhcy properly, or assigning the right thing to a field in the inspector
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
I've been learning off of Game Makers Toolkit's video for making your first game and I finished the video. At the end he gives you a few promts to make for flappy bird and I wanted to make a start game screen. Im wondering how I change between two diffrent scenes and prevent code in one scene happening before I click a button to load the actul game screen?
Objects in unloaded scenes do not exist at all
so until you load the game scene, nothing in it exists or does anything
How do I unload or load a game scene though?
(look at all the SceneManager functions for how to load/unload scenes)
Thanks!
The default mode is single, which means that the new scene replaces all existing scenes
Should I write the script to load and unload scenes outside of my gamestart and gameplay scenes? or should I write it in the gamestart scene?
Game start right?
it should definitely be a separate script
so outside of both scenes and straight in the hiegharchy with no parents?
An object can't be outside of a scene.
you can use DontDestroyOnLoad to move it into a special scene that never unloads
But if you just need to go from menu to game and game to menu, I'd just make a component for each case
one that loads the game scene when you click the "start game" button and one that loads the menu scene when you hit the "quit" button
I guess you could make one component that has a string field on it
to decide where you go
public class SceneChanger : MonoBehaviour {
[SerializeField] string scene;
public void LoadScene() {
SceneManager.LoadScene(scene);
}
}
something like that
then you could just use a UI button to call LoadScene
Rn I have this attached to a button
so do I than delete the void start stuff and put that in?
and change the names to fit the names of my scenes?
That would instantly try to load a scene every frame (if the errors were corrected)
ohhh
this would let you reuse the component for both directions
Would I still need that if I already had a play again button?
cause when the birb hits a pipe, it destorys object and that round is over
would this only change the value on the instance of the script or the script as a whole?
On the instance. If the value was static, then the int would be associated with the Type and not the instance
i dont really understand
could you maybe explain it in simpler terms
Oh I just realized you are changing a value on a different script. But to answer simply, if you are changing an int (written as you have above) it will change the int only for that instance of the script. If you have 2 scripts, these ints can both be different values.
If you use the static keyword, the int will be related to the type (class name) like IceScript.enemiesSlowed every instance of a class will see the same value
ah i see, so as long as its not static, it shouldn't change it for all of them?
Yes but hopefully we are talking about the same thing, about 2 instances of 1 script. I notice you have 2 ints both named the same thing on different scripts
These ints are completely unrelated no matter what
Right now I currently have two scenes that I want to go from one to the other. I have a title screen (Image 1) and a in game screen (Image 2). But right now they are over lapping (Image 3). How do i get the game to start on the first image, then be able to click the Let's play button to get to the second screen? (I have a working play again button for when the bird dies).
i have no answer but i want to commend you for that funny title name
thanks lol
Help i don't know what is going! i am sopossed to have varibles but for some reason after i added the custom inspector all the varibles went "Goodbye!"
Because you have a custom inspector that does not draw those serialized variables
how do i draw the varibles?!
Read the documentation pinned in #↕️┃editor-extensions to learn how to create custom inspectors and the like
Following GMTKs tutorial for beginners and my "pipes" keep spawning off the screen. I've tried lowering/changing the offset from numbers 0-10 and same result. Does anyone know why/how this is happening? I've tried changing the actual position of the "pipe spawner" gameObject as well to see if it would fix but that didn't change anything either
(Pipe spawner gameObject)
You probably need to look at the pivot point of the object being spawned, it's likely lower than where you expect it to be
Either that or you have code on the pipes that changes their Y position
I've also tried this.
Make sure that your tool handle is set to pivot not center
How do I do that?
Oh I see, but it seems to also be fine
Okay so you know it isn't the pivot. Now check your code to see if there is anything that can affect the Y position
Oh actually I found it. Read the code you posted before VERY carefully again
Ahh is it float 'highestPoint = transform.position.x + heightOffset;'
Yes
Hello guys, I have a problem. My hp reset to 3 just when i change my current scene. no mention of "3" in my code. I have no idea where is the problem :/
Neither do we unless you show some code, hierarchy-inspector data, console logs etc
i've searched 3 with the Search feature of VScode so ...
it's probably set to that in the inspector
I define my HP to 5 in my GameManager who is a singleton. When i click on my button to go to my main menu and load my game with a Resume button, it reset my value to 3. When i die and respawn for example the value is 5.
I use Playerprefs to save my data and when i get the value just before use .Save() or GetX() its the correct value, not 3.
Debug.Log is your friend
anyway you're missing something clearly
Make sure to save the player pref before changing scenes
maybe it's set to 5 and then immediately you're losing 2hp for some reason
lots of possibilities
!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 guys, i'll investigate more
Relative to #💻┃unity-talk message
It would be something like thiscs position.y = floor.y; @tidal belfry
i was wondering if anyone knew why whenever i set b_c to the same things as the line colidor one point get set too 0, 0 and the other is where it should be i modified the code slightly to debug so it might not work exactly as i said but please help here is the code
a example
!code
📃 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.
!code ```cs
IEnumerator MakePlatform(Vector3 point1)
{
LineRenderer line_ren = GetComponent<LineRenderer>();
EdgeCollider2D coll = GetComponent<EdgeCollider2D>();
//PolygonCollider2D coll = GetComponent<PolygonCollider2D>();
line_ren.SetPosition(0, point1);
//coll.points[0] = line_ren.GetPosition(0);
building = true;
yield return new WaitForSeconds(0.5f);
yield return waitForKeyPress(KeyCode.Mouse1);
line_ren.SetPosition(1, new Vector3(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y, 0));
//coll.points[1] = line_ren.GetPosition(1);
//coll.points[2] = line_ren.GetPosition(1);
List<Vector2> list = new List<Vector2>();
list.Add(new Vector2(point1.x, point1.y));
list.Add(new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y));
coll.SetPoints(list);
GameObject bride = Instantiate(bridge, transform.position, Quaternion.identity);
LineRenderer b_l = bride.GetComponent<LineRenderer>();
b_l.SetPosition(0, point1);
b_l.SetPosition(1, new Vector3(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y));
EdgeCollider2D b_c = bride.GetComponent<EdgeCollider2D>();
List<Vector2> b_p = new List<Vector2>();
b_p.Add(new Vector2(0, 0));
b_p.Add(-new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y));
b_c.SetPoints(b_p);
yield return new WaitForSeconds(1);
building = false;
}
📃 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.
this is the code
I'm trying to spawn an object at a specific position. But I can't figure out what I am supposed to put for the Quaternion. I don't know what the default Quaternion is supposed to be for 2D.
bar.Position is a Vector2, and I doubt Quaternion.identity is right, but I just threw it in there as a placeholder.
GameObject foo = Instantiate(objectToSpawn, bar.Position, Quaternion.identity);
What do I need to put as the third input parameter to get the correct Quaternion for the default 2D view?
Or is there a better way to spawn a 2D object at a position?
For once no bugs in my code. Would anyone be willing to do a little codereview for critique? https://hastebin.com/share/saqozuzebo.csharp If so 🙂
Identity is no rotation, which should be correct both for 3d and 2d if your visuals are oriented correctly
Oh, good. That's exactly what I want. Thank you.
(currentState == movementState.Grounded | currentState == movementState.Grappling | currentState == movementState.Hookshot)
I don't think this condition does what you expect it to do. | is a bitwise or operator, not a regular or.
In fact I think it would be true when you're airborne
Ah, no, it wouldn't. Still it's not really correct
It IS a logical or as well, but it doesn't short-circuit, it will evaluate all conditions even if the first is true. || would just go to the body if the first were true
I guess so. Anyways, || would be more correct here
You pretty much never want to use | over || in this case though
Definitely
void FixedUpdate()
{
Grounded();
Grapple();
Movement();
AirDash();
Hookshot();
}
I also don't like how it seems to enter all of the states here in fixed update. Kinda confusing to read. But that's a minor detail.
Aside from that seems fine.
i´ve ran into a problem i think i know the solution too but i want to hear your opinions on it, first of all here is a video showing it
bug: the first spawned multishootingenemy works just right but the 2nd one doesnt shoot
i think its due to the 2nd one calling the class(or script) on the first one, and therefore doesnt do anything on its own
once i kill the first one spawned the 2nd one works just fine
i have thought of just creating another class inside the first one script so i have them in the same place and i can make everything private, but idk if having all the code of one enemy in the same script is good for the long term
That last message feels like you've skipped several paragraphs of context...
Ahh i see thanks you two
HpScript | MovementScript | ShootingScript
Is this so bad?
I thought that it makes it easy to read, and makes sure no frame errors happen
since everything is then neatly split up into their own functions
the movementScript takes information from the shooting script so in case its shooting (a bool) is true, then he has his rb2d.velocity set to 0.
what im guessing that is happening is that the 2nd one instead of taking out information from his own script is taking it from the first or something like that ( which makes no sense to me since i get the script by going through the components of the prefab and making a reference in that way)
I have an array of this struct VertexGrid[]
public struct VertexGrid
{
public Vector3 position;
public Vector2 gridPos;
public float height;
}
How would I extract out only position, so I only have an array of Vector3? Vector3[]
I would like to assign the Vector3 array to a new variable
It's confusing, because you'd think that of it enters into the method it would do some logic and not exit right away. The way I'd do it is take out the state check outside the state methods . But that's kinda of a preference thing. It's not like the way your code works would change.
For loop the vertexgrid and create an array from vertexGrid[i].position
Kinda hard to say if your assumption is correct without seeing the code or debugging it. Did you debug to confirm the assumption?
Ahhh I getcha
So not a bad thing, just personal preference ^^
altough perhaps its less efficient data structure wise?
ok, I just thought there would be some kind of c# trick for this kind of thing but I guess this will have to do
i cant think of were to put the debug, since both are prefabs i wouldnt know which one wrote the debug right?
Might be, not that I know of though, sorry
It's a minor detail. In your case you have a very simple state machine, but if you had something more complex, it would've been better to have a generic state selection mechanism.
Gotcha
You can add that info in the debug🤷♂️
how?
and if I airdash whilst hugging a wal, it pushes teh player inside the wall (triggering the groundcheck)
before then forcing the player back out
You can add the name of the object or it's guid in the debug message.
The second parameter of debug is the object calling the debug
https://docs.unity3d.com/ScriptReference/Debug.Log.html
Not sure of the context of what you're doing though
That's an option too, although then you'll need to click the message to know
so it would be debug.log(GameObject);
Assuming you write it correctly. What Aethenosity suggest is also a good approach.