ステージを回転させてボールをゴールに入れるゲームを作っているところですが、
ステージを回転させるとスムーズに動く黒い障害物が(恐らくVector3のせいで) 沈んだり浮いたりします。
これに対する解決策、つまりステージと障害物の間の距離を固定する方法
(ステージを回転させても障害物が浮いたり沈んだりしない)が知りたいです。
障害物の移動
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RepeatMovementOfShark : MonoBehaviour
{
public float zSpeed = -1.0f; //units per second, set negative to go the other way
public float zDistance = 10.0f; //distance to travel before turning back
public bool FreezeY = false;
private Vector3 startPos;
float way = 1.0f;
float zPos = 0.0f;
float zPosPrev = 0.0f;
void Start()
{
//save start position
startPos = transform.position;
}
void Update()
{
Vector3 currentPos = transform.position;
//advance position
zPosPrev = zPos;
zPos += way * zSpeed * Time.deltaTime;
//handle turn around at end
if (Mathf.Abs(zPos) > zDistance)
{
way = -way;
zPos = zPosPrev;
}
//handle turn around at start
if ((zPos < 0.0f && zPosPrev > 0.0f) || (zPosPrev < 0.0f && zPos > 0.0f))
{
way = -way;
zPos = zPosPrev;
}
if (FreezeY)
{
currentPos.y = startPos.y;
}
//set new position
transform.position = new Vector3(transform.position.x, transform.position.y, startPos.z + zPos);
}
}
ステージの回転
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// Transform.rotation example.
// Rotate a GameObject using a Quaternion.
// Tilt the cube using the arrow keys. When the arrow keys are released
// the cube will be rotated back to the center using Slerp.
public class StageRotation : MonoBehaviour
{
public float smooth = 5.0f;
public float tiltAngle = 60.0f;
void Update()
{
// Smoothly tilts a transform towards a target rotation.
float tiltAroundZ = Input.GetAxis("Horizontal") * tiltAngle * -1;
float tiltAroundX = Input.GetAxis("Vertical") * tiltAngle * -1;
// Rotate the cube by converting the angles into a quaternion.
Quaternion target = Quaternion.Euler(tiltAroundX, 0, tiltAroundZ);
// Dampen towards the target rotation
transform.rotation = Quaternion.Slerp(transform.rotation, target, Time.deltaTime * smooth);
}
}
Attached Files: