Reputation: 379
Recently, I am working on a roller ball game ( just for education purpose). And mainly I am working on replay script. That means as long as I click replay button, player previous movement shall be known. It was supposed to be similar to prince of persia rewind feature. But I have done something wrong.
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
public class Player : MonoBehaviour {
private const int buffersize = 1000;
private MyKeyFrame[] playerskeyframe = new MyKeyFrame [buffersize];
private Rigidbody rigidbody;
void Start () {
rigidbody = GetComponent<Rigidbody> ();
}
void Update () {
if (GameManager.Recording == true) {
Record ();
} else {
PlayBack ();
}
}
void PlayBack(){
rigidbody.isKinematic = true;
int frame = Time.frameCount % buffersize;
this.transform.position = playerskeyframe [frame].Position;
this.transform.rotation = playerskeyframe [frame].rotation;
}
void Record(){
Debug.Log (Time.frameCount % buffersize);
rigidbody.isKinematic = false;
int frame = Time.frameCount % buffersize;
float time = Time.time;
playerskeyframe [frame] = new MyKeyFrame (time, this.transform.position, this.transform.rotation);
}
}
public struct MyKeyFrame {
public float frametime;
public Vector3 Position;
public Quaternion rotation;
public MyKeyFrame (float atime,Vector3 apos, Quaternion arotation){
frametime = atime;
Position = apos;
rotation = arotation;
}
}
Edit:- What does not work in my script. Unless frame reaches the buffersize which is 1000 Playback function does not work as expected. That means without completing a loop it does not jump to playback from recording. Thank you for your time and consideration.
Upvotes: 1
Views: 374
Reputation: 171
I would suggest switching to Queue data type. just add a keyframe each frame you record. Something gets screwy with your array when you use a % of the frame count. you probably overwrite good valid data like so.
in the record function :
keyFrameQueue.Enqueue(new MyKeyFrame
(
time, this.transform.position, this.transform.rotation
);
and in the playback just put this in the update to happen every frame:
if(keyFrameQueue.Count > 0)
{
MyKeyFrame = keyFrameQueue.Dequeue();
this.transform.position = MyKeyFrame.Position;
this.transform.rotation = MyKeyFrame.rotation;
}
Upvotes: 1