#๐ปโcode-beginner
1 messages ยท Page 101 of 1
is there another way for me to get the same effect?
time to implement your own physics
pretty much this ^
start with gravity, it's the easiest
ill probably be back tho
or just use the RIgidbody like the tutorial maybe
(dont mix it with cc tho)
ive already been using a CC for everything else, so i dont want to start over
why exactly do you need impulse force down to crouch/sprint anyway
this can be easily done with CC (crouch/sprint)
i dont want my player capsule to float
it wont float if you got gravity on it already
oh ok
and for crouch you shrink collder and move the center up
So will i be fine if i skip that bit?
should be
also, why do a lot of the people i see use rigid body instead of a CC?
is it cuz of the premade physics?
pretty much
physics stuffs not that hard to implement
it's just more convenient to use rigidbodies
oh, rigidbodies do have the benefit of high speed collision detection which is actually somewhat of a pain to implement
hey so i skipped it and it didnt float, but now when i stop pressing the crouch button, i stay in the ground
ope sorry i thought the vid would preview, not make you download
probably becase you have to shift the center of collider
Both the CC and Rigidbody do some things very easily, at the expense of making other things more complicated. Depending on which part is more important to your game, you might pick a different one.
Character controllers make general four directional movement dead simple, but struggle to have fine grained collisions and respond to forces. Rigidbodies do this really easily, but struggle with things like slopes and are quite a bit more fiddly with the code for movement and braking
here is a good way to do the crouching with CC
https://youtu.be/-XNm7dPVVOQ
thank you kind sir
The built in cc is kinda shit, you arent supposed to do 2 moves per frame ever, its grounded check sucks too. I had a custom cc I made, and honestly it was so complicated yet still sucked. Yesterday I decided to scrap the custom cc and used rigidbody velocity, the code is much much simpler and works better.
Unity standard assets used to come with RB third person controller , I wonder why the new ones they decided to just use CC
I try to keep a lot of my level flat, and slopes clear of any bumps and it seems to work out well enough, I only use the CC cause I wanted to make a freaking cool blackhole effect and I wanted some of my own fake physics in the calculations
oh that and people tell me that rbs are performance heavy considering I have like 500 enemies
haven't actually profiled that though
Maybe it's more of an industry standard
maybe nvidia added some features only unity knows ๐คทโโ๏ธ
i dont mind the CC except for moving platforms
"works right away" and takes less messing about with different drag modes with RB
dealing with RB sliding against walls smoothly (without using cheap physic material no friction) is a pain..somehow...
When I tested my custom CC movement, I could easily run 200 enemies at >100 fps (in editor). I was doing a collide and slide approach, which would do multiple capsule casts per enemy per frame. I think 500 should be fine if you optimize
yeah hoepfully cause atm my cpu is kinda maxed and I've been trying to load more work on the gpu as possible
I thought moving platforms are easier on CC
really should have done ECS but too late now
If you're doing a kinematic CC, just get KCC off the asset store and save yourself the headache of handling any of the background stuff so you can focus on pure movement logic.
moving horizontal they are, you just parent it to the platform. Vertically , without bumping is another story ๐
I tried moving platform is kinematic, i tried using Physics.SyncTransforms
twitch city
oooook so im trying to code a camera shake effect myself and this code is NOT optimal it goes wayyy too fast. any ideas on how to make it slower? i dont know how i coudl make it slower consdiereing update() runs on every frame
ok so i decided to completely redo the movement and camera system in order to use a rigid body, and now when i press play my camera is being teleported away from the player, how could i fix this?
Use a coroutine
coroutine huuuhhh
sorry big word
actually i think i know what that is i just dont know how i would establish it in C#
Replace one with delta time and some scalar.
not code question
you said scalar so i assumed you meant you wanted me to scale deltatime up since it is a decimal i think
I said replace one not incr
because too busy not using Cinemachine
just kidding
afaik I think because movement happens in Update/Fixedupdate
and late update comes after those
https://gamedevbeginner.com/how-to-use-late-update-in-unity/
if they try to move on the same frame its choppy
but seriously don't make your own camera follow and use Cinemachine..
You are not understand why we need time.deltatime, not a hard coded number, imagine you have 1000fps now and what will happen to your code
private void Update()
{
mousePos = Input.mousePosition;
mousePos.z = depthOffset;
if(MasterPowerSwitch.isOn)
UpdateMousePositionUI();
else
{
xTxt.text = "00.00";
xTxt.text = "00.00";
}
rectTransform.position = cam.ScreenToWorldPoint(mousePos);
//mouse cursor offset
rectTransform.anchoredPosition += offset;
}
void UpdateMousePositionUI()
{
xTxt.text = mousePos.x.ToString();
yTxt.text = mousePos.y.ToString();
}```
wonder why there's a trailing `.5` on the Y coord
void MoveCamera()
{
rotationX += -Input.GetAxis("Mouse Y") * lookSpeed;
rotationX = Mathf.Clamp(rotationX, -lookXLimit, lookXLimit);
playerCamera.transform.localRotation = Quaternion.Euler(rotationX, 0, 0);
transform.rotation *= Quaternion.Euler(0, Input.GetAxis("Mouse X") * lookSpeed, 0);
}
public override void OnStartClient()
{
base.OnStartClient();
if (base.IsOwner)
{
playerCamera = Camera.main;
playerCamera.transform.position = new Vector3(transform.position.x, transform.position.y + 0.6f, transform.position.z);
playerCamera.transform.SetParent(transform);
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
else
{
gameObject.GetComponent<PlayerScript>().enabled = false;
}
}
when i play and start a server in unity, when moving around its smooth but when i move my camera it is really glitchy the movement and it is not smooth at all
how do i fix.
Presumably because the window isn't perfectly aligned to the pixel grid
scaling issue, yup, it was half a pixel off ๐
yea, i never stopped and thought about what mouse position is actually using
some sort of interpolation could work to smooth out the camera.
there's a few differnt ways. you can search camera smoothing on google to find some examples..
then you can multiply the logic with a modifier you can adjust as needed for the amount of smoothing you want.
That would make it frame dependent. Multiply it by delta time.
_______ = _______? ______ : _______; What does this format mean and how do you use it
It is a ternary operator
It is an if statement essentially
X = Y ? A : B
If Y is true, assign A to X
If Y is false, assign B to X
It only works with assignments
anyone know how to make it so that one animation needs to end befoire playing another in a blend tree?
Hai, I need some help reading one var from a script to another. In this case, I have a UI display script with the UI game object added and a score text field in the CANVAS gameobject parent. There is a child text on it. The UI display script has a public score text variable where I can add a text item on to it, and I can't add the child to that section of the inspector for some reason. I'm trying to make it so that the UI script modifies the score text based off the score int from the playerMovement script. Im sure there's more efficient ways to do it, but prob more complicated to me atm. THis is my current UI script:
public class userInterfaceScript : MonoBehaviour
{
public playerMovement moveScript; // Reference to Script A
public Text scoreText; // Reference to the UI Text component
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void UpdateScore()
{
Debug.Log("Counted!!!");
scoreText.text = "Score: " + moveScript.score;
Debug.Log(moveScript.score);
}
}
oh and this is where I update the score in the playerMovement script when it collides with the coin:
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Collectible"))
{
//Collectables should play a sound effect when collected.
PlaySound(coinCollectSound);
//The collectables count as the score for the player and disappear when touched by the player.
score += 1;
Debug.Log("MOVE: " + score);
Destroy(other.gameObject);
// Call the UpdateScore function in userInterfaceScript to update the UI
if (uiScript != null)
{
uiScript.UpdateScore();
}
}
}
if anyone could help, please ping me :D
i would remove the checking of uiScript!=null (unless the ui script will be destroyed?)
then after you increment score in script A and script B read it back.....why dont just pass the score or let the player control over it?
I will remove that null check.
I thought I was attempting to pass the score through the
public playerMovement moveScript; // Reference to Script A
public userInterfaceScript uiScript; // Reference to Script A
lines. I thought they would allow me to just easily pass a variable around for accessability but I guess I'm not? Can you tell me how to properly pass the score then ? @gaunt ice
if you want accessibility, you can make anything static.....
uiScript.SetScoreText(score);
```pass the score as some ways above
void MoveCamera()
{
float mouseY = Input.GetAxis("Mouse Y") * Time.deltaTime;
float mouseX = Input.GetAxis("Mouse X") * Time.deltaTime;
rotationX += -mouseY * lookSpeed;
rotationX = Mathf.Clamp(rotationX, -lookXLimit, lookXLimit);
playerCamera.transform.localRotation = Quaternion.Euler(rotationX, 0, 0);
transform.rotation *= Quaternion.Euler(0, mouseX * lookSpeed, 0);
}
public override void OnStartClient()
{
base.OnStartClient();
if (base.IsOwner)
{
playerCamera = Camera.main;
playerCamera.transform.position = new Vector3(transform.position.x, transform.position.y + 0.6f, transform.position.z);
playerCamera.transform.SetParent(transform);
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
else
{
gameObject.GetComponent<PlayerScript>().enabled = false;
}
}
when i play and start a server in unity, when moving around its smooth but when i move my camera it is really glitchy the movement and it is not smooth at all
how do i fix.
you should just use cinemachine. its also hard to suggest much since this looks to be multiplayer and also we dont see when MoveCamera is called.
could u just explain it a little more. Im having errors when trying to put that under my playerMovement script and Im not fully understanding what u mean, especially the "pass the score ... "
you're not supposed to multiply Time.deltaTime into your mouse input
That will cause jitter
it still does it even with time.deltaTime out
ill try using cinemachine
let uiScript directly access some variable is not a good idea (you can change player score in ui script), instead lets player tell ui script when its score is changed
did you compensate your sensitivity down?
yes, even at like 0.1 sens it still makes it jittery
are you moving via Rigidbody?
yeah im using rb.addforce
then you should be rotating the Rigidbody not the Transform
instead of transform.rotation *= Quaternion.Euler(0, mouseX * lookSpeed, 0);
it should be rb.rotation *= Quaternion.Euler(0, mouseX * lookSpeed, 0);
iull try that now
ok so usually its best practice for a script to not have direct access to another variable from an outside script? My UI Script isn't really that big atm, its literally just that updateScore() function. Should I just allow the player to have access to UI functionality and change the score text from the playerMovement Script itself rather than having its own seperate script for UI ?
I was also thinking of adding a timer tho
its very small but i think that just made it so then it is always jittery
and the mouse feelsa little delayed
usually an individual ui script is needed to handle some common ui elements like main screen or pause screen or settings, but the score text is tightly related to player to i think it is better to give control to player.
did you turn on interpolation on your Rigidbody?
yeah
its really weird like i can move my mouse without being laggy but when i start moving AND i move my mouse it gets laggy
how are you moving
AddForce you said?
Can you show how the code is currently?
if (grounded)
{
rb.AddForce(moveDirection.normalized * moveSpeed * 10, ForceMode.Force);
}
sorry did you mean the camera code or the movement. above is the movement on ground
its very small so it doesnt matter too much. but it is noticable, all my friends noticed it
you know what its fine, now that i think about it. it isnt worth all this struggle just to fix it. later if it really is bad then i can try to fix it again
soorry if i wasted your time
ok so I deleted everything and currently in my player script I have
using UnityEngine.UI;
public Text scoreText;
scoreText.text = "Score: " + score;
I am adding the Canvas' child (Score), into the player's public Text scoreText in the inspector, but Unity won't let me.
The game itself runs but then I get this error :
NullReferenceException: Object reference not set to an instance of an object
playerMovement.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Scripts/playerMovement.cs:102)
This error ****
what is line 102.....
scoreText.text = "Score: " + score;
and the error comes up when I collide with the coins
sorceText is null, you need to assign it in inspector
but idk why the error is not unassigned reference
I know, what I am saying is Unity doesn't allow me to drag the Score text child object from the Canvas parent into the player's inspector where it hold that
is it textmeshpro not text?
oh I think ur right
so TextMeshPro ?
and do I change the using unity.ui to text mesh pro or is that the same thing ?
I'm having an issue with a script, would someone be willing to help me troubleshoot?
Just post it. We'll try ๐ธ
@gaunt ice tysm!
oop, So I'm using the documented gameobject recoreder script to record animation in runtime, but I'm using to record a rigs animation that is being controlled by an IK system. it is only recordering the main object none of the armature
I had it as humanoid and ik that was some issue, so I was able to get the IK working fine with it in generic, but still to no avail
Probably best for #๐โanimation as this is not really a code question. But maybe the rig doesn't have all the bones required to be Humanoid?
Okay, so learning Unity
And for educational purposes I'm making my own first person player controller.
Working on the movement and I'm having issues with the diagonal movement.
I see a common problem is diagonal movement being faster due to not normalizing, but my issue is that 2 of the 4 diagonal movements don't move at all, the player just stops.
private void Move()
{
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 inputVector = new Vector3(x, 0f, z).normalized;
player.transform.Translate(inputVector * currentSpeed * Time.deltaTime);
Debug.Log(inputVector * currentSpeed * Time.deltaTime);
}```
Assuming it's due to the -x and positive z (or vice versa) fighting each other, but am unsure how to get around it.
It's probably something simple that I'm overlooking / over thinking.
W/D works, S/A works, but W/A and S/D just stop dead
It is easily made humanoid, the script is just not recording the armature, It gave me an error when it was humanoid so I made it generic. but now it still doesnt record the armeture even though there is no more error.
so I'm assuming its not recording it bc of the IK actively moving the armaeture but, that kinda defeats the whole point of a gameobject recorder so im unsure of how to work around that
Yeah, I dunno
#๐โanimation
oki, I'll give that a try ty
I'm guessing you have no idea what Sin is. 

i read up and its interval of how long a frame took to get to the next frame
What's "currentSpeed"?
I have no idea why it would do what you're saying, it doesn't make sense. But you should write inputVector * (currentSpeed * Time.deltaTime) so you save a few multiplications
Last frame to current frame actually.
You can't predict when the next frame happens.
yeah thats what i said
currentSpeed is just a float setting the speed
separated it out from baseSpeed to modify speed based for sprint/crouch movement
There's no reason why it would do what you're saying. Check the individual values of x and z when you're holding those keys and see what they say
-1,1 and 1,-1
x and z values of 1,1 and -1,-1 work fine
and presumably inputVector is the same
Yep, although sometimes it doesn't quite hit 1 or -1, it'll stop at a like 0.998 or something
Well, then it sounds like you would be translating by that amount (scaled), so there's no reason why you wouldn't travel in that direction
unless you're setting currentSpeed in a weird way that contradicts with the diagonal movement
currentSpeed is always at least 2.5f
currentSpeed = baseSpeed *2 while sprinting
currentSpeed = basespeed /2 while crouched
assigned back to baseSpeed (which is 5f) whenever I exit one of those conditions.
Tracking those variables, I don't see any unintended values
Wondering if I should switch to using velocity off a rigidbody
well, if it's for educational purposes, I don't think you should switch. I think you should figure out the current issue. Maybe try sending more of your code, because (as has already been mentioned) this code by itself wouldn't cause issues with diagonal movements
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
don't flood the chat, use links
!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
are you mixing rigidbody with translation?
I just noticed this myself, probably going to drop the rigidbody for the jump
I would drop the translation and keep the rigidbody
if you want accurate collisions its easier to use colliders than making your own casts
Then I'm back to using velocity for the movement, correct?
if you don't want velocity you can always make it kinematic
with that you might still need to check walls so you don't go through them
Honestly I'm impartial, I'm mostly just confused as to why it's happening to begin with.
I'm not opposed to using a different approach
are you sure the rigidbody wasn't drifting your player or something?
btw this is reduant doing if statements for these bools
if(Physics.Raycast(checkGround, out hit, rayLength))
{
isGrounded = true;
} else
{
isGrounded = false;
}```
can just be `isGrounded = Physics.Raycast(checkGround, out hit, rayLength)`
Fairly certain
Only happens when the translate is being fed -x, z or x, -z regardless of position within the world, rotation or terrain/objects around it
and agreed, was just writing it as simply as possible for my brain, was going to go back and clean up once it was working
normal move or crouch ?
both, sprint as well
even mid air, if I input W/A or S/D the player just stops completely
wdym mid-air? thought you had no rigidbody lol
what is the shape of your collider ?
Had a rigidbody that was was being used by Jump(), tried removing it and even the collider, still the same behaviour
Was using a capsule collider
I know exactly why you're having your issue
idk how I did not see this before lol
doh
Get rid of this
if (Input.GetAxis("Horizontal") + Input.GetAxis("Vertical") != 0)
pretty sure that will fix it
I would clean this up btw
private Vector2 move;
void Update()
{
move.x = Input.GetAxis("Horizontal");
move.y = Input.GetAxis("Vertical");```
then if you want you can do move.normalized
Agreed, still plan to go back and tidy everything up
Thanks for the help though, I chased that for far longer than I care to admit
yeah, I got what you meant 
so you can do if (move != Vector2.zero))
That's much cleaner but for the time being I just slapped an OR in there
if (Input.GetAxis("Horizontal") !=0 || Input.GetAxis("Vertical") != 0)
so verbose
Guys, I need some help.
I'm learning to do the dialogue system with Ink integration based on this video https://youtu.be/vY0Sk93YUhA?si=9k7oH6wimO36MwDT
Then I realized I couldn't use the mouse to click on any button on the screen.
I even tried to make a new project and used his GitHub repo (I took the branch number 2) to test if my script was wrong and I still can't click the choice button provided on the choice button. I also used Unity new input system
In this video, I show how to make a dialogue system with choices for a 2D game in Unity.
The dialogue system features Ink, which is an open source narrative scripting language for creating video game dialogue that integrates nicely with Unity.
Thank you for watching and I hope the video was helpful! ๐
NOTE ABOUT INPUT HANDLING - If you're try...
Anyone know why my game is lagging? I know it's because of the player rotation feature I've added. But I cant seem to figure out why. Here is my script:
float angle = Mathf.Atan2(direction.x, direction.y) * Mathf.Rad2Deg;
Quaternion rotation = Quaternion.AngleAxis(-1 * angle - 90, Vector3.forward);
m_transform.rotation = rotation;```
I know the transform.rotation is the reason why, but I can't figure out an alternative or work around
Rotate the rb by setting angular velocity/adding torque or using MoveRotation (not sure if there is one in 2d).
do you have at event system in your hirerchy
are you using the mouse because from the video seems they are just using keyboard
The video use KB only. My project can use KB just like the video but I also want to use mouse too
oh , so is your mouse made visible and not locked?
do you happen to have an example of this?
You can have a look at the documentation. They usually have examples.
Here's an example, for example:
https://docs.unity3d.com/ScriptReference/Rigidbody2D.MoveRotation.html
but rotating the rb doesn't rotate the sprite itself, correct?
Why not?
If your sprite is on the same object or parented to it, it will rotate as any other object.
This is my video. I haven't done anything to the mouse yet.
does this happen when you comment out the rotation code? I don't see why that would be an issue
correct
this problem is commonly caused by running stuff in fixedupdate without proper frame interpolation
there is, but it's still an odd problem
from my understanding is has to with rigidbodies
the weapon child rotates as well to face the mouse, before I decided to change it to the player
and it doesn't have a rigidbody attached to it
whereas the player does
Using transform rotation breaks the interpolation
im surpised no one else has run into this problem before
or if they have i cant find any solutions
Many people do. It's quite common.
Some just think that it's supposed to be like that and never think it's an issue.
I don't do 2D, but you could try
I just don't see how setting the rotation would break the position's interpolation
since that's where the actual lag is coming from
oh ok and those are buttons ?
Im not really following how to implement MoveRotation
would it be like this: rb.MoveRotation(rotation);
degrees
Yup, all those 2 are buttons
that's what it's in, but when I call it. WIthout the transform.rotation, it doesn't rotate at all.
It may help a little, but the lag is definetly still noticeable
so you're saying the lag still happens even without rotation code?
No, when I remove the transform.rotation it's fixed
I can't debug log it because its a void method
might be something to do with possiblity overriding that SelectedObject in event system but was only able to glance quickly
So you think the SeletecObject in the event system is the wrong here right?
Oh, MoveRotation should be used for Kinematic, not dynamic. Might be why its not working
This is how you generally rotate something "inline" with the physics engine
but it's a pretty ugly approach if you want a snappy rotation
again, I know nothing about 2d, so it's hard for me to understand why setting the rotation is breaking position interpolation
Do you have tons of dynamic (non-kinematic) rigidbodies in your scene that are getting moved when these objects rotate? The profiler results are telling you that whatever you're doing is very expensive from a physics standpoint. But it might indicate it's because you're not taking your rigidbodies into account. Generally, moving rigidbodies means timing the movement with the physics timestep, and using the rigidbody-specific movement methods. So, instead of transform.Rotate, you'd usually want Rigidbody.MoveRotation.
I found this forums post on it
I mean yeah, you could check the frame rate
if it's 60+ then it's not really the issue
your game doesn't really look that demanding
post all of your movement code
worst case, you could probably just have an invisible rigidbody underneath, and your graphics sprite on top
actually that probably still wouldn't work
if (canControl) {
float controlx = Input.GetAxisRaw("Horizontal");
float controly = Input.GetAxisRaw("Vertical");
direction = new Vector2(controlx, controly);
keypressed = controlx != 0 || controly != 0;
direction = direction.normalized;
if (keypressed) {
saved_direction = direction;
}
rb.velocity *= Mathf.Pow(1f - damper, Time.deltaTime * 10f);
rb.velocity += direction * speed * Time.deltaTime;
base.Update();
I think thats everything, I didnt write so Im not entirely sure.
It works the same as in 3d. Rotating the object with transform would break interpolation in both cases.
It does from my experience.
you're probably right. I use a custom interpolator
And many people had it as the cause of jittering so far. Changing the rotation method fixed it for them. They can't all be lying can they?๐ฌ
its the same in 2d
You can still use angular velocity or torque.
If you don't like that answer ^ I can help you build a custom interpolator
which will solve the problem for good
both solutions are janky
Im a little loss on how tod ot aht
Probably not haha, I imagine it would take time I don't have. The projects due in about a month, thanks for the offer though
Infact, I'm getting beta out tmmrw or monday D:
you'll basically need to write some logic that spins the object using AddTorque until it's reached the desired angle
easier said than done
I would probably calculate the error = current_angle - desired_angle
and factor that into the rotation speed / direction
realistically it's probably gonna oscillate back and forth a minimal amount when it's reached the desired rotation
Check the documentation as I suggested before
There's not gonna be any error if you set the angular velocity manually.
Might need to clamp it when approaching the target angle to not overshoot, but it's not very complicated.
yeah, that's probably the best solution
public void AddTorqueImpulse(float angularChangeInDegrees)
{
var body = GetComponent<Rigidbody2D>();
var impulse = (angularChangeInDegrees * Mathf.Deg2Rad) * body.inertia;
body.AddTorque(impulse, ForceMode2D.Impulse);
}
}
is the angular Change in Degrees the same as my angle?
disregard what I said about addTorque. Use dlich's solution with setting the angular velocity directly
you'll get finer tuned control over the rotation
is there documenation for this?
Angular velocity in degrees per second.
This line is important in figuring out the equation
the physics engine ticks in fractional seconds
fixedupdate also ticks inline with the physics engine btw
For instance, if my physics engine ticks at 30hz (30 times per second), and my angular velocity is 30 (rotating 30 degrees per second) then it's rotating 1 degree every fixed update (30 / 30 = 1)
hey guys! im making a fishing game and i'd like the fish size (in arbitrary inches), the fish size (in unity units), and the fish sell price to all be randomized but scale with each other. so ideally i'd have a three ranges of twos and then randomize one of them and then scale the other two off of that. does anyone know how i could achieve this? thanks all :D
so this should ideally be set in fixed update
yes
Then, i change the speed of the angular velocity until i reach my desired point and set it to 0?
you should come up with a formula that does this for you
but yes
why one fish can have two size?
shouldnt there is a inch to Unity unit conversion
the default angular velocity is 7, so i could turn it up really high, then multiply it by a time to get my almost instatneous change?
maybe, but for my use case i feel like itd be easier for the actual size of the fish and the stated "inch" size to not have be direct conversions of each other. maybe in the future, im still in early prototyping
trying to block things out
float angleDifference = desiredAngle - currentAngle;
my brain doesn't work so good at 11pm, but that should be somewhere in your formula
the angularVelocity is just how much the physics engine is rotating your object every physics tick
i get what you mean now, since if the actual size of fish is small player cant see the fish in world?
actual size and price should be related, but you can clamp the magnitude when convert actual size to world size (at least make it looks consistence)
like dlich said, you probably want to clamp the values so it doesn't teleport instantly to the new angle
How do you start this rotation, like it's not a constant rotation so how do you turn it on?
if your character is not moving at all, then the angular velocity is 0
just go ahead and comment out your old rotation code, while we start off with this
I pretty much have already haha
just so you can get a general idea, set the angularVelocity to a constant value, like 0.1 every fixedupdate
cool, will try
and run the game, and just see what it does
your guy should be spinning
if your physics update rate is 30hz, then realistically he's rotating 0.00333333333 degrees every physics update
no, he doesn't seem to be moving
do it in fixedupdate
in the rigidbody2d in your editor, crank the angularDrag down to 0
if that doesn't work, debug.log your rb variable and make sure it's set
the debug log returns object
post all of the code
rb.angularVelocity = 1000;
debug.log(rb.angularVelocity);
}```
tell me what that outputs
you can remove the other debug
it returns 0
thats pretty strange
okay now it rotates
great
you'll have to do some trial and error, but just start off by getting
float angleDifference = currentAngle - desiredAngle;
and set that as your angularVelocity
every fixedupdate
so would it eventually hit 0 then and stop moxing
that's the goal
when the current angle and desired angle are the same/
you might have to do angleDifference * time.fixedDeltaTime
or something
since we want it happening in 1 step
yea, atm I have it so it rotates
I just need it to get to stop when it reaches that position
No, a body set in motion will remain in motion unless other forces are applied to it.
I think Newton figured it out?
we're updating the angularVelocity every physics tick though
Updating to 1000 according to the last code snippet
I gave him updated code
float angleDifference = currentAngle - desiredAngle;
angularVelocity = angleDifference * time.fixedDeltaTime;
Oh, with the desired angle?
yes
๐ 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.
my keyboard doesnt let me type that symbol
im on a 60%
you did it earlier
i copy and pasted it then
ah
okay i got it
Vector2 direction = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 finaldir = direction - rb.position;
float angle = Mathf.Atan2(finaldir.x, finaldir.y) * Mathf.Rad2Deg;
Debug.Log(Time.fixedDeltaTime);
rb.angularVelocity = angle * Time.fixedDeltaTime;```
the time*fixed delta time makes it rotate veryslowly
I thought i was doing that in finaldir?
nope, that just gets the direction for desiredAngle
your
float angle = Mathf.Atan2(finaldir.x, finaldir.y) * Mathf.Rad2Deg;
should be
float desiredAngle = Mathf.Atan2(finaldir.x, finaldir.y) * Mathf.Rad2Deg;
then currentAngle is the angle that the body itself is currently pointing (in degrees)
I understand
post updated code if you need help
am i dumb? doesnt rb.velocity return the direction of the rb
Rigidbody2D.rotation
rb.angularVelocity = desiredangle - rb.rotation;
wouldnt it look something like this?
it doesnt quite work tho
i just added that lol
gimme asec its compling
that make its run really slowly
makes sense tho cuz my fixeddelta time is .2
does it work though?
Vector2 finaldir = direction - rb.position;
float desiredangle = Mathf.Atan2(finaldir.x, finaldir.y) * Mathf.Rad2Deg;
rb.angularVelocity = (desiredangle - rb.rotation) * Time.fixedDeltaTime;```
when i devide by fixed delta time its instant
It works!
I just multiplied by the x value by -1
Ill probably just leave it at that
just has to do w my sprite orientation probably
yeah, division is right for the equation. you're set
dunno, you'll have to figure that part out
thanks for all the help bro i really appreciat eit
what is the getmask for anything except again? public static int AllExceptCharacters = LayerMask.GetMask("Character");
is ~ havent used for a while
It's the ~ alright.
How can I launch a dedicated server build from MacOS terminal with arguments?
Can't even launch it, "open executableFileName" doesn't work.
The executable is correct, double clicking it works.
too many ; in one line
look closer
number #1 rule of learning to code. Make sure if you're following tutorials or guides you're typing the correct syntax
ok ty!
more to the point is your IDE configured?
yeah that too
the program you are using to write code in
no clue tbh
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
โข VS Code
โข JetBrains Rider
โข Other/None
ooooh that
follow one of these links
yes it does that
it does not look like it, your IDE should have shown your error
Right so when im in edit mode and click run the camera rotates on the x axis as i want but it doesnt move when im viewing through the game tab
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseLook : MonoBehaviour
{
public float mouseSensitivity;
private float xRotation = 0;
public Transform playerBody;
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90, 90f);
Debug.Log(xRotation);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
playerBody.Rotate(Vector3.up * mouseX);
}
}
anything visibly wrong with that?
oh...
Theres a camera in my body and i cant access ut
public class ScareCrowReveal : MonoBehaviour
{
// Start is called before the first frame
public float RevealTime;
public float delay;
void Awake()
{
Debug.Log("Hi");
Color colora = gameObject.GetComponent<SpriteRenderer>().color;
colora.a = 0;
StartCoroutine(Reveal(RevealTime, delay));
}
IEnumerator Reveal(float time, float delay)
{
Color color = gameObject.GetComponent<SpriteRenderer>().color;
float deltaTime = 0;
yield return new WaitForSecondsRealtime(time);
Debug.Log("alpha");
while (deltaTime < delay)
{
Debug.Log(color.a);
deltaTime += Time.deltaTime;
color.a = deltaTime / delay;
yield return new WaitForFixedUpdate();
}
color.a = 0;
}
}
So I just made Coroutine which changes color alpha but It dosent works well
Debug.log(color.a) printed well but the actual value uis still not changing since Awake().
what should I do to solve this?
you need to set the changed colour back to the renderer. Color is a struct which is a value type
the GameObject's actual color alpha is always 1 as default although I made them 0 on Awake
I made same code before and It worked well without returning the colors
doubt
this
Color color = gameObject.GetComponent<SpriteRenderer>().color;
makes a copy so any changes to color will not affect the original
hmm youre right but one question
IEnumerator FireShakeEvent(GameObject RailGunTrail, GameObject RailGunCircle, List<GameObject> Effects, float count)
{
GameObject EF1 = Instantiate(Effects[0]);
GameObject EF2 = Instantiate(Effects[1]);
....
RailGunTrail.SetActive(true);
RailGunCircle.SetActive(true);
Color colorRG = RailGunTrail.GetComponent<SpriteRenderer>().color;
Color colorCircle = RailGunCircle.GetComponent<SpriteRenderer>().color;
int x = 1;
Vector3 railgunScale1 = RailGunTrail.transform.localScale;
Vector3 railgunScale2 = RailGunCircle.transform.localScale;
while (x < count + 1)
{
//Debug.Log(color);
// color.a = UnityEngine.Random.Range(0f, 1f);
// obj.GetComponent<SpriteRenderer>().color = color;
colorRG.a = x * 0.1f;
colorCircle.a = x * 0.1f;
railgunScale1.x += (float)Math.Sqrt(x) * 0.00075f;
railgunScale2.x += (float)Math.Sqrt(x) * 0.00126f;
RailGunTrail.transform.localScale = railgunScale1;
RailGunCircle.transform.localScale = railgunScale2;
x++;
yield return new WaitForSecondsRealtime(Time.deltaTime * 0.25f);
}
colorRG.a = 1;
colorCircle.a = 1;
RailGunTrail.GetComponent<SpriteRenderer>().color = colorRG;
RailGunCircle.GetComponent<SpriteRenderer>().color = colorCircle;
}
then why this code works well?
I assigned them at end of coroutine but its alpha changes slowly
it doesn't work 'well'
RailGunTrail.GetComponent<SpriteRenderer>().color = colorRG;
RailGunCircle.GetComponent<SpriteRenderer>().color = colorCircle;
need to be inside the while as well
it may be that you are starting many instances of your coroutine
thanks
why cant i directly drag in this textmeshpro function, im setting up a ui function to display my player health
this is the textmesh i want to drag in
Whts is the type of that Hpui field?
Make sure it's not the 3D/world type
change the declaration to TMP_Text
Use TextMeshProUGUI or TMP_Text
declaring it as TMP_Text fixed my issue
Hey everyone, so I'm making a game in Unity. I want to add a sprite to my 3D scene, but when I right click > 2D Object in the scene panel, the only option available to me is Pixel Perfect Camera (URP)
How do I get Unity to give the option to add a sprite like in this tutorial screenshot?
Install the 2D packages from the package manager
Okay cool I think I just did that. It's this one, right?
Are there any other packages that are generally useful to have in Unity?
cinemachine
What is the absolute most simple braindead way to get data from one scene to another. i dont care wether its clean or pretty
static class
lol
Store that data on a DDOL object, store it on a ScriptableObject referenced from both scenes, serialize it and write to disk then read it in the other scene, store it in a static variable. there are many ways to accomplish that
if i aleady have a class that isnt static that i gotta use?
reference it in a static class
Basically just a singleton.
Hello. How can i apply force in opposite direction of a body. like add force but in opposite direction from the collision direction
depends on your actual goal, you could just get the normal from the first contact point and apply force in that direction. or you could get the velocity of the rigidbody and add force in the opposite direction of the velocity
so i have a npc and when a player gets close i want smth to happen how to i check for when they get close
you could have a trigger collider and use OnTriggerEnter to determine when the player gets near, or you could use a physics query like a CheckBox or OverlapSphere or something. the query would give you a bit more control for when you want to check
i would personally use the physics query
Thanks, but now the sound doesn't play at all. What do I do?
did you read past the first bit of my message?
I don't know what messages I'm supposed to have, and I don't accurately understand the meaning on the site. The translator is not very accurate
I had a bug with two audio listeners, I solved it but still no sound
you need to go through the steps in https://unity.huh.how/physics-messages to figure out why your OnCollisionEnter may not be working
okay
do you have a video or smth on the physics query
no, you can read the docs or find a video yourself though
Can a single object be subject to OnTriggerEnter and OnCollisionEnter?
yes provided that object has a non-trigger collider. OnCollisionEnter will not happen for trigger colliders but OnTriggerEnter can be called on a non-trigger because that collider could enter a trigger
also don't crosspost
im trying to use UnityEngine.InputSystem in one of my tests. ive installed the package and added it to my assembly definition. but its still not being recognized in my test. What coul be th reason?
I don't understand what I need to do to get the OnCollisionEnter message sent and OnTriggenEnter working
if you would go through the steps in the page i linked you would see that two kinematic rigidbodies colliding do not produce an OnCollisionEnter message
These are not kinematic bodies, there is a tick on Is Trigger in the screenshot. But it won't work without it. You yourself said that OnCollisionEnter and OnTriggerEnter can be together, but I've tried everything already
I am a newbie and may not understand the meaning of the word "Kinematic Object" if so, I apologise
You also shouldn't be putting rigidbodies on environment objects that aren't moving, such as the floor/wall.
Without that tick, like I said, nothing works anyway
also one of these is a trigger so OnCollisionEnter will not be called. only OnTriggerEnter will be called with this pair of colliders
and you're not bothering to show what your code even looks like so ๐คทโโ๏ธ
I showed you the code above, here it is
Fall - Sound
Trigger lamp - Trigger
You know what I mean.
well for one !code
and two, did you not bother following literally the first instruction on the page i had linked that said to use breakpoints or logs to determine if that code is even being called?
๐ 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 again, OnCollisionEnter cannot be called when those two colliders intersect
Firstly:I don't know what these dots are, haven't looked into it yet.
And secondly: How do I get this code to execute then? There is even a video where the author succeeded and I did not. ( Most likely he didn't say or show something).\
i feel like i'm giving instructions to a brick wall so i'm not going to try helping any further. maybe someone else will have the patience to do so ๐คทโโ๏ธ
Maybe I should try to do a different floor. An invisible one that will perform the OnCollisionOn function?
Ok, thanks for trying to help, sorry for being obtuse, but that's what I am, a newbie
Looks like you cannot get helped
If you dont understand the help
You should learn the very basics first in order to understand the provided help
I have linked you the OnTriggerEnter docs, did you read it?
there are conditions that must be met in order to call this function
OnTriggerEnter works for me. Yeah, I read it. Hold on, I'm going to try one thing now, in case it works
To reproduce OnCollisionEnter both objects must be non-triggered without Rigidbody?
To have a collision, one object must have a rigibody. Both must have a collider.
Hi everyone, new user of the discord community. I've been struggling for a couple of days on this bug and I can't figure out what's causing it. I implemented a grid-based movement for a pokemon clone. The movement works, I was also able to add collisions and animations. But after some time I realized something was off. I removed animations and tilemap rendering and saw that the player lags from time to time when moving. It's very subtle but I'm providing a clip showing the bug (hopefully you can see it).
I'm adding the link to the code here:
https://gdl.space/qibayihaca.cs
Dude, do you think maybe I should change OnCollisionEnter to OnTriggerEnter? And when the lamp makes contact with the floor, it will make a sound.
Is this related to code 
That's how it works, isn't it?
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'm not sure, I've followed three different videos and I can't fix the problem. You think it is not and I should change channel? Sorry not used to the all channel things
Oh I tried using the inline method and hit the character mark so I thought I could upload it as txt file as recommended by Discord. Shall I delete and reupload as a link using one of the website?
Some people will not get the embedded text and won't bother to download the text file.
Okay I reuploaded it, thanks for showing me how
You may want to try using the pixel perfect camera package to ensure your art doesn't sit between pixels.
Also, just a note that setting the scale value of your game view isn't making things bigger. Keep it to the left, and scale the size property of your orthographic camera instead.
Okay I'll try looking into the pixel perfect camera
Even after adding the Pixel Perfect camera component there is no change
It's silly since it is a really minor thing, but I can't stand not having crisp movement. I want to nail at least that down before proceeding with more complex stuff
you won't have smooth code by directly modyfing the transform.position
that is a very bad way of handling the movement for several reasons (collisions, weird stutter movement)
Really?? What's good practice then? Adding a dynamic rigid body and changing its position? I saw that in another video
hey
You can do that, or the CharacterController is another option
Using transform just requires a lot of manual physics simulation to avoid the issues mentioned by xaxup. It is possible though for sure
Okay then I'll try doing that and see if the problem gets fixed, thanks
is there a way to get the normal of the collider when using ontriggerenter2D?
when using oncollisionEnter2D you can just use collision.contacts[0].normal; but that doesn't work with triggers for some reason
Triggers don't generate contacts
oh, is there another way to get them?
hi I am trying to do something from tutorial but itยดs not working
GMTK is powered by Patreon - https://www.patreon.com/GameMakersToolkit
Unity is an amazingly powerful game engine - but it can be hard to learn. Especially if you find tutorials hard to follow and prefer to learn by doing. If that sounds like you then this tutorial will get you acquainted with the basics - and then give you some goals to learn ...
hover over the red line. What does it say?
alright. ScoreText is of type 'Text' and you want to assign a 'String' to it, which doesn't work.
A 'Text' type contains many things, for example the font size, font type, spacing etc. And it also contains a variable called 'text' which is what you are looking for.
guys can i use C++ in unity
I donยดt think so
If you look closely you can also see that the code in the tutorial and the code you posted don't match exactly.
and how can I fix that?
ah sad unfortunately i cant run UE5 is there any other engines that use C++
scoreText.text = playerScore...
I am stupid but I canยดt find it
scoreText is of type 'Text' which is a class that contains all things you would need to display a text, the font, the spacing of the letters and more importantly the actual text you want to display. To set the text you need to call:
scoreText**.text** = "this text will be shown";
When you make game object and give it a child
Do you add scripts to the parent or child
depends what child does
Animation occurs after Update and before LateUpdate, notably.
I am trying to make a player move and I put the body of the player in a game object called player
there's no answer to this question; it isn't well-defined enough
If you want to move the parent object around, you probably want to put your movement component on the parent object
not because you couldn't put it on the child, but because it just makes more sense that way
Ok ty
also, you add components to objects, not scripts (:
Ok ty
Your script files don't get "attached" to anything. They just declare components.
So your Player.cs script probably has a Player class in it, which derives from MonoBehaviour
that creates a new kind of component called Player
Ok
how can i limit the velocity without setting it directly like i am doing now?
look fine
oh its because velocity overrides gravity
maybe run handle speed only if vel is above certain treshold
doesn't solve it fully tho, you're fighiting forces with vel override :\
Is player movement always horizontal?
i was thinking of this maybe
what do you mean
I don't think your ClampMagnitude line does anything because moveDirection.normalized * moveSpeed will always be the same magitude.
you can't look up and hold W to start climbing into the sky, right?
You could separate out two parts of your velocity:
- Horizontal movement -- in the X and Z directions
- Vertical movement -- in the Y direction
and then only clamp the first one
But this would behave weirdly on slopes. You'd be able to climb them super quickly
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class finalScript : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
int buildIndex = SceneManager.GetActiveScene().buildIndex;
if(buildIndex == 2)
{
SceneManager.LoadScene(0);
}
else
{
SceneManger.LoadScene(buildIndex + 1);
}
}
}
}
No ```?
whats the error?
Assets/finalScript.cs(19,17): error CS103: The name 'SceneManager' does not exist in the current context
lines 19 and 17? are u sure u tried it with this exact script
yes
Spell SceneManager correctly
Misspelled
let me see
๐
Probably need to configure your IDE? Did it underline the word?
Did you manually type this error message out?
I would assume the actual message says The name 'SceneManger' does not exist in the current context
Did it do a red underline under the error in your code?
or the drugs
i mean
i'm spanish
yk sometimes hard to write
why did you manually type out the error message and hide the most important part where it says "SceneManger" instead of "SceneManager"
idk literally idk
Evening all. I was just wondering if anyone had a 'technique' for hiding objects that the player character passes behind (fixed Camera angle always following/focused on the player), especially with things like 'multi-storey' buildings that the player can walk inside?
You can do this with shaders. I also remember an asset on the store that does it
Never done it myself though, so that's the extent of what I know
can do it with raycast from the camera too if you wanna just hide the walls
like, fully
shaders allow you to do some cutouts though
Yeah, I was imagining only a piece being transparent. Raycast is a good idea too, and would be easier
Okay yeah I'd thought about raycasting and shaders/disabling objects, but not entirely sure how I'd go about only disabling floors 'above' the current floor that the player is on if that makes sense?
comparisons
as in.....(pseudo)
if raycast hit floor3
enable floor1, floor2
disable floor4, floor5
etc.etc
floor + 1
Aah, I get you.
How to maintain lighting of the environment for viewmodels that uses camera stacking
Gun is bland and doesn't follow the lighting of the scene
Probably best for #archived-lighting
dudes, when it comes to handling attack animations, would you rather use triggers or boolean variables in your animators? I want to assess pros and cons.
if it's not a loop then I trigger
@grim wyvern a bool is good for looping animation, or animations that you don't want to be stopped if interrupted, like if walking is true, keep walking, while a trigger is good for something like an attack you want to do once or like a death animation, generally I use triggers most often
rb.velocity = new Vector2(movementInput.x * movementSpeed, rb.velocity.y);
Am i correct in assuming setting the rb velocity like this in an update, negates any force applied to said object?
As adding force just sets velocity on the rigidbody?
yes, but this should be done in FixedUpdate
if you want forces to impact your movement you may want to use addforce
instead of velocity
I didn't want to use addForce for movement cause then there would be acceleration, but i geuss it is inevitable
I'm sure i can work around it
You could either commit to velocity or clamp velocity while using addforce
you can use AddForce without Acceleration
Ye, i think i saw a good video on how to approach it awhile back
what are you actually making?
2d platformer, just wanted the movement to be precise
https://youtu.be/KbtcEVCM7bw?t=116
Found the video if anyone is interested
๐ฌDesigning a Platformer Jump: https://youtu.be/2S3g8CgBG1g
Want to make your character feel fluid and responsive to control? Use these tips and tricks to improve your platformer in any Engine or Language.
In this video, I'll show YOU how you can make more advanced platformer movement, which is more flexible to your needs as well as feeling fan...
thanks im checking it
While i'm at it, when i want to use AddForce once on an object can i just call it in a random method or do i want to flag it so it's used in the fixed update?
hey so for my game i have npcs with dialogue how would i make it so the player cant move while they are listening to the dialogue
Depends. Impulse and SetVelocity modes can be used anywhere no issues when you use them as one time calls
The others can too, but you may want to use them in FixedUpdate to keep it smooth and consistent
if you want consistent results best keep physics stuff in FixedUpdate
How do you move? Just make a bool to prevent it
It really depends on what you're doing now
this is my move function ```csharp
public void Move()
{
horizontalMove = Input.GetAxisRaw("Horizontal") * m_Speed;
Vector2 targetVelocity = new Vector2(horizontalMove * 10f, m_Rigidbody2D.velocity.y);
m_Rigidbody2D.velocity = Vector2.SmoothDamp(m_Rigidbody2D.velocity, targetVelocity, ref m_Velocity, m_MovementSmoothing);
animator.SetFloat("Speed", Mathf.Abs(horizontalMove));
if (horizontalMove > 0 && !m_FacingRight)
{
// ... flip the player.
Flip();
}
// Otherwise if the input is moving the player left and the player is facing right...
else if (horizontalMove < 0 && m_FacingRight)
{
// ... flip the player.
Flip();
}
}
You have given me knowledge.
just so you are aware, celeste uses a custom movement system so just make sure to use a rigidbody2d and you will be adding a lot of custom stuff either way to make it feel good
At the top of Move write
if (!canMove) return;
When you start dialogue, disable canMove
Yup, i already got clean movement down tbh, just need to switch it up cause i want to be able to apply forces to my player easy, since I just wander the docs like a lost rat I have gaps in my knowledge:)
I am using moveposition for my WASD movement on a 2D top down and it is pretty easy to apply forces like knock back and stuff, you ask a very good question tho
thats now how you do it
btw:
When you change the Rendering Mode, Unity applies a number of changes to the Material. There is no single C# API to change the Rendering Mode of a Material, but you can make the same changes in your code.
yea i looked it
it says BlendMode.Opaque this but doesnt work
i dont know how it works i am very beginner if anyone know can help
just switch 2 materials out..
That is in a switch statement. Assignments use =
But I agree, just swap materials
if im making a customization system where you can choose your color do i make a scriptable object that has a color for each image (that you select to choose your color) and then just use that or is there a better way
are predetermined colors? why not just a dictionary of them in 1 SO? or am i misunderstanding what you're asking
Someone can help me to do an script that makes the player knockback when attacked? feel free to dm me
do you have something started already and need help with? this is a learning place not really the place for scripts handouts
yea i think its not work like that
youre right
i added a wall in front of the glass so when i touch a button or something the wall will be disappear
oh i see what u mean
I have no idea how to do that
ye that wil prolly work thx
search up a rigidbody tutorial
are you using rigidbody >
Yes
def use it , it will make it easier
I tried to use AddForce but it dont worked
I'll try
depends, you can also just set a gameobject to inactive to hide it , or hide renderer.
or just do the 2 material thing and swap it out in Renderer
how do i reference a component from an entirely diff obj
for example
in a script inside my camera i want to reference the rigidbody component of the player object
i want to access the rigidbody's velocity
https://unity.huh.how/programming/references
the best way is always using Serialized references
player.GetComponent<Rigidbody>();
what is a serialized reference
public Rigidbody rb;
or
[SerializeField] private Rigidbody rb;
ideally the private one
soooo.. this will refrence a rigidbody component from a entirely different object yes?
this makes it easy to drag n drop the component directly in the fieldvia inspector
yes you just drag and drop the component you want from the other object into the field
GetComponent is ok too but imo no reason to use it if its not a runtime search , and even then stick with TryGetComponent
hi can you suggest a unity document for it, when you free
ye i thought they meant during runtime
you mean new()
not sure what you mean initialize in this context
i mean like
document for what exactly lol
you're just declaring
hiding the object or deleting it
I hate that unity made an overcomplicated example code on this one but yeah
just SetActive
oh you mean the type
accessor T variablename that defines vairable name as Type
im sorry im confused now
question does anyone know how to use git bash? im trying to update my unity project which i edited
define would be the type the variable name is
Rigidbody is a type you define for example myrigidbody
like i remember doing add . "name" but forgot how to get ther
even when i use serialized field,
i have to define it? the unity wont just handle it for me?
i just use a gui ๐ถโโ๏ธ
a gui? how so
c# is strongly/statically typed , you have to always define something you create
I have two functions (https://paste.ofcode.org/385sHssbFBmyMxzDXGtqxVe) that are very similar and both rebind controls but the one thats supposed to work for composites(the second one) dosent run the On complete part of the PerformInteractiveRebinding but the first function runs perfectly fine.
like Github Desktop or Fork
oh gotcha
oke doke
https://hatebin.com <- use this one
ahh new #๐ฑ๏ธโinput-system . I'm no help with this one just yet sorrry ๐ฆ
didnt see that channel ill post it in there
ive had issues where they y is not the up and down and the z is because of how ive made things mabey thats the problem
you have two local variables that are named very similarly and you are using the wrong one in a couple places due to that
you should print the position to see if the Y value is actually changing
and if it is not, then it is most likely your input axis not set up correctly
and if your Y axis is changing correctly but you do not see the object actually moving then you've deliberately rotated everything 90 degrees around the X axis for some reason so that you have a top down view in a 3d world instead of using the default 2d view
read the docs on GetAxis
If you google "getaxis unity" it should be the top result
even better, if you want to google something from Unity put Unity first in the search
where i can find support for unity mirror?
pretty sure there's a mirror discord
oh, they have discord?
its pinned in #archived-networking
If I have a string like
Sandpaper - 2136A
How can I remove the - and everything after?
using string.Trim()?
if you know it will specifically be that character you could just get the index of that character then use that as the end index for a substring starting at the beginning of the string
Can i somehow attach a instace of a c# object (in my case a Item) to a dynamically created gameobject (a button)?
if it is a plain old c# object you don't "attach" it, just pass the reference to the instantiated object from another monobehaviour
Yes it will be that character specifically
string key = inventoryList.name.ToLower();
Only classes that derive UnityEngine.Object will show up as a draggable "thing" in the inspector.
All reference types can be shared as per usual. If you do foo.bar = baz;, then foo.bar and baz refer to the same object.
Not exactly sure what you mean, currently i've got something like
foreach(Item item in Inventory.items)
{
GameObject inventoryItem = Instantiate(InventoryContentPrefab, InventoryContent_Component.transform);
// Somehow being able make the Item part of the instantiated gameoObject for later use
}
well, start by changing InventoryContentPrefab's type to something other than GameObject
that's a very vague prefab
Inventory and UI stuff follows the basic model view controller pattern if you're familiar with that with the GameObject's being the UI logic and the inventory the business.
public class InventoryContentEntry : MonoBehaviour {
public Item item;
// more code
}
...
foreach (var item in Inventory.items) {
var entry = Instantiate(inventoryContentEntryPrefab, InventoryDisplay.transform);
entry.item = item;
}
it might look like this
Just editing strings that have a "-" followed by 4 numbers and a letter like above I just wanna change this line below to cut off the - and everything after that character.. ( Sandpaper - 2136A then becomes sandpaper)
string key = inventoryList.name.ToLower();
no, that's what you're trying to do to solve your problem
the "Y" in the XY problem
this doesn't explain why
https://xyproblem.info
Asking about your attempted solution rather than your actual problem
what are you actually doing?
Hi! I'm looking for a way to not trigger OnValueChanged(); when I change the value of a dropdown in a script. Is there any simple way to do this? I haven't found a simple and concrete answer.
you want SetValueWithoutNotify
SetValueWithoutNotify
you'll find this on all of the UI input classes
I'll come back to this in 4.5 hours gotta go back into work , I'll explain just maybe a pm
no, you can explain what you're doing here, so that people can help you
Oh! It's that simple. Thank you
Hey, i want to do that when the player jumps and attacks he does a dive, but he kind of "teleports" instead of moving to the direction, this is my code:
public void Attack()
{
if (!readyToAttack || attacking) return;
readyToAttack = false;
attacking = true;
playerRigidbody.AddForce(transform.forward*1000, ForceMode.Acceleration);
Invoke(nameof(ResetAttack), attackSpeed);
Invoke(nameof(AttackRaycast), attackDelay);
//audioSource.pitch =
//sound stuff
if (isGrounded)
{
if (attackCount == 0)
{
ChangeAnimationState(ATTACK1);
attackCount++;
}
else
{
ChangeAnimationState(ATTACK2);
attackCount = 0;
}
}
else
{
if (dived == false)
{
//if (animator.GetBool("isDiving") == false && !isGrounded)
//{
//DIVE ATTACK
animatorManager.PlayTargetAnimtion("Dive Attack", false);
animator.SetBool("isDiving", true);
//}
moveDirection *= 7;
dived = true;
}
playerRigidbody.AddForce(transform.up * 70, ForceMode.Impulse);
playerRigidbody.AddForce(transform.forward * 300, ForceMode.Impulse);
}
}
I tried using other forcemodes, but they barely make a change.
i'm guessing that you typically move the object using velocity instead of force? because you're probably just overwriting any velocity applied by these AddForce calls
using ForceMode.Acceleration in a method you only call once doesn't make sense, by the way
Force and Acceleration are both used to apply force over time
they tell you how hard you're pushing
What happens to my UI code when I build for dedicated server? for example a listener to a button, that wont be needed on my server, is that still running on the server and wasting resources?
VelocityChange and Impulse are forces applied instantly (in one frame) as opposed to over time (multiple frames) . . .
Is there any benefit to using C# instead of C++
-for unity. I know C++ is generally more complex, but I'll be forced to learn it either way.
yes, people who only think they can code have less chance of totally screwing things up
lol
What?
They're not wrong. It's harder to screw up in C# . . .
Oh, yeah, I know. But is there any benefit specifically for using it with Unity?
But since you're in here, Unity is only C# so that's all you have . . .
You dont use c++ in unity at all
Unity only supports c# so there is that
see what I mean about who 'think'
You've been duped . . .
Duped?
Duplicated
It means tricked. From the word duplicity
Deceived or cheated of thinking you can use C++ . . .
but 'others' might not know what they are talking about either, so how much better off are you?
So you're saying I can't trust you?
me you can trust, others I'm not so sure of
would it be better to add force using the objects mass or ignoring it?
depends on your game requirements
Do you use the correct mass to move every object in your game?
like which one will result in less bugs and exploits in the future
that should not be your concern, what physics does your game require?
in my UI2D script I have a function to restart the main scene
public void RestartLevel()
{
SceneManager.LoadScene("mainGame");
}
I want it to be triggered upon pressing a button, the problem is that I am unable to select any function in the dropdown
Any suggestions as to why I am unable to find the function please?
for now im only using rigidbodies with default settings
Oh are you implying that I should be attaching UI2D over Player2D?
what? you need to drag an object that has the component into the slot. not the script asset
That went completely over my head, thank you
should have read the info in the link
Got it working, thanks a lot
Hi. Does anyone know any tutorials for implamenting melee combat on AI enemies?
Someone can help me with this error? Object reference not set to an instace of an object
Huh? We cannot paste from Transform rotation to Quaternion inside a custom struct?
but works for Position ?
Am I missing something?
[Serializable]
public struct PosRot
{
public Vector3 Position;
public Quaternion Rotation;
}```
I can't right click the field at all.
I'm assuming there's a w field with quaternion that you aren't showing
actually unity displays quaternions as euler angles in the inspector for whatever reason so there's probably not
nope
it's showing euler angles
I just can't copy / paste in this field for some reason
only the individual X,Y,Z though
Haven't tried but is this exclusive to your script only or does this apply for to Transform property as well?
I'm uncertain than
yea Unity must be doing some extra tricks with Transform inspector
private void OnTriggerStay(Collider collider)
{
if (collider.gameObject.GetComponent<Health>())
{
Health health = collider.gameObject.GetComponent<Health>();
Debug.Log(health.healthPoint.Value);
}
if (cooldown <= 0)
{
if (collider.gameObject.GetComponent<Health>())
{
if (!IsServer) { return; }
Health health = collider.gameObject.GetComponent<Health>();
if (health.whatIsIt == WhatIsIt.isBoss) return;
health.healthPoint.Value -= 1000;
}
Destroy(gameObject);
}
}
Can someone explain to me why Trigger is not getting the sentry collision?
I mean the wall, the boss or even the player are reciving the trigger and they get Debug.Log but not that sentry
Colliders are in childs but parent have rigidbody
Does rigidbody ignore collision or what?
For what are u sending me something I know and its even in the code?
well if you don't want help ๐คทโโ๏ธ
show the rigidbody and the collider for both of the objects involved
also finish your thought before pressing enter. your vertical messages are annoying
Are your colliders actually set to triggers?
Is this channel for beginners?
did you read the name of the channel?
lol.. ur gonna have trouble coding ๐
Yea but I still want to make sure
No its for experts
Got to start somewhere
The name of the channel is a sarcatic joke
Oh ok
this is a code channel. but just toggle the grid snapping option in your scene view
where is it sir
How the fuck am I supposed to make a player
oh i found
This scripting shit is hard ๐ญ
tysm for helping
there are beginner courses pinned in this channel. i suggest you start there
Are you spawning this explosion at a point? TriggerEnter won't call for things which are immediately inside the collider when spawned since they never "entered" inside.
Its on stay mate
why isnt this code working? im using character controller (cc)
As I am telling you guys. The script is working on every other gameobject wich has Health script like player, wall or boss
But not on a sentry
cc.Move expects a direction to move the character controller in. passing a position does not make sense
would i just change transform.position then?
There are so many structure in my game that have health script but this one is not working and its the only one gameobject that has a mesh collider
As it's a model from blender
yes but be mindful that you need to disable the CC to teleport it
https://unity.huh.how/character-controller/teleportation
There is a LOT that goes into that, what specifically do you need help with?
Man where do I even start, sorry I'm an absolute begginer
you still haven't shown the collider for your sentry
But I have to start somewhere yk
ahhh thats probably why it didnt work when i did transform.position the first time
!learn
and the default layer can collide with itself? and you've added logs into your OnTriggerStay to confirm whether it is actually being called or not and that this isn't just a logic issue?
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
placeTile(tileAtlas.Leaf.tileSprites, x, y + treeHeight);
placeTile(tileAtlas.Leaf.tileSprites, x, y + treeHeight);
placeTile(tileAtlas.Leaf.tileSprites, x, y + treeHeight + 1);
placeTile(tileAtlas.Leaf.tileSprites, x, y + treeHeight + 2);
placeTile(tileAtlas.Leaf.tileSprites, x, y + treeHeight + 3);
placeTile(tileAtlas.Leaf.tileSprites, x - 1, y + treeHeight);
placeTile(tileAtlas.Leaf.tileSprites, x - 1, y + treeHeight + 1);
placeTile(tileAtlas.Leaf.tileSprites, x - 1, y + treeHeight + 2);
placeTile(tileAtlas.Leaf.tileSprites, x - 2, y + treeHeight);
placeTile(tileAtlas.Leaf.tileSprites, x - 2, y + treeHeight + 1);
placeTile(tileAtlas.Leaf.tileSprites, x + 2, y + treeHeight);
** placeTile(tileAtlas.Leaf.tileSprites, x + 2, y + treeHeight + 1);**
placeTile(tileAtlas.Leaf.tileSprites, x + 1, y + treeHeight);
placeTile(tileAtlas.Leaf.tileSprites, x + 1, y + treeHeight + 1);
placeTile(tileAtlas.Leaf.tileSprites, x + 1, y + treeHeight + 2);
}
um what?
๐
Yes and yes
so if you have confirmed that OnTriggerStay is not being called then your objects colliders are not actually overlapping
any help with my code?
So what should I do now?
!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.
Seems like you went out of bounds
yes
newTile.transform.parent = worldChunks[(int)chunkCoord].transform;
this means that chunkCoord is either below 0 or larger than the number of objects you have in the array
wdym where do you put that? that's line 221 which is the line your error is happening on
well you need to start by figuring out why that number is outside of the range
hmm thinking
start printing values
i'd imagine it has something to do with your giant pile of magic numbers being added to your X inside of generateTree
you need to fix your errors
ill ask chat gpt
if you have a time, can you look at the prob in unity talk too.
how do make the code wait for a lil bit, like a "time.sleep" but in c#
coroutines usually
use a coroutine or a timer in update
and do not fall into the trap of using Thread.Sleep. it's a trick and will freeze your entire game for the duration of the sleep
๐ซก aye aye
ill try and fix ty guys
public void StartCoroutineExample()
{
StartCoroutine(WaitAndCallFunction());
}
// Coroutine that waits for 3 seconds and then calls another function
private IEnumerator WaitAndCallFunction()
{
// Do something before waiting, if needed
// Wait for 3 seconds
yield return new WaitForSeconds(3f);
// Call another function here
YourOtherFunction();
}```
heres an example of a coroutine being called in the `StartCoroutineExample()` function..
you'll also need the using System.Collections; using statement at the top in order to access the stuff u need to run one
You can never stop the main thread. That's the golden rule.
So you can't make your Update method "wait", for example
I thought Unity remembers the output folder when you switch from Desktop to Server Build? or is there a setting.. I would think it would remember the different folders you select when Building for the different Platforms in the editor... that just seems like it should naturally remember that. This is on 2022
quick thing if (y >= height - 1)
{
int t = Random.Range(0, Treechance);
if (t == 1)
{
// Tree generation
if (worldTiles.Contains(new Vector2(x, y)))
{
generateTree(x, y + 1);
}
else
{
int i = Random.Range(0, tallGrassChance);
//TallGrass Generation
if (i == 1)
{
placeTile(tileAtlas.TallGrass.tileSprites, x, y + 1);
}
}
}
}
did i do a mistake or sm
Tall grass doesnt spawn
!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.