本节书摘来自异步社区《Android 应用案例开发大全(第二版)》一书中的第2章,第2.8节工具常量类,作者 吴亚峰 , 于复兴 , 杜化美,更多章节内容可以访问云栖社区“异步社区”公众号查看
2.8 工具常量类Android 应用案例开发大全(第二版)上一节完成了线程相关类的详细介绍,这一节将对本案例工具类Vector3f的开发进行介绍,Vector3f是一个向量类,在该类里进行了向量的基本运算,如向量的加法、减法、求模等,具体代码如下所示。
1 package com.bn.ld.Vectors; 2 public class Vector3f { 3 public float x; // 向量中的_x_ 4 public float y; // 向量中的_y_ 5 public float z; // 向量中的_z_ 6 public Vector3f(float x, float y, float z) { 7 this.x = x; 8 this.y = y; 9 this.z = z; 10 } 11 public float Vectormodule() { // 获取向量的模长 12 float Vectormodule = (float) Math.sqrt(this.x * this.x + this.y* this.y + this.z * this.z); 13 return Vectormodule; 14 } 15 public void plus(Vector3f Vector) { // 向量的加法 16 this.x += Vector.x 17 this.y += Vector.y; 18 this.z += Vector.z; 19 } 20 public void ChangeStep(float Length) { // 向量的缩放 21 this.x = this.x / Length; 22 this.y = this.y / Length; 23 this.z = this.z / Length; 24 } 25 public void getforce(float weight) { // 获取力的大小 26 if (weight != 0) { 27 this.x = this.x / weight; 28 this.y = this.y / weight; 29 this.z = this.z / weight; 30 }} 31 public Vector3f cutGetforce(Vector3f Vector) { // 恒力的归一化 32 Vector3f Vtr = new Vector3f(this.x - Vector.x, this.y - Vector.y,this.z - Vector.z);//向量减法 33 float Length = Vtr.Vectormodule(); // 获取模长 34 if (Length != 0){ 35 Vtr.ChangeStep(Length); // 向量归一化 36 } 37 return Vtr; 38 } 39 public Vector3f cutPc(Vector3f Vector){ 40 Vector3f Vtr = new Vector3f(this.x - Vector.x, this.y - Vector.y,this.z - Vector.z);//向量减法 41 return Vtr; 42 } 43 public Vector3f cut(Vector3f Vector, float MinDistances) { 44 Vector3f Vtr = new Vector3f(this.x - Vector.x, this.y - Vector.y,this.z - Vector.z);//向量减法 45 float Length = Vtr.Vectormodule(); // 求模 46 if (Length <= MinDistances) { 47 if (Length != 0) { 48 Vtr.ChangeStep(Length * Length); // 向量归一化 49 }} else { // 两条鱼的距离超出一定范围力消失 50 Vtr.x = 0; // 将_x_轴的力设为零 51 Vtr.y = 0; // 将_y_轴的力设为零 52 Vtr.z = 0; // 将_z_轴的力设为零 53 } 54 return Vtr; 55 }}第1~24行依次为求向量的模,以及向量的加减法,和向量的归一化。向量的加法主要用在鱼的速度与鱼受到的力相加得到新的速度或鱼的位移与鱼的速度相加得到新的位移等方面。第25~42行分别为获得了力的大小,进行力的减法与力的归一化的方法。力的大小是与鱼的质量(力的缩放比)成反比的。第43~55行是计算两条鱼之间的力的方法。先计算出两条鱼之间的距离判断是否小于阈值,如果小于阈值则两条鱼之间产生力的作用并且力的大小与两条鱼之间的距离成反比。当两条鱼之间的距离超出一定范围之后则两条鱼之间的力会消失。
相关资源:Android开发实例大全源码第一部分