I really am struggling with how slow an inefficient the javascript sine and cosine functions are. I'm making a first person shooter out of p5.js webgl and it's really causing a ton of lag.
Can someone tell me how to find the sine/cosine of an angle with only one angle? or at least show me a more efficient way to do this?
So literally I'm trying to recreate the Math.cos and Math.sin functions to just simply run faster.
If your degrees are only full integer degrees in the range 0-359, you could cache the result of the sin/cos in an array, where the degrees is the index of the array:
const pi180 = (Math.PI/180);
const angles =[...new Array(360).fill(0)].map((_,i) => ({
cos: Math.cos(i * pi180),
sin: Math.sin(i * pi180)
}));
console.log(angles);
If you wanted for example the cos of 32 degrees it would be angles[32].cos
This is harder to do using radians, as you're dealing with floating point values and you'd need a way to either truncate or interpolate between values.
A short commentary on you believing cos/sine are your bottleneck: This is unlikely. Much more likely is that you're continually calling mathematical functions when it is unecessary. Check your code to make sure you only calculate things when they change, not on every keyframe of an animation and that you only invalidate parts of your code which has actually changed.