2

Как в Unity3D, для 2D игры рисовать произвольные линии с помощью касаний (правда мне кажется, что с мышой все так же).

Например, я нажал на экран, нарисовал произвольный круг, после чего палец убрал и этот объект создался, и уже по возможности добавился компонент Rigidbody2D, и верная маска коллизий, что бы не квадрат был, который по краях ограничивает область, а крива. И на сколько я знаю, Rigidbody и MeshCollider вместе не работают(но это в 3D).

3
  • Можно использовать Line Renderer для рисования линий docs.unity3d.com/ru/current/Manual/class-LineRenderer.html .......зачем вам коллиззи и Rigidbody? что хотите добиться в итоге? 24 мар 2016 в 21:32
  • @АлексейШиманский а можно ли на эту линию адекватно повесить rigidbody и коллайдер? 24 мар 2016 в 21:34
  • Сомневаюсь.... линия это множество точек. Коллайдер если вешать, то не на конкретную линию, а на маленькие промежутки между точками, каждые (к примеру) две штуки...... Вообще зависит от задачи.. Если наносить damage то не обязательно даже коллайдеры вешать 24 мар 2016 в 21:39

1 ответ 1

1

Линию от точки к точке рисуем при помощи двух треугольников, создаем MeshRenderer и для него создаем последовательно от точки к точке линии, дополняя. Код из нашего проекта , брал пример из сети, рисовал 2D графики. Для физики можно повешать потом на объект Rigidbody2D и попробовать либо PolygonCollider2D, либо придется на каждую линию BoxCollider2D вешать.

Вот код класса рисующего линии по точкам добавляемым в процессе рисования

using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using ThreadPriority = System.Threading.ThreadPriority;

[RequireComponent (typeof (MeshFilter))]

