我这边是要在角色脚下创建一个扇形区域。效果图如下:
?我用的版本是2.3.4,注意3.0以上版本接口不一样。
3.0以上版本可以参考社区一位大佬写的,我这边是用了他的顶点数据和UV。
出处:分享一个绘制扇形网格组件 - Creator 3.x - Cocos中文社区
import GameMgr from "../Mgrs/GameMgr";
const { ccclass, property } = cc._decorator;
@ccclass
/**
* 绘制扇形网格
*/
export class SectorComp extends cc.Component {
@property({ type: cc.Material })
public mat: cc.Material | null = null;
@property({
tooltip: "外圈半径"
})
public radius: number = 5;
@property({
tooltip: "内圈半径"
})
public innerRadius: number = 1;
@property({
tooltip: "扇形角度"
})
public angledegree: number = 60;
start() {
this.createMesh()
}
createMesh() {
const model = this.node.addComponent(cc.MeshRenderer)!;
const segments: number = Math.floor(this.angledegree / 4) + 1;
var positions: number[] = [];
// 组装顶点数据
var vertices_count: number = segments * 2 + 2;
var vertices: Array<cc.Vec3> = new Array<cc.Vec3>(vertices_count);
var angleRad: number = this.angledegree * cc.macro.RAD;
var angleCur: number = angleRad;
var angledelta: number = angleRad / segments;
for (var i = 0; i < vertices_count; i += 2) {
var cosA: number = Math.cos(angleCur);
var sinA: number = Math.sin(angleCur);
vertices[i] = new cc.Vec3(this.radius * cosA, 0, this.radius * sinA);
vertices[i + 1] = new cc.Vec3(this.innerRadius * cosA, 0, this.innerRadius * sinA);
angleCur -= angledelta;
positions.push(vertices[i].x);
positions.push(vertices[i].y);
positions.push(vertices[i].z);
positions.push(vertices[i + 1].x);
positions.push(vertices[i + 1].y);
positions.push(vertices[i + 1].z);
}
// 组装三角形数据
var indice_count: number = segments * 6;
var indices: Array<number> = new Array<number>(indice_count);
for (var i = 0, vi = 0; i < indice_count; i += 6, vi += 2) {
indices[i] = vi;
indices[i + 1] = vi + 3;
indices[i + 2] = vi + 1;
indices[i + 3] = vi + 2;
indices[i + 4] = vi + 3;
indices[i + 5] = vi;
}
// 组装UV数据
var uvs: number[] = [];
for (var i = 0; i < vertices_count; i++) {
var u = vertices[i].x / this.radius / 2 + 0.5
var v = vertices[i].z / this.radius / 2 + 0.5
uvs.push(u, v);
}
//@ts-ignore
let gfx = cc.gfx;
//创建Mesh
const mesh = new cc.Mesh();
//初始化格式
let vfmtPosColor = new gfx.VertexFormat([
{ name: gfx.ATTR_POSITION, type: gfx.ATTR_TYPE_FLOAT32, num: 3 },
{ name: gfx.ATTR_UV0, type: gfx.ATTR_TYPE_FLOAT32, num: 2 },
]);
mesh.init(vfmtPosColor,vertices_count,true);
//设置顶点位置
mesh.setVertices(gfx.ATTR_POSITION,positions);
//UV
mesh.setVertices(gfx.ATTR_UV0,uvs);
mesh.setIndices(indices);
model.mesh = mesh;
model.setMaterial(0,this.mat);
}
}
|