using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using AGXUnity;

/// <summary>
/// Set the Surface velocity on a shape.
/// Also Animates the texture in the same speed
/// </summary>
public class SurfaceVelocity : ScriptComponent
{

  public float speed = 0.1f;
  private AGXUnity.Collide.Shape m_shape;

  private Material m_material;

  protected override bool Initialize()
  {
    // We are assuming this is a box further down
    m_shape = GetComponentInChildren<AGXUnity.Collide.Shape>();
    Debug.Assert(m_shape!= null);

    // That has one material
    m_material = GetComponentInChildren<Renderer>().material;
    Debug.Assert(m_material != null);

    return base.Initialize();
  }

  void Update()
  {
    // We are assuming the belt should move along Y (local coord).
    // Get the Tiling.
    var scale = m_material.mainTextureScale;
    var offset = Time.time * new Vector2(0, scale.y*speed);
    var box = m_shape.NativeShape.asBox();
    float length = 1.0f;

    if (box != null )
    {
      var size = box.getHalfExtents();
      length = (float)size.z*2.0f;
    }
    // Did not get a 100% match. Belt texture should move 5% faster...
    m_material.mainTextureOffset = 1.05f*offset/length;

    // Set the speed of the conveyorbelt.
    // The z axis for the box is along the conveyorbelt.
    m_shape.NativeGeometry.setSurfaceVelocity(new agx.Vec3f(0, 0, speed));
  }




}
