Make the code shorter in Unity3D with Vector3 and float value in 1 axis - unity3d

This is my code:
transform.localPosition = new Vector3(transform.localPosition.x, Mathf.PingPong(Time.time * movementSpeed, movementRange), transform.localPosition.z);
Can you help me to short it?
Like
transform.localPosition = Vector3.up * Mathf.PingPong(Time.time * movementSpeed, movementRange)
I am constantly encountering a Vector3 abbreviation of this form, but can't write this code any better

Perfect use-case for Extension Methods
public static class Vector3Extensions {
public static Vector3 SetY(this Vector3 vector, float y) {
//This works as-is because structs, such as Vector_ in Unity, are pass-by-value
vector.y = y;
return vector;
}
}
Usage:
//You have to assign the result of the method because, again, pass-by-value...
//..So the vector that was modified inside the method is a different object from the original
transform.localPosition = transform.localPosition.SetY(Mathf.PingPong(Time.time * movementSpeed, movementRange));
Your second example is functionally different from the first. In it, the X and Z will be zero instead of inheriting the original transform's values. If your intention is that, then your example's code is already pretty much as small as it gets, without another extension method to the Transform class, ie transform.SetLocalPositionY(y).
If you need inheritance of the X and Z values, AND using SetY would still be too verose to your liking, then use a Transform Extension Method as I said above:
public static class TransformExtensions {
public static void SetLocalPositionY(this Transform transform, float y) {
transform.localPosition = transform.localPosition.SetY(y);
}
}
Usage:
//Assignment not needed in this case, as transform is a class...
//..and assignment of localPosition is handled inside the extension method.
transform.SetLocalPositionY(Mathf.PingPong(Time.time * movementSpeed, movementRange));
There is a slight performance cost to extensions methods for struct types, due to the pass-by-value nature of structs. Which are the types being used in this case. But it's negligible in this case specifically, and should be negligible for all structs in general, if you are using structs correctly.
On pass-by-reference types, there should be no performance cost any different to any standard static method modifying the data.
Note that the operation does not need to be inline, and if you're willing to spread it across a few lines, you can use the same principle of the extension method, of modifying a cached clone of the original vector and then (re)assigning it back to the transform, to achieve this with shorter lines and without the extra struct instance from passing as parameter and then returning (one instance creation instead of two):
var localPos = transform.localPosition; //Creates temp/cached instance
localPos.y = Mathf.PingPong(Time.time * movementSpeed, movementRange); //Modification
transform.localPosition = localPos; //(Re)Assignment.
But with exception to cases requiring extreme performance, the extension will be fine. In fact, anything short of a case verified in the debugger, doing it this way just for the performance concern is going to be premature-optimization.

Related

making a variable equal a Arraylist value within a class (Processing)

Hi this is my first time making a question so hopefully i have done this right :)
In my code Im trying to make a Arraylist that is within a class that only holds floats so I made this: (some information is taken away to make it easier to read)
class object {
private ArrayList yc=new ArrayList<Float>();
private ArrayList xc=new ArrayList<Float>();
object(float xer,float yer,float rer){
xc.add(10.0);
x=xer;
y=yer;
r=rer;
}
void update(){
print(xc.get(0))
x=xc.get(0);
}
}
everything else except x=xc.get(0) works outside of the class this assignment works but inside the class it doesn't
hope this makes sense thanks.
It seems like when you initialised the variable xc you specified the type of the ArrayList to Float. However, when declaring xc, you did not specify the type.
When you try to assign variable x with xc.get(0), you are basically assigning any Object to variable x that was declared as a Float.
To solve this issue you can declare your variable xc specifying the type of the ArrayList: private ArrayList<Float> xc = new ArrayList<Float>();
Also, processing offers the helper class FloatList as well if this suits your program.
This should solve your issue, depending on the rest of your code.

How can I properly create invalid Vector3 in Unity?

