- Home /
Question by
digiumbri · Jul 24, 2020 at 09:43 PM ·
c#playerunity 2dmovinggameobject
I'm having a weird problem with my Player touching a moving object and he gets stuck within the moving object script?
So when my player touches my moving object he gets put under the object in the hierarchy and starts moving with the object. I can't figure out the solution to the current issue. This is the script for my moving object.
{
[SerializeField] Vector3 movementVector = new Vector3(0f, 0f, 0f);
[SerializeField] float period = 0f;
[Range(0, 1)] [SerializeField] float movementFactor;
Vector3 startingPos;
private bool moving;
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Player")
{
moving = true;
collision.collider.transform.SetParent(transform);
}
}
// Start is called before the first frame update
void Start()
{
startingPos = transform.position;
}
// Update is called once per frame
void Update()
{
if (period <= Mathf.Epsilon) { return; }
float cycles = Time.time / period;
const float tau = Mathf.PI * 2f;
float rawSinWave = Mathf.Sin(cycles * tau);
movementFactor = rawSinWave / 2f + 0.5f;
Vector3 offset = movementFactor * movementVector;
transform.position = startingPos + offset;
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613004008im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers