- Home /
ZigZag Movement whilst Moving Forward?
Hi Guys,
Ive got an object that constantly moves forward (be it, at a vector or target) Now, i want its movement to be going in a ZIGZAG, forward. Essentially i would end up with a snake like movement, an S shape.
Problem is, with the coding ive used and itween events, it appears there is no easy logical way to update the position for two different movements.
Can anyone provide some insight on this?
Thanks
Thanks mate, although im not sure how to make that sine movement go towards a vector or object.
i'll play around with it some more
Answer by jakirhossain · Feb 03, 2020 at 05:35 PM
If anyone looking for new version:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class VirusMove : MonoBehaviour
{
public float speed = 2;
float frequency = 10.0f; // Speed of sine movement
float magnitude = 0.5f; // Size of sine movement
Vector3 pos;
Vector3 axis;
private void Awake()
{
pos = transform.position;
axis = transform.up;
}
void Update()
{
pos += Vector3.left * Time.deltaTime * speed;
transform.position = pos + axis * Mathf.Sin(Time.time * frequency) * magnitude;
}
Answer by asadalichoudhary · Apr 20, 2020 at 08:51 AM
Here I have found a nice & detailed article on the zigzag movement of game objects.
Answer by Trouch · Mar 15, 2015 at 10:28 AM
Hey guys, not sure if this will help anyone, but here is the code im personally using so far. Theres still a problem with origin positions/angles, but its still alright.
(made some minor edits to the code within the link savlon provided)
#pragma strict
var MoveSpeed = 5.0f;
var frequency = 20.0f; // Speed of sine movement
var magnitude = 0.5f; // Size of sine movement
var axis : Vector3;
var pos : Vector3;
var player : Transform;
function Start () {
transform.LookAt(player);
pos = transform.position;
//DestroyObject(gameObject, 1.0f);
axis = transform.up; // May or may not be the axis you want
}
function Update () {
pos += transform.forward * Time.deltaTime * MoveSpeed;
transform.position = pos + axis * Mathf.Sin (Time.time * frequency) * magnitude;
}