Amount of distance to travel when a key is pressed - unity3d

In code below, I want to manage the amount of distance to travel when a left arrow key is pressed depending upon if it's half way down or not.
The object moves all the way to left on very first press instead of movement to be divided in 3 or 4 parts depending on the above mentioned condition, where am I doing it wrong?
var diff = Mathf.Abs(this.transform.position.x - r.renderer.bounds.min.x);
print("diff" + diff);
var lessdistancetotravel = diff/4;
var moredistancetotravel = diff/3;
if(this.transform.position.x > half)
{
print ("greater than half while moving left");
print("currentpos" + this.transform.position.x); //gives 0.6
print("moredistance " + moredistancetotravel);//gives 0.69
this.transform.position = new Vector3 (this.transform.position.x - moredistancetotravel,
this.transform.position.y,
this.transform.position.z);
print("updated" + (this.transform.position.x - moredistancetotravel)); //gives -0.78,How come?
}

Since you can't check how far down a key is pressed, as Jerdak mentioned in the comments. I would then just measure how long a key has been pressed. You can start counting how long the key has been down and stop counting once it is released. Then you can use that time to determine how far your object can travel.
How to count the time the key has been pressed:
float count = 0.0f;
void Update()
{
if(Input.GetKey("a"))
count += Time.deltaTime;
else if(Input.GetKeyUp("a"))
count = 0.0f;
}
Code resets count back to 0 once you release the key.

Related

I am trying to make a timer in unity for reload using Time.deltaTime. Anyone know why this isn't working?

Here is the code, I'm not sure why this isn't working. I've done things very simmilar before.
float limit = 1f;
float i = 0f;
if(hasResetReload == true && i < limit)
{
i += Time.deltaTime;
}
else if(i == limit)
{
hasResetReload = false;
anim.SetBool("Reload", false);
}
When you write i += Time.deltaTime;, it will assign a 7 digit long float value to i. Now, when you say i == limit, it will have to match all 7 digits on both float which is almost impossible and never become true. You have to use i >= limit. So, it will become true whenever i become greater than or equal to limit.

How to set specific angle between 2 game objects in unity

SCENARIO
I am creating an app where I have to show chemical bonding between atoms(which are game objects). I am using Leap motion hands for spawning and making atoms collide to form molecules. Now the bond between atoms are made using cylinder game objects.
Also when bond(cylinder) is spawned correctly it is joined to atoms' game objects using fixed joints.
All these things are working correctly and as intended.
PROBLEM:
As one atom can form bond with multiple atoms so I want to maintain a certain angle between each bonded atoms.(for eg. in chemistry CH4 molecule's atoms are separated by around 105 degrees).
So I want to achieve the same effect in my app too by separating each atom in molecule by certain angle.
What I currently have only create molecule properly but doesn't have anything to separate according to angle.
This is what I am doing currently.
private IEnumerator SetAtomPosition(Transform atomOne, Transform atomTwo, Transform cylinder)
{
cylinder.gameObject.GetComponent<Rigidbody>().isKinematic = true;
while (Vector3.Distance(atomOne.position, atomTwo.position) > atomDistance)
{
atomTwo.position = Vector3.MoveTowards(atomTwo.position, atomOne.position, Time.deltaTime * 0.1f);
yield return 0;
}
while (Vector3.Distance(atomOne.position, atomTwo.position) < atomDistance)
{
atomTwo.position = Vector3.MoveTowards(atomTwo.position, -atomTwo.forward * 1000f, Time.deltaTime * 0.1f);
yield return 0;
}
cylinder.transform.position = (atomTwo.position - atomOne.position) / 2.0f + atomOne.position;
cylinder.transform.rotation = Quaternion.FromToRotation(Vector3.up, atomTwo.position - atomOne.position);
#region JoinAtoms
cylinder.gameObject.AddComponent<FixedJoint>();
cylinder.gameObject.AddComponent<FixedJoint>();
var cylinderJoints = cylinder.GetComponents<FixedJoint>();
cylinderJoints[0].connectedBody = atomOne.GetComponent<Rigidbody>();
atomOne.GetComponent<Atom>().joint = cylinderJoints[0];
//cylinderJoints[0].breakForce = breakForce;
cylinderJoints[1].connectedBody = atomTwo.GetComponent<Rigidbody>();
atomTwo.GetComponent<Atom>().joint = cylinderJoints[1];
KinematicToggle(cylinder.gameObject);
cylinder.GetComponent<Rigidbody>().mass = 10f;
#endregion
yield return null;
}
And this is what it looks like currently
I want those 4 white spheres to be aligned around black sphere(Carbon atom).
What I want is something similar to this image.

Input Interface not being called on scene change in Unity

Unity 5.3.4 Version
My problem is when I am moving my character with 2 keys (diagonal motion) and I change the scene the character will cease to move in that direction and only move in the direction of the last key I pressed.
Example : I am moving up left (I first press the left key and then up key). I then get transferred to another scene and (I am still holding down the up and left key) my character will end up only moving up until I let go of the left key and press it again.
void Update(){
// Get a -1, 0 or 1.
moveHorizontal = Input.GetAxisRaw ("Horizontal");
moveVertical = Input.GetAxisRaw ("Vertical");
// Check what is actually being called.
print ("up : " + Input.GetKey("w"));
print ("down : " + Input.GetKey("s"));
print ("left : " + Input.GetKey("a"));
print ("right : " + Input.GetKey("d"));
}
Is there a setting I can check to make multiple keys transfer over or is this a bug in Unity because even though I am holding down the left key the print statement will show false for 'left'.

How do you pause, stop and reset an AUFilePlayer?

I am working with core audio using an AUFilePlayer to load a few mp3s into a mixer unit, everything plays great however I am unable to pause the music or rewind the music back to the start. I tried Starting and stopping the AudioGraph, but once the playback is stopped, I can't get it to restart. I also tried using AudioUnitSetProperty to set the file playback to 0
i.e something along these lines:
ScheduledAudioFileRegion rgn;
memset (&rgn.mTimeStamp, 0, sizeof(rgn.mTimeStamp));
rgn.mTimeStamp.mFlags = kAudioTimeStampSampleTimeValid;
rgn.mTimeStamp.mSampleTime = 0;
rgn.mCompletionProc = NULL;
rgn.mCompletionProcUserData = NULL;
rgn.mAudioFile = inputFile;
rgn.mLoopCount = 1;
rgn.mStartFrame = 0;
rgn.mFramesToPlay = nPackets * inputFormat.mFramesPerPacket;
AudioUnitSetProperty(fileUnit, kAudioUnitProperty_ScheduledFileRegion,
kAudioUnitScope_Global, 0,&rgn, sizeof(rgn));
Any suggestions?
In case anyone else is dealing with a similar issue, which cost me several hours searching on google, here's what I've discovered on how to specifically retrieve and set the playhead.
To get the playhead from an AUFilePlayer unit:
AudioTimeStamp timestamp;
UInt32 size = sizeof(timestamp);
err = AudioUnitGetProperty(unit, kAudioUnitProperty_CurrentPlayTime, kAudioUnitScope_Global, 0, &timestamp, &size);
The timestamp.mSampleTime is the current playhead for that file. Cast mSampleTime to a float or a double and divide by the file's sample rate to convert to seconds.
For restarting the AUFilePlayer's playhead, I had a more complex scenario where multiple AUFilePlayers pass through a mixer and can be scheduled at different times, multiple times, and with varying loop counts. This is a real-world scenario, and getting them all to restart at the correct time took a little bit of code.
There are four scenarios for each AUFilePlayer and it's schedule:
The playhead is at the beginning, so can be scheduled normally.
The playhead is past the item's duration, and doesn't need to be scheduled at all.
The playhead is before the item has started, so the start time can be moved up.
The playhead is in the middle of playing an item, so the region playing within the file needs to be adjusted, and remaining loops need to be scheduled separately (so they play in full).
Here is some code which demonstrates this (some external structures are from my own code and not Core Audio, but the mechanism should be clear):
// Add each region
for(int iItem = 0; iItem < schedule.items.count; iItem++) {
AEFileScheduleItem *scheduleItem = [schedule.items objectAtIndex:iItem];
// Setup the region
ScheduledAudioFileRegion region;
[file setRegion:&region schedule:scheduleItem];
// Compute where we are at in it
float playheadTime = schedule.playhead / file.sampleRate;
float endOfItem = scheduleItem.startTime + (file.duration*(1+scheduleItem.loopCount));
// There are four scenarios:
// 1. The playhead is -1
// In this case, we're all done
if(schedule.playhead == -1) {
}
// 2. The playhead is past the item start time and duration*loopCount
// In this case, just ignore it and move on
else if(playheadTime > endOfItem) {
continue;
}
// 3. The playhead is less than or equal to the start time
// In this case, simply subtract the playhead from the start time
else if(playheadTime <= scheduleItem.startTime) {
region.mTimeStamp.mSampleTime -= schedule.playhead;
}
// 4. The playhead is in the middle of the file duration*loopCount
// In this case, set the start time to zero, adjust the loopCount
// startFrame and framesToPlay
else {
// First remove the start time
region.mStartFrame = 0;
double offsetTime = playheadTime - scheduleItem.startTime;
// Next, take out any expired loops
int loopsExpired = floor(offsetTime/file.duration);
int fullLoops = region.mLoopCount - loopsExpired;
region.mLoopCount = 0;
offsetTime -= (loopsExpired * file.duration);
// Then, adjust this segment of a loop accordingly
region.mStartFrame = offsetTime * file.sampleRate;
region.mFramesToPlay = region.mFramesToPlay - region.mStartFrame;
// Finally, schedule any remaining loops separately
if(fullLoops > 0) {
ScheduledAudioFileRegion loops;
[file setRegion:&loops schedule:scheduleItem];
loops.mStartFrame = region.mFramesToPlay;
loops.mLoopCount = fullLoops-1;
if(![super.errors check:AudioUnitSetProperty(unit, kAudioUnitProperty_ScheduledFileRegion, kAudioUnitScope_Global, 0, &region, sizeof(region))
location:#"AudioUnitSetProperty(ScheduledFileRegion)"])
return false;
}
}
// Set the region
if(![super.errors check:AudioUnitSetProperty(unit, kAudioUnitProperty_ScheduledFileRegion, kAudioUnitScope_Global, 0, &region, sizeof(region))
location:#"AudioUnitSetProperty(ScheduledFileRegion)"])
return false;
}
I figured it out. In case any of you ever run into the same problem, here was my solution:
On startup, I initialize the AUGraph with an array of file player audio units. I set the play head of each track in the file player audio unit array to zero.
On “pause” , first I stop the AuGraph. Then I loop through the array of file player audio units and capture the current playhead position. Each time the pause button is pressed, I make sure I add the new current playhead position to the old playhead position to get its true position.
When the user hits play, I re initialize the AuGraph just as if I was starting the app for the very first time, only I set the playhead to the number I stored when the user hit “pause” instead of telling it to play at the start of the file.
If the user clicks stop, I set the stored playhead position to zero and then stop the AuGraph.

how to set the break point for UISlider?

I have two UISlider called slider1
slider1.minimumValue = 0; slider1.maximumValue = 100;
i want to set a break point,such as 60, if the slider1 move to 60 from 0(left) to 60(right), it will stop here the thumb can not move to right, but it can move to left. so how can i do?
please take a look the following code, it doesn't work, thanks
-(IBAction)s1valuechanged:(id)sender{
if ((int)slider1.value > 60) {
slider1.userInteractionEnabled = FALSE;
}
else{
slider1.userInteractionEnabled =TRUE;
}
}
I'm having a bit of trouble understanding your question, so I'm going to assume that your slider looks like the following, and you want to prevent the user from moving the slider to a value greater than 60:
0 ----------60------100
|---valid----|-invalid-|
All you would need is the following:
-(IBAction)s1valuechanged:(id)sender{
if ((int)slider1.value > 60) {
slider.value = 60;
}
}
In other words, whenever the user tries to move the slider to a value greater than 60, move the slider back to 60.