Search Unity

Moving the points of a polygon collider to form a wave surface 2D

Discussion in '2D' started by gangafinti, Mar 14, 2018.

  1. gangafinti

    gangafinti

    Joined:
    Jun 13, 2013
    Posts:
    19
    I wrote this code to get the top points of a polygon collider and move those points. I can get the points but I can't move them, wich is wierd because I can move them if I edit them in the inspector(while playing). What am I doing wrong? Is there another approach to this? The end goal is to have a 2d water surface where a surfer can surf on. I put in the OnDrawGizmos to see if I truly get the right points.

    https://snag.gy/fwsvA4.jpg

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using System.Linq;

    [RequireComponent(typeof(PolygonCollider2D))]
    public class Wave2 : MonoBehaviour {

    private PolygonCollider2D polygonCollider2D;
    private Mesh colliderMesh;
    private int[] indexesOfTopPoints;
    private AnimationCurve curve;

    private void Awake()
    {
    polygonCollider2D = GetComponent<PolygonCollider2D>();
    float lowestY = polygonCollider2D.points.Min(x => x.y);

    indexesOfTopPoints = polygonCollider2D.points
    .Select((p, i) => new { Point = p, Index = i })
    .Where(x => x.Point.y > lowestY)
    .Select(x => x.Index)
    .ToArray();

    for (int i = 0; i < indexesOfTopPoints.Length; i++)
    {
    polygonCollider2D.points[indexesOfTopPoints[i]] += new Vector2(0, 50);

    }
    }

    private void OnDrawGizmos()
    {
    Gizmos.color = Color.red;
    for (int i = 0; i < indexesOfTopPoints.Length; i++)
    {
    Gizmos.DrawSphere(polygonCollider2D.points[indexesOfTopPoints[i]], 0.1f);

    }
    }
    }