Hello,
I´m writing a moving-sript. An object is moving from A to B and back. But I wanted, that the object should move only twenty times and NOT in loop-function.
That means im math-term:
1x = A–>B + B–>A
20x = (A–>B + B–>A)x20
I know, how to write a moving-script with loop-function. But I don´t know, how to write moving-script, where a object is moved with certain times between two object.
Has someone a easy script for that?
1 Answer
1
There are many ways to get things to oscillate, so without more criteria, it is hard to give a specific answer. Things like:
- Does it need to collide?
- Are the positions taken from other objects?
- Is it triggered multiple times?
- Does it need to be interrupted?
- Does the movement need to feel natural (like the swing of a pendulum)?
- Etc.
Also asking for a script, especially in the absence of any coding effort on your part, often results in either questions being rejected in the moderation queue, or down votes.
Whenever something oscillates, my first thoughts are Mathf.PingPong() and Mathf.Sin(). Here is an example script:
#pragma strict
var posA = Vector3(-5,0,0);
var posB = Vector3(5,0,0);
var speed = 1.0;
var times = 20.0;
function Start() { ManyTimes(); }
function ManyTimes() {
var timer = 0.0;
while (timer < times * 2.0) {
transform.position = Vector3.Lerp(posA, posB, Mathf.PingPong(timer, 1.0));
timer += Time.deltaTime * speed;
yield;
}
}
Why don't you want to use loops? That is actually the perfect scenary for a loop clause.
– dmg0600Why I don´t want to use loops? Because endless loops, which I persume that you mean that, its easy to write and most common asked questions here. My question isn´t at the moment for using it in a game, its more for learning JavaScript itself (but with helping).
– TemplateRLoops aren't all endless... You're the one who writes the condition at which it will end... for example : for (int i = 0; i < 20; i++) { //Do something } This loop will exit after 20 loops (last iteration at i = 19) This isn't endless. As a precision, I was writing in C#. But the differences are minor. same concept.
– jokim