三维波的法线

时间:2014-04-30 05:24:35

标签: c# unity3d polynomial-math unityscript normals

问题:     我有一个函数来计算给定 X Z 坐标的波的 Y 值(高度)。此时我也需要法线,即此时切线/渐变的法线。

背景资料:

  • 我正在试图模拟海洋的波浪,这样我就可以拥有一艘受海浪影响的漂浮船,这样它就会来回摆动,并且能够左右摇摆。
  • 这是我为学校项目统一制作的游戏。
  • 我使用C#编写脚本,但Unity也接受JavaScript
  • 水是一个有多个顶点的平面,因此我的脚本会计算每个顶点的高度(此部分已经完成)。

到目前为止我有什么

using UnityEngine;
using System.Collections;

public class Weather : MonoBehaviour
{   
        //The height of the waves
        public float amplitude = 0.01f;
        //The number of waves
        public float frequency = 50f;
        //The speed the direction of the waves rotate
        public float directionChange;

        // Update is called once per frame, every frame it is rotated a small amount.
        //using transform.rotate allows for easy rotation and reference to its direction with transform.forward is automaticlly normalised.
        void FixedUpdate ()
        {
                //Rotates around the y axis
                transform.RotateAround (transform.position, Vector3.up, directionChange * Time.deltaTime);
        }   

        //Gets the height (y value) of the wave at an (x,z) position. At each frame the amplitude, time, frequency and direction are considered constant so that but these all change with between each frame.
        public float heightAt (float x, float z)
        {
                return amplitude * Mathf.Sin (Time.realtimeSinceStartup + x * frequency * transform.forward.x + z * frequency * transform.forward.z);
        }

        //This needs to use the same function as the heightAt(x, z) method so that the normal at a point can be calculated e.g. the normal at a point on top of the wave would be straight up
        public Vector3 normalAt (float x, float z)
        {
                return Vector3.up;
        }
}

我的研究发现了链条规则,我一直试图[不成功]使用它。 我遇到困难的是得到渐变的归一化向量(这样我就可以得到法线的归一化向量)

我需要找到法线以便我可以通过使用节点来计算船上的浮力,这些节点可以通过检查它们是否在水中来计算应用于其父对象(船)的力。 如果节点位于波浪之上,那么它将对船施加重力,如果在波浪下面,它将使用法线施加力,以便它被波浪推动。

希望我已经足够清楚,你可以理解。 感谢您阅读:)

1 个答案:

答案 0 :(得分:2)

嗯...应该是这样的:

public Vector3 normalAt (float x, float z)
{
    float argument = Time.realtimeSinceStartup + x * frequency * transform.forward.x + z * frequency * transform.forward.z;
    float nx = amplitude * frequency * transform.forward.x * Mathf.Cos(argument);
    float ny = -1.0f;
    float nz = amplitude * frequency * transform.forward.z * Mathf.Cos(argument);
    return new Vector3(nx, ny, nz).normalized; // Not sure about sign. Maybe you need to multiply the result by -1.
}
相关问题