/// <summary>
/// Generates a trail that is always facing upwards using the scriptable mesh interface.
/// vertex colors and uv's are generated similar to the builtin Trail Renderer.
/// To use it
/// 1. create an empty game object
/// 2. attach this script and a MeshRenderer
/// 3. Then assign a particle material to the mesh renderer
/// </summary>
public class Line : MonoBehaviour {

public float height = 2.0f;
public float time = 2.0f;
public bool localDraw = false;
public float minDistance = 0.1f;

public Color startColor = Color.white;
public Color endColor = new Color (1, 1, 1, 0);
[HideInInspector]
public Mesh mesh;

protected List<TrailSection> sections;
protected TrailSection lastSection; 

private float testNormal = 1.0f;
private Transform cachedTransform;
private Vector3[] vertices;
private Color[] colors;
private Vector2[] uv;
private Vector3[] normals;
private int[] triangles;
private bool needUpdate = false;
private Thread threadCalcMesh;

private object lockOn = new object();


// Use this for initialization
protected virtual void Awake () {
    // Rebuild the mesh
    cachedTransform = transform;
    mesh = GetComponent<MeshFilter>().mesh;
    Clear();
    /*AddPoint(new Vector3(0.0f,0.0f));
    AddPoint(new Vector3(5.0f,4.0f));
    AddPoint(new Vector3(8.0f,2.0f));
    AddPoint(new Vector3(10.0f,12.0f));
        ReDraw();*/
}

virtual public void Clear() {
    mesh.Clear();
    sections = new List<TrailSection>();
    lastSection = null;
    transform.localScale = Vector3.one;
}

// Update is called once per frame
void Update () {
    /*if (Input.GetKeyDown(KeyCode.Space)){
    //  this.AddPoint(Input.mousePosition);
        testNormal *= -1;
        Sender.SendEventHierarchy(EventDiagram.UPDATE, this);
    }*/
    if (needUpdate)
    {
        //if (Monitor.TryEnter(lockOn))
        lock (lockOn)
        {
            mesh.Clear();
            mesh.vertices = vertices;
            mesh.colors = colors;
            mesh.uv = uv;
            mesh.triangles = triangles;
            mesh.normals = normals;
            needUpdate = false;
        }
    }
}

virtual public void ReDraw(){
    MeshUpdate();
}
virtual protected void OnEnable(){
    Sender.SendEventHierarchy(EventDiagram.UPDATE, this);
}

virtual protected void OnDisable(){
}

virtual public void AddPoint(Vector3    position){

    Vector3 vDistance = Vector3.zero;
    if (lastSection != null){
        vDistance = lastSection.point - position;
        vDistance.Scale(transform.localScale);
    }
    // Add a new trail section
    if (lastSection == null || vDistance.sqrMagnitude > minDistance * minDistance)
    {
        var section = new TrailSection();
        section.point = position;
        if (localDraw)
            section.forwardDir = Vector3.forward;
        else
            section.forwardDir = transform.TransformDirection(Vector3.forward);
        sections.Add(section); 
        lastSection = section;
    }
    updateAfterAddPoint();
}

virtual protected void updateAfterAddPoint(){
}

public void MeshUpdate () {

// We need at least 2 sections to create the line
    if (sections.Count < 2)
        return;

    if (threadCalcMesh != null && threadCalcMesh.IsAlive)
        return;

    threadCalcMesh = new Thread(recalcMesh);
    threadCalcMesh.IsBackground = true;
    threadCalcMesh.Priority = ThreadPriority.BelowNormal;

    threadCalcMesh.Start(getVectorScale());
    //thread.Join();

}

void recalcMesh(object scaleV)
{
    int sectCount = sections.Count;

    int vert = (sectCount - 1) * 4;
    Vector3[] vertices = new Vector3[vert];
    Color[] colors = new Color[vert];
    Vector2[] uv = new Vector2[vert];
    Vector3[] normals = new Vector3[vert];

    TrailSection previousSection;// = sections[0];
    TrailSection currentSection = sections[0];
    TrailSection nextSection;// = sections[0];

    // Use matrix instead of transform.TransformPoint for performance reasons
    //Matrix4x4 localSpaceTransform = transform.worldToLocalMatrix;
    Vector3 upDir, upDirCross;
    Vector3 vec;
    Vector3 vec1, vec2, vecCross;
    int idx;

    Vector3 vectorScale = (Vector3) scaleV;

    // Generate vertex, uv and colors
    for (int i = 1; i < sectCount; i++)
    {
        previousSection = currentSection;
        currentSection = sections[i];
        if (i < sectCount - 1)
            nextSection = sections[i + 1];
        else
            nextSection = currentSection;
        // Calculate u for texture uv and color interpolation
        vec = currentSection.point - previousSection.point;

        vec1 = currentSection.point - previousSection.point;
        vec2 = currentSection.point - nextSection.point;

        vecCross = Vector3.Cross(vec1, vec2);

        // Calculate upwards direction
        upDir = Vector3.Cross(-vec, Vector3.forward);
        upDir.Normalize();
        upDir *= height / 2;
        upDir = Vector3.Scale(upDir, vectorScale);

        idx = (i - 1) * 4;

        if (i == 1)
        {
            vertices[idx + 0] = previousSection.point - upDir;
            vertices[idx + 1] = previousSection.point + upDir;
        }
        else
        {
            vertices[idx + 0] = previousSection.crossUp ? previousSection.point - upDir : vertices[idx - 2];
            vertices[idx + 1] = !previousSection.crossUp ? previousSection.point + upDir : vertices[idx - 1]; ;
        }

        if (i + 1 == sectCount)
        {
            vertices[idx + 2] = currentSection.point - upDir;
            vertices[idx + 3] = currentSection.point + upDir;
        }
        else
        {
            // ищем точку пересечения секции со следующей секцией
            currentSection.crossUp = Vector3.Dot(vecCross, currentSection.forwardDir) < 0;

            upDirCross = Vector3.Cross(vec2.normalized - vec1.normalized, currentSection.forwardDir);
            //upDirCross = vec1 + vec2;
            upDirCross.Normalize();
            //float sinb = Vector3.Cross(vec1.normalized, vec2.normalized).magnitude; 
            upDirCross *= height / 2;// / sinb;
            upDirCross = Vector3.Scale(upDirCross, vectorScale);

            // Поиск точки как сумму векторов
            /*vec1.Normalize();
            vec1 *= height / 2;
            vec1 = Vector3.Scale(vec1, vectorScale);
            vec2.Normalize();
            vec2 *= height / 2;
            vec2 = Vector3.Scale(vec2, vectorScale);
            upDirCross = -vec1 - vec2;*/

            if (currentSection.crossUp)
            {
                vertices[idx + 2] = currentSection.point - upDir;
                vertices[idx + 3] = currentSection.point + upDirCross;
            }
            else
            {
                vertices[idx + 2] = currentSection.point - upDirCross;
                vertices[idx + 3] = currentSection.point + upDir;
            }
        }

        float u = 0.0f;

        u = Mathf.Clamp01((float)(i - 1) / sectCount);
        uv[idx + 0] = new Vector2(u, 0);
        uv[idx + 1] = new Vector2(u, 1);
        u = Mathf.Clamp01((float)i / sectCount);
        uv[idx + 2] = new Vector2(u, 0);
        uv[idx + 3] = new Vector2(u, 1);

        // fade colors out over time
        Color interpolatedColor = Color.Lerp(startColor, endColor, u);
        colors[idx + 0] = interpolatedColor;
        colors[idx + 1] = interpolatedColor;
        colors[idx + 2] = interpolatedColor;
        colors[idx + 3] = interpolatedColor;

        normals[idx + 0] = currentSection.forwardDir * testNormal;
        normals[idx + 1] = currentSection.forwardDir * testNormal;
        normals[idx + 2] = currentSection.forwardDir * testNormal;
        normals[idx + 3] = currentSection.forwardDir * testNormal;
    }

    // Generate triangles indices

    int[] triangles = new int[(sectCount - 1) * 6 + (sectCount - 2) * 3];
    int sectionNum = 1;
    int idx4, idx9;
    float cntStep = ((float)triangles.Length) / 9;
    for (int i = 0; i < cntStep; i++)
    {
        idx9 = i * 9;
        idx4 = i * 4;
        //Первый треугольник
        triangles[idx9 + 0] = idx4;
        triangles[idx9 + 1] = idx4 + 1;
        triangles[idx9 + 2] = idx4 + 2;
        //Второй треугольник
        triangles[idx9 + 3] = idx4 + 2;
        triangles[idx9 + 4] = idx4 + 1;
        triangles[idx9 + 5] = idx4 + 3;

        if (sectionNum + 1 == sectCount)
            break;
        //соединяющий треугольник
        if (sections[sectionNum].crossUp)
        {

            triangles[idx9 + 6] = idx4 + 2;
            triangles[idx9 + 7] = idx4 + 3;
            triangles[idx9 + 8] = idx4 + 4;

        }
        else
        {
            //соединяющий треугольник
            triangles[idx9 + 6] = idx4 + 2;
            triangles[idx9 + 7] = idx4 + 3;
            triangles[idx9 + 8] = idx4 + 5;

        }
        sectionNum++;

    }
    lock (lockOn)
    {
        this.vertices = vertices;
        this.colors = colors;
        this.uv = uv;
        this.triangles = triangles;
        this.normals = normals;
        needUpdate = true;
    }
}

protected Vector3 getVectorScale(){
    return new Vector3(1 / transform.localScale.x, 1/ transform.localScale.y, 1 / transform.localScale.z);
}

}

Предупреждаю код из проекта, поэтому могут быть какие то хвосты, вроде вызова внешних событий и т.п. Как использовать вроде бы есть в комментариях

2
  • подожду код, пожалуй) и спасибо за направление, в которое нужно искать) 27 мар 2016 в 19:56
  • 1
    @ЯрославМовчан добавил код
    – KingPeas
    28 мар 2016 в 4:15

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.