I'm making a game in c# and I'm trying to make my texture move. I need some help and advice to make the texture move. This is what I've used so far.
public float InitialTime { get; set; }
public Vector2 InitialPosition { get; set; }
public Vector2 InitialVelocity { get; set; }
public Vector2 Position(GameTime time)
{
float t = (float)time.TotalGameTime.TotalSeconds = InitialTime;
return InitialPosition + t * InitialVelocity;
}
on the 'float t' line, it comes up with the following error,
Error CS0131 The left-hand side of an assignment must be a variable,
property or indexer
Your problem is because of this:
float t = (float)time.TotalGameTime.TotalSeconds = InitialTime;
Both sides of an assignment operation need to have valid syntax. If you were to isolate the second assignment, it would look like this:
(float)time.TotalGameTime.TotalSeconds = InitialTime;
Which is not only invalid syntax, but it also makes little sense.
I imagine that the reason you are doing the cast is because TotalSeconds and InitialTime are doubles and you need to cast them to a float. There are two ways to accomplish this.
You can either split up the assignment onto two different lines:
time.TotalGameTime.TotalSeconds = InitialTime;
float t = (float)time.TotalGameTime.TotalSeconds;
Or, if you insist on doing this on a single line, use parentheses to group your operations:
float t = (float)(time.TotalGameTime.TotalSeconds = InitialTime);
EDIT:
Then again, I've been assuming that the double assignment was intentional. What you may have meant to do was to subtract InitialTime from your TotalTime to get the current time stamp. In that case, it's just a simple fix of a typo:
float t = (float)(time.TotalGameTime.TotalSeconds - InitialTime);
(Note that if TotalSeconds and InitialTime are doubles, you will need to use parentheses to cast the operation to a float, as I have done.)
Related
I'm learning C# and Unity3D for a few months and now I stumbled on a logic, which hopefully somebody can describe to me.
(I already googled for hours and even looked up if other languages use enums that way.)
This code is from a free asset from the unity asset store, which I try to anatomize.
Everything is fine and understandable for me, but then it comes to the functions GetSliderData() and SetSliderData().
My Question: How does the modulo part works?
Why dividing anyway, when it comes to getting and setting values? Or is it some kind of syntax, like the lambda expression "=>" which is not ">="(less or equal sign)
Thank you in advance for your time!
Dom
public class SliderData : ScriptableObject
{
// Data storage
public List<float> sliderData;
/* Use a single enum as retrieval label for any slider by using a splitter
* value as interval. */
private const int ENUM_INTERVAL = 16;
public enum SliderField
{
// Customizer sliders
DEPTH_MIN,
DEPTH_MAX,
PERLIN_SPEED,
PERLIN_LEVEL,
ZONE_PERLIN_SPEED,
ZONE_PERLIN_LEVEL,
MAP_PERLIN_SPEED,
MAP_PERLIN_LEVEL,
}
/// Retrieves the value of the slider belonging to the given field constant.
public float GetSliderData(SliderField field)
{
return sliderData[(int)field % ENUM_INTERVAL];
}
/// Sets the value of the slider belonging to the given field constant.
public void SetSliderData(SliderField field, float value)
{
sliderData[(int)field % ENUM_INTERVAL] = value;
}
}
The % seems to have the purpose of wrap-around the given field value onto the existing indices of the sliderData list.
If the value reaches/exceeds the ENUM_INTERVAL it will instead start over from 0.
For your methods indeed this seems a bit redundant if using the enum values since there are only 8 of them anyway. But it could be triggered via type casting e.g. (SliderField)17 .. but why would someone do that?
Anyway this seems to simply assume that the sliderData list contains at least 16 elements ...
In general to be honest I wouldn't use such a structure but rather store and access the values via actual fields instead of this kind of "dictionary" List.
Ofcourse depends on the use-case and how exactly your asset is used later. It seems there is some behavior involved you didn't share here.
But instead of going through the magic enum and list indices - why not simply have
public class SliderData : ScriptableObject
{
public float DEPTH_MIN;
public float DEPTH_MAX;
public float PERLIN_SPEED;
public float PERLIN_LEVEL;
public float ZONE_PERLIN_SPEED;
public float ZONE_PERLIN_LEVEL;
public float MAP_PERLIN_SPEED;
public float MAP_PERLIN_LEVEL;
}
Im trying to create a ufloat class/struct in c#. It's more of a challenge for me, but would help me control some values in code. After trying a couple of approaches, I finally have one that seems to work:
public struct ufloat
{
public float Value
{
get{ return value; }
set
{
if(value < 0)
{
this.value = 0;
}
else
{
this.value = Math.Abs(value);
}
}
}
}
The problem is, I want it to behave like a typical basic type:
ufloat n = 5;
n += 1;
After some thinking I tried to overload the '=' operator, but it is not possible. Now I am out of ideas. This is why I ask, how can you change this:
ufloat x; x.value = 1;
to this:
ufloat x = 0; x = 1;
?
(Sorry if I am losing something really easy, but I am a self-taught "programmer" and I am pretty new to c#. I learnt c++ at first, and going from lower to higher level isn't easy for me.)
You can't overload the = operator, but you can overload the + operator, and then the += operator (which I believe you meant instead of =+) will work in a reasonably obvious way. You'd also need to add an implicit conversion from float to your struct though.
I would strongly advise not making the struct mutable though - instead, let the + operator return a new value. That will make it behave like every other primitive type, and like most other structs. I'd also rename it to USingle to follow the normal .NET naming conventions (where Single is the CLR name for float). You can't add your own C# alias for a name like float is for Single though.
I suspect your type will want:
A constructor accepting a float
Conversions to and from float (note that normally implicit conversions shouldn't throw exceptions - you may want to ignore that, but I'm not sure...)
Overloads for the arithmetic operators (+, -, * and /)
Overrides of ToString, Equals and GetHashCode
Implementation of IComparable<USingle> and IEquatable<USingle>
You should think about what you want to happen if you add two values which are "large positive floats" together - is the intention that your new type is able to support larger positive values than float can, or is it just "float but always non-negative"?
You can not overload = operator but you may write implicit casts, for example this one is for casting an int:
public class ufloat
{
public float value { get; }
public ufloat(int val) { value = Math.Abs(val); }
public static implicit operator ufloat(int input)
{
return new ufloat(input);
}
}
Now if you assign an int value to it, it will implicitly be converted to ufloat:
ufloat x = -5;
I was working on a code and got an issue. What I'm trying to do is to use InputField in unity, then use that number to multiply by existing float. Here's what I got so far:
private float finePrice = 0.0001f;
public InputField enterValue;
public Text estimatedValue;
estimatedValue.text = string.Format ("{0}", finePrice * enterValue);
Error I'm getting:
Operator `*' cannot be applied to operands of type `float' and `UnityEngine.UI.InputField'
In my understanding is that I cannot multiply string (inputfield) to float? I tried changing Content Type of Input Field to "Decimal Number" but I'm getting the same error. Tried googling it, nothing to be found. Please help? I'm lost.
You need to get the content of the InputField using the text property, and then convert that content to float because it's a string:
private float finePrice = 0.0001f, valueEntered;
public InputField enterValue;
public Text estimatedValue;
if(float.TryParse(enterValue.text, out valueEntered))
{
estimatedValue.text = (finePrice * valueEntered).ToString();
}
else
{
estimatedValue.text = "Please enter a float value";
}
Note I've used float.TryParse so that if the user entered a value that can't be converted to float you will simply get false instead of an exception you would get if you used float.Parse. Also, I've changed your string.Format to simply ToString - There is no point of using string.Format in cases like this.
Like Zohar mentioned, InputField.text is a string and you need to convert that to float before you multiply it with your other float.
I left my own answer because I think it's better to use float.Parse to make that conversion and pass in CultureInfo.InvariantCulture.NumberFormat to the second parameter as you don't know what culture the user's device is set to.
Convert InputField value to float
float inputInFloatFormat = float.Parse(enterValue.text, CultureInfo.InvariantCulture.NumberFormat);
Multiply by your float finePrice variable
float multiplyResult = inputInFloatFormat * finePrice;
Display result on your text component(Convert multiplyResult to string) then display it
estimatedValue.text = multiplyResult.ToString();
I have a float array in C# that stores data. However, I need to cast the data to structures like Vector2, Vector3 etc. The structures are holding only floats, so there is no data type conversion in the matter of bytes, only in access.
Eg.:
struct Vector3
{
public float x;
public float y;
public float z;
//plus some methods
}
I can copy the whole float array to the struct one manually by creating a new array, but that is kind of slow for big ones. I have tried to do conversion in unsafe code, but using generic is not working and creating special method for every struct I have is kind of "weird".
In C++ I have something like this:
float * arrayFloat = ....
Vector3 * arrayVector3 = reinterpret_cast<Vector3 *>(arrayFloat);
but that is not an option in C#...
Any ideas how to achieve this, or how to change the design?
you could add a constructor to your struct:
struct Vector3
{
public float x;
public float y;
public float z;
public Vector3(float[] vals)
{
if(vals.Length != 3)
throw new ArgumentException();
x = vals[0]; y = vals[1]; z = vals[2];
}
}
...elsewhere
float[] myFloats = { 0.0f, 1.1f, 2.2f };
var myVec = new Vector3(myFloats);
if you're asking if there is something that lets you do this without any work, the answer is no. Any conversion from an array to a struct of your choosing has to be implemented by you, preferably in your struct.
I believe this can work for your struct, using .NET Core 2.1's MemoryMarshal methods.
My answer here describes how. The essence is:
var vectors = MemoryMarshal.Cast<float, Vector3>(floatArray.AsSpan());
var firstVector = vectors[0];
This is C#'s equivalent of a reinterpret cast.
I'm new to C#, and i was struggling with the same problem, what i found useful is to use an enumerator which lazily converts every element on access:
IEnumerator<Vector3> Positions()
{
for (int i = 0; i < _positions.Length / 3; ++i)
{
yield return new Vector3(_positions[3*i],
_positions[3*i+1],
_positions[3*i+2]);
}
}
With this you don't need to copy the whole array and compiler most likely will not create new object of type Vector3 in memory instead it will use registers.
I wrote a code for checking typecasting in C#. The following code:
using System;
class Convert{
public static void Main(){
double a=14.25,b=26.12;
var z=(int)(a*b);
Console.WriteLine("z= "+z);
Console.ReadKey(true);
}
}
Gave output:
z=372
But when i modified the code a bit then i got a big difference between the value of z earlier and after modification.
using System;
class Convert{
public static void Main(){
double a=14.25,b=26.12;
var z=(int)a*b; // Modified part
Console.WriteLine("z= "+z);
Console.ReadKey(true);
}
}
Gave output:
z=365.68
I don't understand that why is there so much difference after removing the brackets from the original code?
Without the outer parentheses, the (int) cast applies to a only.
Therefore, you end up multiplying a truncated integer by a normal double, and type inference turns var into double.
With the parentheses, the cast applies to the result of the multiplication. Therefore, the entire result gets truncated, and type inference turns var into int.
Thus, changing var to double would have no effect on either example. (in the second case, it would assign the truncated int to a double variable)
Changing var to int would turn the second example into a compiler error.
brackets set prioryty
var z=(int)(a*b);//(a*b) cast to int
var z=(int)a*b;//a cast to int and myltiply with b
the priority of conversation operation () is bigger than multiply priority.
in first case you have:
double tmp = a*b;
int z = (int)tmp;
and in second:
int tmp = (int)a;
double z = tmp * b;
in the line
var z=(int)a*b;
a is being converted into an int before it is being multiplied. So it is going to be 14*26.12. Where in the 2nd case, you are multiplying a*b and converting the result into an int afterward.