im trying to build Pong Game with Microphone Input as controls for the paddles. the following part of the code (c#) is moving the paddle.
void Update ()
{
loudness=GetAveragedVolume() * sensitivty;
if (loudness>=8)
{
this.GetComponent<Rigidbody2D>().velocity=new Vector2(this.GetComponent<Rigidbody2D>().velocity.y,4);
}
shouldn´t this code below do the job? however its not working
else (loudness<=8)
{
this.GetComponent<Rigidbody2D>().velocity=new Vector2(this.GetComponent<Rigidbody2D>().velocity.y,-4);
}
Its obviously an easy problem but im kinda stuck in here with this noob question
Thanks in advance
EDIT// what i want to do:
Move the paddle up when the microphone receives Sound and drop back down if there is no sound, just like an value from an visual amp.
Daniel
Given that Update () is called correctly and GetAveragedVolume() returns meaningful values, it would have to look like this:
void Update () {
loudness = GetAveragedVolume() * sensitivty;
if (loudness > 8) {
this.GetComponent<Rigidbody2D>().velocity = new Vector2(this.GetComponent<Rigidbody2D>().velocity.x, 4);
}
else {
this.GetComponent<Rigidbody2D>().velocity = new Vector2(this.GetComponent<Rigidbody2D>().velocity.x, -4);
}
}
Your mistakes:
else (...) is invalid. Use else if(...).
You used this.GetComponent<Rigidbody2D>().velocity.y instead of this.GetComponent<Rigidbody2D>().velocity.x for the x-component of the two new vectors.
Some tips:
Wether you use >= or > does not really matter for floating point numbers in most cases, and definitely not in your one.
else is sufficient here. You don't need to check else if (loudness <= 8), because if it isn't > 8, then it is always <= 8.
Conventionally, you write a = b; / a, b and not a=b; / a,b, to make your code more readable.
I hope that works for you!
Related
So, i don't really know how to search for a answer to my question, i am working as a game developer for a freelance and my task was to do a "pendulum platform", That's the concept:
I tried a lot of different aproaches, like, for example setting collision boxes in the sides of the platform and when the player enter in the collision box, the platform will move like a pendulum.
But, i always ran into a lot of glitches, and when i managed to solve all of them, the movement felt unnatural.
Here is one of the ways i was trying :
public IEnumerator RotatesTowardsLeft()
{
while (transform.parent.eulerAngles.z < 25 || transform.parent.eulerAngles.z >= 330)//25
{
transform.parent.eulerAngles += new Vector3(0, 0, speed);
yield return new WaitForSeconds(0.01f);
}
currentDirection = Directions.Left;
}
public IEnumerator RotatesTowardsRight()
{
while (transform.parent.eulerAngles.z > 335 || transform.parent.eulerAngles.z < 30)
{
transform.parent.eulerAngles += new Vector3(0, 0, -speed);
yield return new WaitForSeconds(0.01f);
}
currentDirection = Directions.Right;
}
So, if anyone could help me, it would mean a lot, because i feel like i am running out of options...
Try using physics objects, and attaching a ConfigurableJoint to your object. (If you're working in 2D, use DistanceJoint2D) Then you can choose a location for the joint to attach to above it, and it should give you the effect you desire without a bunch of code. Keep in mind, if you are in 3D, there will be a little extra work to set up the ConfigurableJoint, like limiting some of the axes and spring force.
Hope this helps!
I'm having trouble counting the points of my AI Paddle Player and the user Paddle Player each time they miss colliding the ball. I tried using a boolean method and loops to count points, but to no avail as the program keeps on stating that the label in which my points are to be displayed, is "stack overflowed" due to an infinite loop which I am unable to recognize. So can you please help me.
Here is my code:
private void resetShiruken()
{
if ((reset == false) && (AIPoints < MAXPoints))
{
picShiruken.Location = new Point(ClientSize.Width / 2 - picShiruken.Width / 2, ClientSize.Height / 2 - picShiruken.Height / 2); //puts the picShiruken Picturebox in the middle anytime the picPlayerPaddle or picAIPaddle miss and is useful for counting the points of the computer and the player.
reset = true;
}
TheWinner();
}
private void TheWinner()
{
while (reset == true)
{
AIPoints += 1;
reset = false;
}
if (AIPoints >= AIPoints)
{
lblAIPoints.Text = AIPoints.ToString();
}
resetShiruken();
}
. resetShiruken() is a method that resets the ball to the middle each time any player misses.
. TheWinner() is a method that determines the winner of the game after either one of the players reach 5 points.
Thank You very Much,
Kai
As comments says:
you have recursive call of methods which lasts forever. resetShiruken calls TheWinner which calls resetShiruken and so on....
private void resetShiruken()
{
if ((reset == false) && (AIPoints < MAXPoints))
{
picShiruken.Location = new Point(ClientSize.Width / 2 - picShiruken.Width / 2, ClientSize.Height / 2 - picShiruken.Height / 2); //puts the picShiruken Picturebox in the middle anytime the picPlayerPaddle or picAIPaddle miss and is useful for counting the points of the computer and the player.
reset = true;
}
TheWinner();
}
private void TheWinner()
{
while (reset == true)
{
AIPoints += 1;
reset = false;
}
if (AIPoints >= AIPoints)
{
lblAIPoints.Text = AIPoints.ToString();
}
//resetShiruken(); <--- if you get rid of that call, should be fine.
}
Please note if you need to do reset after show the Winner, you should add additional parameter to reset method, or create separated method for post-winning reset.
Regular answer:
Your functions keep calling each other. Thats probably where the overflow is coming from.
From the functions given I'm unable to deduce exactly what your program flow would look like so I can't provide you with a fix which will do what you expect it to do.
To get rid of the overflow however simply remove either the call to "TheWinner" from "resetShiruken" or remove the call to "resetShiruken" from "TheWineer".
I suspect you should remove the latter.
Code style:
You're mixing upercase and lowercase function names which is a bad habit.
The default case for method names is "PascalCase" in c# (as depicted by the documentation).
I want to do
gradually stop car animation as it collildes with another car
gradually speed up car animation as it exit the collider
And I have two ways to acheive this thing(means to run my logic in).
Update
Co-routine
for coroutine I used this
IEnumerator IncreaseSpeedGradually1(AnimationControlSpeed lastGOHitScript)
{
//stop if decrease speed in progress
StopCoroutine("DecreaseSpeedGradually");
float decrementValue = ((lastHitVehicleSpeed / 2) * 2);
while (lastGOHitScript.Speed <= lastHitVehicleSpeed)
{
lastGOHitScript.Speed += decrementValue * Time.deltaTime;
yield return 0;
}
//setting speed to the last speed
lastGOHitScript.Speed = lastGOHitScript.iniSpeeed;
}
While for update I just make this criteria:
if (carAnimState == carAnimationState.starting)
{
carAnimState = carAnimationState.running;
}
if (carAnimState == carAnimationState.stoping)
{
carAnimState = carAnimationState.running;
}
These two ways I know but i want to ask that which is right way to do this job? to slow down animation speed and hence get my objective? I guess corroutine later can be problematic in my game and what are the performance concerns?
Not perfectly clear what your goal exactly is. What you describe is clear, but the two code snippets you posted do completely different things. BUT, basically, for something this small I would use Update() as it's easier to debug if something blows up and there's nothing -theoretically- in your code that wishes "threading" / "side tasking" (which coroutines are for, basically: do something -most probably a side task- async).
As a side note, the code in your Update() can be optimized a little so it will look something like this:
if (carAnimState == carAnimationState.starting) {
carAnimState = carAnimationState.running;
} else if (carAnimState == carAnimationState.stoping) {
carAnimState = carAnimationState.running;
} //this way the 2nd "if" won't be unnecessarily evaluated when animstate was .starting
I'd also add a method instead and call that from Update(). The pre-compiler will inline it most probably (cannot be forced in Unity) and your code is more readable.
Quick disclaimer: I am not a very advanced C# user, being more accustomed to languages like python, so i apologise if the answer is right in front of me.
I've been making a little game for the Google Cardboard, Using the demo scene as a base. I've got some code that checks for a "Trigger Pull" and then should translate the Cardboard cameras up by 10 units.
//Checks For Magnet Trigger
if (Cardboard.SDK.Triggered)
{
//moves player up at a rate of 10u/s
transform.Translate(Vector3.up * 10);
Debug.Log("Triggered_Head");
//Tell Cardboard to maintain new position
}
Currently this works really well for detecting the magnet pull, and it does translate the cardboard. The problem is that almost immediately after translation the cardboard gets teleported back to the base position.
Currently i have this code inserted into the UpdateHead() method (?) from CardboardHead.cs, like so:
// Compute new head pose.
private void UpdateHead() {
if (updated) { // Only one update per frame, please.
return;
}
updated = true;
Cardboard.SDK.UpdateState();
if (trackRotation) {
var rot = Cardboard.SDK.HeadPose.Orientation;
if (target == null) {
transform.localRotation = rot;
} else {
transform.rotation = target.rotation * rot;
}
}
if (trackPosition) {
Vector3 pos = Cardboard.SDK.HeadPose.Position;
if (target == null) {
transform.localPosition = pos;
}
else {
transform.position = target.position + target.rotation * pos;
}
//Checks For Magnet Trigger
if (Cardboard.SDK.Triggered)
{
//moves player up at a rate of 10u/s
transform.Translate(Vector3.up * 10);
Debug.Log("Triggered_Head");
//Tell Cardboard to maintain new position
}
}
if (OnHeadUpdated != null) {
OnHeadUpdated(gameObject);
}
}
Doing this does everything right, but the location is reverted almost instantly (in the next frame i assume). So my question is: How do i make the transform stick, and is there a better way for me to handle this?
Alright, i figured out how to handle movement, and I'm posting the solution here for anyone in the future who can't figure it out. Quick note: I did update to the latest version of the SDK, although that shouldn't make a difference, except for naming.
So, Step 1:
Create an object to use as your controller. I just used one of the prototyping cubes from an asset pack, but whatever will work (empty objects would be best).
Place this object more or less in the center-point of the two cameras.
Parent your GvrMain object to the controller object (by dragging it onto the controller object) as well as any other components you want to move with the player (Guns, GUI's, etc)
Step 2:
Create a script for the controller object.
In the Update() method, add the lines:
if (GvrViewer.Instance.Triggered)
{
transform.Translate(Vector3.up)
}
for older versions replace GvrViewer.Instance with Cardboard.SDK
Customise your movement to your liking, any normal unity functions should work.
Some shortcomings:
You have to repeatedly press the trigger, using while() seems to break unity. This seems pretty easy to fix
The code snippet instantly translates up by 1. Not sure how to do it as a steady acceleration.
Hopefully this helps anyone who had my problem.
So basically I have an enemy that, once you get close enough, will chase you around and try to attack you. Once you get far enough away, it will run back to where it was originally.
The issue I'm having is that once it runs back to where its starting point is, but doesn't quite hit the point, and keeps falling over and trying to get to that exact point..
Here's what I have for code for that section:
if (inAggroRange()) {
//In aggro range
if (!inAttackRange()) {
chase();
} else {
animation.CrossFade(animationAttack.name);
attack();
if (animation[animationAttack.name].time > 0.9 * animation[animationAttack.name].length) {
impacted = false;
}
}
} else if (!inAggroRange()){
//Go back to home position
if (!(transform.position == enemyHomePosition)) {
animation.CrossFade(animationRun.name);
transform.LookAt(enemyHomePosition);
controller.SimpleMove(transform.forward * speed);
} else {
//Enemy is at home position
animation.CrossFade(animationIdle.name);
}
}
just use
private readonly float maxDistanceToHomePosition = 0.3f; // change this value as you like
...
if((transform.position - enemyHomePosition).magnitude > maxDistanceToHomePosition)
{
...
}
...
the way you are doing it, the enemy is trying to reach one specific point but without a megaton of luck it will always be just a bit over, then turn around and try again. Much like a golf player trying to hit the whole but alyways hitting to hard.
edit: also think about using != for 'not equal', in my opinion thats a bit easier to read