How moving object only twenty times?

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?

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;
	}
}