I often need to pass invalid location to functions that optionally can use location (eg. RTS unit action). But this does not compile:
public abstract void CastSpell(Spell spell, Vector3 targetLocation = null);
So how can I make a proper invaid Vector3 to determine invalid/"don't care" locations? I've seen things like vector with -999999 coordinates - but that's a nasty trick that might cause bugs (eg. on huge maps).
I had a similar problem in the past, I found there was two solutions. The first solution was to create a wrapper for the class.
Class Vector3Wrapper
{
Vector3 vector;
}
Then I would simply set the Vector3Wrapper to null then if it wasnt null access its vector. A better method would be making it a Nullable type. A example is below.
http://unitypatterns.com/nullable-types/
public class Character : MonoBehaviour
{
//Notice the added "?"
Vector3? targetPosition;
void MoveTowardsTargetPosition()
{
//First, check if the variable has been assigned a value
if (targetPosition.HasValue)
{
//move towards targetPosition.Value
}
else
{
//targetPosition.Value is invalid! Don't use it!
}
}

Is the argout paradigm good practice in RenderScript?

Reflection classes in RenderScript contain functions that execute the kernels. These functions follow the out argument paradigm- one of their arguments an Allocation in which output is stored.
Is there a reason this is better practice than returning the output Allocation? (Should I follow suit and use out arguments in my RenderScript-related functions?)
For example, I have implemented the following helper class which wraps ScriptC_gradient and computes the gradient of a Bitmap. It can infer from the input Allocation what type the output Allocation should have, and thus hide the boilerplate necessary to set up the destination Allocation. Is there a reason to prefer one implementation of compute() over the other?
public class Gradient {
private RenderScript mRS;
private ScriptC_gradient mScript;
public Gradient(RenderScript RS) {
mRS = RS;
mScript = new ScriptC_gradient(mRS);
}
/* Out-argument implementation
*
* This closely mirrors RenderScript's kernel functions, but
* it requires the caller to write boilerplate to set up the
* destination Allocation.
*/
public void compute(Allocation elevation, Allocation gradient) {
mScript.invoke_setDimensions(elevation);
mScript.forEach_root(elevation, gradient);
}
/* Allocation-returning implementation
*
* This hides the boilerplate.
*/
public Allocation compute(Allocation elevation) {
Allocation gradient = Allocation.createTyped(mRS,
new Type.Builder(mRS,Element.F32_2(mRS))
.setX(elevation.getType().getX())
.setY(elevation.getType().getY())
.create(),
Allocation.USAGE_SCRIPT);
mScript.invoke_setDimensions(elevation);
mScript.forEach_root(elevation, gradient);
return gradient;
}
Yes, the reason to prefer the approach with the passed in Allocation for the output is memory reuse. Creating allocations is expensive and should not be done more than necessary.
The second method would also cause problems for "tiling" where you do multiple kernel launches to each fill out a part of an output allocation. As the output would be reallocated each time the previous contents would be lost (or have to be copied).

Trying to access variables from another script in unity (Not Homework)

I am currently playing around in Unity trying to make/test a 2D game. I keep getting the following error when I attempt to access CharacterMotor.playerx from inside camerafollow.js:
An instance of type "CharacterMotor" is required to access non static member "playerx"
Here are my two scripts:
camerafollow.js
#pragma strict
function Start () {
transform.position.x = CharacterMotor.playerx;
}
CharacterMotor.js
#pragma strict
#pragma implicit
#pragma downcast
public var playerx : float = transform.position.x;
You could change playerx to static, but I don't think that's what you want to do (there's probably only one player object, but this would prevent you from ever having multiple CharacterMotors). I think you want/need to retrieve the instance of CharacterMotor that is attached to this gameObject.
#pragma strict
function Start () {
var charMotor : CharacterMotor = gameObject.GetComponent(CharacterMotor);
transform.position.x = charMotor.playerx;
}
An instance of type "CharacterMotor" is required to access non static member "playerx"
The above error message describes precisely what is happening. You are just trying to access a variable without first creating an instance of it. Keep in mind that UnityScript != JavaScript.
To fix this issue, simply change
public var playerx : float = transform.position.x;
to
public static var playerx : float = transform.position.x;
Though this fixes your immediate problem I do not recommend continuing down this path. I suggest that you learn other aspects of the language first (such as classes) so that you can better organize and construct your data.
See: http://forum.unity3d.com/threads/34015-Newbie-guide-to-Unity-Javascript-(long)
CharacterMotor is the type, there can be multiple instantiations of your type in memory at the same time so when you call the type name you are not referencing any instance in memory.
to get an instance of the type that is connected to you current gameobject try this:
var charactorMotor : CharacterMotor = gameObject.getComponent("CharacterMotor");
Now you have access to that instances properties
transform.position.x = characterMotor.playerx;

scala game programming: advancing object position in a functional style

Long time java programmer slowly learning scala (loving it by the way), and I think my mind is still wrapping itself around the concept of writing things functionally. Right now I'm attempting to write a simple visualizer for some moving 2d textures. The imperative approach is simple enough, and I'm sure most of you will recognize this relatively ubiquitous block of code (stuff was changed to protect the innocent):
class MovingTexture(var position, var velocity) extends Renders with Advances {
def render : Unit = {...}
def advance(milliseconds : Float) : Unit = {
position = position + velocity * milliseconds
}
}
This code will work just fine, however it has tons of mutable state and its functions are replete with side effects. I can't let myself get away with this, there must be a better way!
Does anyone have an amazing, elegant, functional solution to this simple problem? Does anyone know of a source where I could learn more about solving these sorts of problems?
There's way more to this answer than can be fit in the space of one stackoverflow response, but the best and most complete answer to questions like this is to use something called Functional Reactive Programming. The basic idea is to represent each time-varying or interactive quantity not as a mutable variable, but rather as an immutable stream of values, one for each time quanta. The trick then is that while each value is a represented by a potentially infinite stream of values, the streams are lazily calculated (so that memory isn't taken up until needed), and stream values aren't looked at for time quanta in the past (so that the previous calculations may be garbage collected). The calculation is nicely functional and immutable, but the part of the calculation you are "looking at" changes with time.
This is all rather intricate, and combining streams like this is tricky, particularly if you wish to avoid memory leaks and have everything work in a thread-safe and efficient manner. There are a few Scala libraries that implement Functional Reactive Programming, but maturity isn't yet very high. The most interesting is probably scala.react, described here .
Games are often high-performance affairs, in which case you may find that mutable state is just the thing you need.
However, in this case, there are a couple of simple solutions:
case class MovingTexture(position: VecXY, velocity: VecXY) extends Renders with Advances {
def advance(ms: Float) = copy(position = position + ms*velocity
def accelerate(acc: Float, ms: Float) = copy(velocity = velocity + ms*acc)
...
}
That is, instead of having your classes update themselves, have them return new copies of themselves. (You can see how this could get expensive quickly. For Tetris, no big deal. For Crysis? Maybe not so smart.) This seems like it just pushes the problem back one level: now you need a var for the MovingTexture, right? Not at all:
Iterator.iterate(MovingTexture(home, defaultSpeed))(_.advance(defaultStep))
This will produce an endless stream of position updates in the same direction. You can do more complicated things to mix in user input or whatnot.
Alternatively, you can
class Origin extends Renders {
// All sorts of expensive stuff goes here
}
class Transposed(val ori: Origin, val position: VecXY) extends Renders with Advances {
// Wrap TextureAtOrigin with inexpensive methods to make it act like it's moved
def moving(vel: VecXY, ms: Float) = {
Iterator.iterate(this).(tt => new Transposed(tt.ori, position+ms*vel))
}
}
That is, have heavyweight things never be updated and have lighter-weight views of them that make them look as though they've changed in the way that you want them changed.
There's a brochure called "How to design worlds" (by the authors of "How to design programs") which goes into some length about a purely functional approach to programming interactive applications.
Basically, they introduce a "world" (a datatype that contains all the game state), and some functions, such as "tick" (of type world -> world) and "onkeypress" (of type key * world -> world). A "render" function then takes a world and returns a scene, which is then passed to the "real" renderer.
Here's a sample of some code I've been working on that uses the approach of returning a copy rather than mutating state directly. The nice thing about this kind of approach, on the server side at least, is that it enables me to easily implement transaction-type semantics. If something goes wrong while doing an update, it's trivial for me to still have everything that was updated in a consistent state.
The code below is from a game server I'm working on, which does something similar to what you're doing, it's for tracking objects that are moving around in time slices. This approach isn't as spectacular as what Dave Griffith suggests, but it may be of some use to you for contemplation.
case class PosController(
pos: Vector3 = Vector3.zero,
maxSpeed: Int = 90,
velocity: Vector3 = Vector3.zero,
target: Vector3 = Vector3.zero
) {
def moving = !velocity.isZero
def update(elapsed: Double) = {
if (!moving)
this
else {
val proposedMove = velocity * elapsed
// If we're about to overshoot, then stop at the exact position.
if (proposedMove.mag2 > pos.dist2(target))
copy(velocity = Vector3.zero, pos = target)
else
copy(pos = pos + proposedMove)
}
}
def setTarget(p: Vector3) = {
if (p == pos)
this
else {
// For now, go immediately to max velocity in the correct direction.
val direction = (p - pos).norm
val newVel = direction * maxSpeed
copy(velocity = direction * maxSpeed, target = p)
}
}
def setTargetRange(p: Vector3, range: Double) = {
val delta = p - pos
// Already in range?
if (delta.mag2 < range * range)
this
else {
// We're not in range. Select a spot on a line between them and us, at max range.
val d = delta.norm * range
setTarget(p - d)
}
}
def eta = if (!moving) 0.0 else pos.dist(target) / maxSpeed
}
One nice thing about case classes in Scala is that they create the copy() method for you-- you just pass in which parameters have changed, and the others retain the same value. You can code this by hand if you're not using case classes, but you need to remember to update the copy method whenever you change what values are present in the class.
Regarding resources, what really made a difference for me was spending some time doing things in Erlang, where there is basically no choice but to use immutable state. I have two Erlang books I worked through and studied every example carefully. That, plus forcing myself to get some things done in Erlang made me a lot more comfortable with working with immutable data.
This series of short articles helped me as a beginner, in thinking Functionally in solving programming problems. The game is Retro (Pac Man), but the programmer is not.
http://prog21.dadgum.com/23.html